xref: /btstack/src/hci.c (revision ebde8a6099b606ea3bcff7dd4307f3948e58eabe)
11f504dbdSmatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "hci.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
411f504dbdSmatthias.ringwald  *  hci.c
421f504dbdSmatthias.ringwald  *
431f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
441f504dbdSmatthias.ringwald  *
451f504dbdSmatthias.ringwald  */
461f504dbdSmatthias.ringwald 
477907f069SMatthias Ringwald #include "btstack_config.h"
4828171530Smatthias.ringwald 
497f2435e6Smatthias.ringwald 
5006b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
51aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
528f2a52f4SMatthias Ringwald #include "btstack_run_loop_embedded.h"
53a484130cSMatthias Ringwald #endif
5406b9e820SMatthias Ringwald #endif
55a484130cSMatthias Ringwald 
564a3574a1SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
57d0b87befSMatthias Ringwald #include "../port/ios/src/btstack_control_iphone.h"
584a3574a1SMatthias Ringwald #endif
594a3574a1SMatthias Ringwald 
60a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
61472a5742SMatthias Ringwald #include "gap.h"
6221debf25SMatthias Ringwald #include "ble/le_device_db.h"
6345c102fdSMatthias Ringwald #endif
6445c102fdSMatthias Ringwald 
6593b8dc03Smatthias.ringwald #include <stdarg.h>
6693b8dc03Smatthias.ringwald #include <string.h>
675838a2edSMatthias Ringwald #include <inttypes.h>
687f2435e6Smatthias.ringwald 
6916ece135SMatthias Ringwald #include "btstack_debug.h"
700e2df43fSMatthias Ringwald #include "btstack_event.h"
714a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
724a3574a1SMatthias Ringwald #include "btstack_memory.h"
7361f37892SMatthias Ringwald #include "bluetooth_company_id.h"
741cfb383eSMatthias Ringwald #include "bluetooth_data_types.h"
754a3574a1SMatthias Ringwald #include "gap.h"
764a3574a1SMatthias Ringwald #include "hci.h"
774a3574a1SMatthias Ringwald #include "hci_cmd.h"
78d8905019Smatthias.ringwald #include "hci_dump.h"
791cfb383eSMatthias Ringwald #include "ad_parser.h"
8093b8dc03Smatthias.ringwald 
812b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
822b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_NUM
832b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
842b838201SMatthias Ringwald #endif
852b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_LEN
862b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
872b838201SMatthias Ringwald #endif
882b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_NUM
892b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
902b838201SMatthias Ringwald #endif
912b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_LEN
922b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
932b838201SMatthias Ringwald #endif
942b838201SMatthias Ringwald #endif
951b0e3922Smatthias.ringwald 
96aa81e641SMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
97aa81e641SMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
98aa81e641SMatthias Ringwald #endif
99aa81e641SMatthias Ringwald 
1001e20a53eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
1011e20a53eSMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT."
1021e20a53eSMatthias Ringwald #endif
1031e20a53eSMatthias Ringwald 
104169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
10562473419SMatthias Ringwald 
10662473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
107659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
10862473419SMatthias Ringwald #endif
109ee091cf1Smatthias.ringwald 
1101cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1111cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1121cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1131cfb383eSMatthias Ringwald #endif
1141cfb383eSMatthias Ringwald 
115f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
116f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN       0x01
117f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX       0x30
118beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE         0x00
119beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
120beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE       0x81
121beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
122beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
123f5875de5SMatthias Ringwald 
124b7f1ee76SMatthias Ringwald // GAP Remote Name Request
125b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
126b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
127b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
128b7f1ee76SMatthias Ringwald 
1290a51f88bSMatthias Ringwald // GAP Pairing
1300a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1310a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1320a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1330a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1340a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1350a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1360a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
137cc15bb2cSMatthias Ringwald #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
1380a51f88bSMatthias Ringwald 
139b83d5eabSMatthias Ringwald // prototypes
14035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
141758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
14235454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled);
14335454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
14435454696SMatthias Ringwald static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
14567aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
14635454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
14735454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
148a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
14935454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
150ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
15196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
15252db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
1539784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
15452db98b2SMatthias Ringwald #endif
1551cfb383eSMatthias Ringwald 
1567586ee35S[email protected] static int  hci_power_control_on(void);
1577586ee35S[email protected] static void hci_power_control_off(void);
1586da48142SSean Wilson static void hci_state_reset(void);
159fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
160fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
161b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
162b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
163b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
164b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
165b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
16695d71764SMatthias Ringwald static void hci_run(void);
16795d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
16895d71764SMatthias Ringwald static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
1696a5ffed8SMatthias Ringwald 
1706a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
171f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
1726a5ffed8SMatthias Ringwald #endif
1735d509858SMatthias Ringwald 
174a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
175e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
17639677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
177384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
178667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
1799c77c9dbSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void);
1805d509858SMatthias Ringwald #endif
181d70217a2SMatthias Ringwald #endif
182758b46ceSmatthias.ringwald 
18306b35ec0Smatthias.ringwald // the STACK is here
1843a9fb326S[email protected] #ifndef HAVE_MALLOC
1853a9fb326S[email protected] static hci_stack_t   hci_stack_static;
1863a9fb326S[email protected] #endif
1873a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
18816833f0aSmatthias.ringwald 
1891c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
19063168530SMatthias Ringwald // default name
19163168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
19263168530SMatthias Ringwald 
19366fb9560S[email protected] // test helper
19466fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
1951c9e5e9dSMatthias Ringwald #endif
19666fb9560S[email protected] 
19796a45072S[email protected] /**
19896a45072S[email protected]  * create connection for given address
19996a45072S[email protected]  *
20096a45072S[email protected]  * @return connection OR NULL, if no memory left
20196a45072S[email protected]  */
202667ba9d1SMatthias Ringwald static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){
2031a06f663S[email protected]     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
204bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
20596a45072S[email protected]     if (!conn) return NULL;
206058e3d6bSMatthias Ringwald     bd_addr_copy(conn->address, addr);
2072dceb1d6SMatthias Ringwald     conn->role = HCI_ROLE_INVALID;
20896a45072S[email protected]     conn->address_type = addr_type;
20996a45072S[email protected]     conn->con_handle = 0xffff;
2108daf94bcSMatthias Ringwald     conn->authentication_flags = AUTH_FLAG_NONE;
21196a45072S[email protected]     conn->bonding_flags = 0;
21296a45072S[email protected]     conn->requested_security_level = LEVEL_0;
21352db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
21488a03c8dSMatthias Ringwald     conn->request_role = HCI_ROLE_INVALID;
215140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = 0xffff;
216965a4ccfSMatthias Ringwald     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
217e9f98c4aSMatthias Ringwald     conn->link_key_type = INVALID_LINK_KEY;
21891a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
21991a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
22096a45072S[email protected]     hci_connection_timestamp(conn);
22152db98b2SMatthias Ringwald #endif
22296a45072S[email protected]     conn->acl_recombination_length = 0;
22396a45072S[email protected]     conn->acl_recombination_pos = 0;
224ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
225760b20efSMatthias Ringwald 
226da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
227b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
228b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
229b90f6e0aSMatthias Ringwald #endif
2300f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2310f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
2320f3b27c5SMatthias Ringwald #endif
233665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
23496a45072S[email protected]     return conn;
23596a45072S[email protected] }
23666fb9560S[email protected] 
237da886c03S[email protected] 
238da886c03S[email protected] /**
239da886c03S[email protected]  * get le connection parameter range
240da886c03S[email protected] *
241da886c03S[email protected]  * @return le connection parameter range struct
242da886c03S[email protected]  */
2434ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
2444ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
245da886c03S[email protected] }
246da886c03S[email protected] 
247da886c03S[email protected] /**
248da886c03S[email protected]  * set le connection parameter range
249da886c03S[email protected]  *
250da886c03S[email protected]  */
251da886c03S[email protected] 
2524ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
2534ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
254da886c03S[email protected] }
255da886c03S[email protected] 
256da886c03S[email protected] /**
25773cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
25873cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
25973cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
26073cd8a2aSMatthias Ringwald  * @param conn_latency
26173cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
26273cd8a2aSMatthias Ringwald  * @returns 1 if included
26373cd8a2aSMatthias Ringwald  */
26473cd8a2aSMatthias Ringwald int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
26573cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
26673cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
26773cd8a2aSMatthias Ringwald 
26873cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
26973cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
27073cd8a2aSMatthias Ringwald 
27173cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
27273cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
27373cd8a2aSMatthias Ringwald 
27473cd8a2aSMatthias Ringwald     return 1;
27573cd8a2aSMatthias Ringwald }
27673cd8a2aSMatthias Ringwald 
27773cd8a2aSMatthias Ringwald /**
2782b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
2792b6ab3e6SMatthias Ringwald  * @note: default: 1
2802b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
2812b6ab3e6SMatthias Ringwald  */
282d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2832b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
2842b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
2852b6ab3e6SMatthias Ringwald }
286d4e4907bSMatthias Ringwald #endif
2872b6ab3e6SMatthias Ringwald 
2882b6ab3e6SMatthias Ringwald /**
289da886c03S[email protected]  * get hci connections iterator
290da886c03S[email protected]  *
291da886c03S[email protected]  * @return hci connections iterator
292da886c03S[email protected]  */
293da886c03S[email protected] 
294665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
295665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
296da886c03S[email protected] }
297da886c03S[email protected] 
29897addcc5Smatthias.ringwald /**
299ee091cf1Smatthias.ringwald  * get connection for a given handle
300ee091cf1Smatthias.ringwald  *
301ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
302ee091cf1Smatthias.ringwald  */
3035061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
304665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
305665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
306665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
307665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
3083ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
309da886c03S[email protected]             return item;
310ee091cf1Smatthias.ringwald         }
311ee091cf1Smatthias.ringwald     }
312ee091cf1Smatthias.ringwald     return NULL;
313ee091cf1Smatthias.ringwald }
314ee091cf1Smatthias.ringwald 
31596a45072S[email protected] /**
31696a45072S[email protected]  * get connection for given address
31796a45072S[email protected]  *
31896a45072S[email protected]  * @return connection OR NULL, if not found
31996a45072S[email protected]  */
320667ba9d1SMatthias Ringwald hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
321665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
322665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
323665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
324665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
32596a45072S[email protected]         if (connection->address_type != addr_type)  continue;
32696a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
32762bda3fbS[email protected]         return connection;
32862bda3fbS[email protected]     }
32962bda3fbS[email protected]     return NULL;
33062bda3fbS[email protected] }
33162bda3fbS[email protected] 
3323e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
3333e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
3343e5e0926SMatthias Ringwald }
33552db98b2SMatthias Ringwald 
336228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
337228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
338228e430cSMatthias Ringwald }
339228e430cSMatthias Ringwald 
34052db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
34152db98b2SMatthias Ringwald 
342ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
343ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
344ee752bb8SMatthias Ringwald     int connections = 0;
345ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
346ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
347ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
348ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
349ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
350ee752bb8SMatthias Ringwald         connections++;
351ee752bb8SMatthias Ringwald     }
352ee752bb8SMatthias Ringwald     return connections;
353ee752bb8SMatthias Ringwald }
354ee752bb8SMatthias Ringwald #endif
355ee752bb8SMatthias Ringwald 
356ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
35791a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
358aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
359528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
360c785ef68Smatthias.ringwald         // connections might be timed out
361c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
362c785ef68Smatthias.ringwald     }
363f316a845SMatthias Ringwald #else
364c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
3655f26aadcSMatthias Ringwald         // connections might be timed out
3665f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
3675f26aadcSMatthias Ringwald     }
3685f26aadcSMatthias Ringwald #endif
369c785ef68Smatthias.ringwald }
370ee091cf1Smatthias.ringwald 
371ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
372aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
373528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
374f316a845SMatthias Ringwald #else
375528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
3765f26aadcSMatthias Ringwald #endif
377ee091cf1Smatthias.ringwald }
378ee091cf1Smatthias.ringwald 
37943bfb1bdSmatthias.ringwald /**
38080ca58a0Smatthias.ringwald  * add authentication flags and reset timer
38196a45072S[email protected]  * @note: assumes classic connection
3822e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
3837fde4af9Smatthias.ringwald  */
3847fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
3857fde4af9Smatthias.ringwald     bd_addr_t addr;
386724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
387f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3887fde4af9Smatthias.ringwald     if (conn) {
38928ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
39080ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
3917fde4af9Smatthias.ringwald     }
3927fde4af9Smatthias.ringwald }
3937fde4af9Smatthias.ringwald 
3941714cbbdSMatthias Ringwald static bool hci_pairing_active(hci_connection_t * hci_connection){
3958daf94bcSMatthias Ringwald     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
3961714cbbdSMatthias Ringwald }
3971714cbbdSMatthias Ringwald 
3981714cbbdSMatthias Ringwald static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
3991714cbbdSMatthias Ringwald     if (hci_pairing_active(hci_connection)) return;
4001714cbbdSMatthias Ringwald     if (ssp){
4018daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
4021714cbbdSMatthias Ringwald     } else {
4038daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
4041714cbbdSMatthias Ringwald     }
4051714cbbdSMatthias Ringwald     // if we are initiator, we have sent an HCI Authenticate Request
4061714cbbdSMatthias Ringwald     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
4071714cbbdSMatthias Ringwald 
4085a561920SMatthias Ringwald     // if we are responder, use minimal service security level as required level
4095a561920SMatthias Ringwald     if (!initiator){
410acadfdd0SMatthias Ringwald         hci_connection->requested_security_level = (gap_security_level_t) btstack_max((uint32_t) hci_connection->requested_security_level, (uint32_t) hci_stack->gap_minimal_service_security_level);
4115a561920SMatthias Ringwald     }
4125a561920SMatthias Ringwald 
4135a561920SMatthias Ringwald     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
41477208d90SMatthias Ringwald 
41577208d90SMatthias Ringwald     uint8_t event[12];
41677208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_STARTED;
41777208d90SMatthias Ringwald     event[1] = 10;
418bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
4194159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
42077208d90SMatthias Ringwald     event[10] = (uint8_t) ssp;
42177208d90SMatthias Ringwald     event[11] = (uint8_t) initiator;
42277208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4231714cbbdSMatthias Ringwald }
4241714cbbdSMatthias Ringwald 
4251714cbbdSMatthias Ringwald static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
4263c439ac4SMatthias Ringwald     hci_connection->requested_security_level = LEVEL_0;
4271714cbbdSMatthias Ringwald     if (!hci_pairing_active(hci_connection)) return;
4288daf94bcSMatthias Ringwald     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
4291714cbbdSMatthias Ringwald     log_info("pairing complete, status %02x", status);
43077208d90SMatthias Ringwald 
43177208d90SMatthias Ringwald     uint8_t event[12];
43277208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_COMPLETE;
43377208d90SMatthias Ringwald     event[1] = 9;
434bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
4354159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
43677208d90SMatthias Ringwald     event[10] = status;
43777208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4381714cbbdSMatthias Ringwald }
4391714cbbdSMatthias Ringwald 
44080ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
4415061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
44280ca58a0Smatthias.ringwald     if (!conn) return 0;
4431714cbbdSMatthias Ringwald     return (int) hci_pairing_active(conn);
44480ca58a0Smatthias.ringwald }
44580ca58a0Smatthias.ringwald 
44615a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
44755597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
4482bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
449a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
450c12e46e7Smatthias.ringwald }
45155597469SMatthias Ringwald 
45255597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
45355597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
4542bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
45555597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
456c12e46e7Smatthias.ringwald }
4571b6fb31bSMatthias Ringwald 
458e8ad470fSMatthias Ringwald bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
459e8ad470fSMatthias Ringwald 	if (!hci_stack->link_key_db) return false;
46076b0318eSMatthias Ringwald 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
46176b0318eSMatthias Ringwald 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
46276b0318eSMatthias Ringwald 	return result;
463e8ad470fSMatthias Ringwald }
464e8ad470fSMatthias Ringwald 
465ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
466ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
467ceecb9d9SMatthias Ringwald     link_key_t link_key;
468ceecb9d9SMatthias Ringwald     link_key_type_t type;
469ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
470ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
471ceecb9d9SMatthias Ringwald     if (!ok) {
472ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
473ceecb9d9SMatthias Ringwald         return;
474ceecb9d9SMatthias Ringwald     }
475ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
476ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
477ceecb9d9SMatthias Ringwald     }
478ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
479ceecb9d9SMatthias Ringwald }
480ceecb9d9SMatthias Ringwald 
4811b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
4821b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4831b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
4841b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
4851b6fb31bSMatthias Ringwald }
4861b6fb31bSMatthias Ringwald int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
4871b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4881b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
4891b6fb31bSMatthias Ringwald }
4901b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
4911b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
4921b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
4931b6fb31bSMatthias Ringwald }
49435454696SMatthias Ringwald #endif
495c12e46e7Smatthias.ringwald 
496eb8076ddSMatthias Ringwald static bool hci_is_le_connection_type(bd_addr_type_t address_type){
497eb8076ddSMatthias Ringwald     switch (address_type){
498ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
499ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
500ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
501ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
502eb8076ddSMatthias Ringwald             return true;
503ce41473eSMatthias Ringwald         default:
504eb8076ddSMatthias Ringwald             return false;
505ce41473eSMatthias Ringwald     }
5060bf6344aS[email protected] }
5070bf6344aS[email protected] 
508eb8076ddSMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
509eb8076ddSMatthias Ringwald     return hci_is_le_connection_type(connection->address_type);
510eb8076ddSMatthias Ringwald }
511eb8076ddSMatthias Ringwald 
5127fde4af9Smatthias.ringwald /**
51343bfb1bdSmatthias.ringwald  * count connections
51443bfb1bdSmatthias.ringwald  */
51540d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
51656c253c9Smatthias.ringwald     int count = 0;
517665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
518a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
51915a27967SMatthias Ringwald         count++;
52015a27967SMatthias Ringwald     }
52143bfb1bdSmatthias.ringwald     return count;
52243bfb1bdSmatthias.ringwald }
523c8e4258aSmatthias.ringwald 
52495d71764SMatthias Ringwald static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
525ee303eddS[email protected] 
526f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
527f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
528ee303eddS[email protected] 
529665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
530a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
531998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
532ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
533ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
534ce41473eSMatthias Ringwald         }
535f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
536ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
537ee303eddS[email protected]         }
538ee303eddS[email protected]     }
539d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
540ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
541ee303eddS[email protected]     int free_slots_le = 0;
542ee303eddS[email protected] 
543ee303eddS[email protected]     if (free_slots_classic < 0){
5449da54300S[email protected]         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);
545998906cdSmatthias.ringwald         return 0;
546998906cdSmatthias.ringwald     }
547ee303eddS[email protected] 
548ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
549ee303eddS[email protected]         // if we have LE slots, they are used
550ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
551ee303eddS[email protected]         if (free_slots_le < 0){
5529da54300S[email protected]             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);
553ee303eddS[email protected]             return 0;
554998906cdSmatthias.ringwald         }
555ee303eddS[email protected]     } else {
556ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
557ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
558ee303eddS[email protected]         if (free_slots_classic < 0){
5599da54300S[email protected]             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);
560ee303eddS[email protected]             return 0;
561ee303eddS[email protected]         }
562ee303eddS[email protected]     }
563ee303eddS[email protected] 
564ee303eddS[email protected]     switch (address_type){
565ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
5662125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
567ee303eddS[email protected]             return 0;
568ee303eddS[email protected] 
569f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
570ee303eddS[email protected]             return free_slots_classic;
571ee303eddS[email protected] 
572ee303eddS[email protected]         default:
573cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
574ee303eddS[email protected]                return free_slots_le;
575ee303eddS[email protected]            }
576cb00d3aaS[email protected]            return free_slots_classic;
577cb00d3aaS[email protected]     }
578998906cdSmatthias.ringwald }
579998906cdSmatthias.ringwald 
5802125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
5812125de09SMatthias Ringwald     // get connection type
5822125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5832125de09SMatthias Ringwald     if (!connection){
5842125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
5852125de09SMatthias Ringwald         return 0;
5862125de09SMatthias Ringwald     }
5872125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
5882125de09SMatthias Ringwald }
5892125de09SMatthias Ringwald 
59035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
591701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
592f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
593665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
594760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
595760b20efSMatthias Ringwald         // explicit flow control
596665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
597e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
598ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
599ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
600e35edcc1S[email protected]         }
601e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
602701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
60344d0e3d5S[email protected]             return 0;
60444d0e3d5S[email protected]         }
605e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
60649205f5dSMatthias Ringwald     } else {
60749205f5dSMatthias Ringwald         // implicit flow control -- TODO
6086f28d2eeSMatthias Ringwald         int num_ready = 0;
6096f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
6106f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
6116f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
6126f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
6136f28d2eeSMatthias Ringwald             num_ready++;
61449205f5dSMatthias Ringwald         }
6156f28d2eeSMatthias Ringwald         return num_ready;
6166f28d2eeSMatthias Ringwald     }
617e35edcc1S[email protected] }
61835454696SMatthias Ringwald #endif
61944d0e3d5S[email protected] 
6202b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
6212b838201SMatthias Ringwald static int hci_can_send_comand_packet_transport(void){
622ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
623ac928cc2S[email protected] 
624ac928cc2S[email protected]     // check for async hci transport implementations
625ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
626ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
627ac928cc2S[email protected]             return 0;
628ac928cc2S[email protected]         }
629ac928cc2S[email protected]     }
6302b838201SMatthias Ringwald     return 1;
6312b838201SMatthias Ringwald }
632ac928cc2S[email protected] 
6332b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
6342b838201SMatthias Ringwald int hci_can_send_command_packet_now(void){
6352b838201SMatthias Ringwald     if (hci_can_send_comand_packet_transport() == 0) return 0;
6364ea43905SMatthias Ringwald     return hci_stack->num_cmd_packets > 0u;
637ac928cc2S[email protected] }
638ac928cc2S[email protected] 
6399d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
640ac928cc2S[email protected]     // check for async hci transport implementations
6419d04d3a7SMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
6429d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
643ac928cc2S[email protected] }
6449d04d3a7SMatthias Ringwald 
6459d04d3a7SMatthias Ringwald static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
6469d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
6479d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
648ac928cc2S[email protected] }
6499d04d3a7SMatthias Ringwald 
6509d04d3a7SMatthias Ringwald int hci_can_send_acl_le_packet_now(void){
6519d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
6529d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
6539d04d3a7SMatthias Ringwald }
6549d04d3a7SMatthias Ringwald 
6559d04d3a7SMatthias Ringwald int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
6569d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
657e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
658ac928cc2S[email protected] }
659ac928cc2S[email protected] 
660ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
661ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
662ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
6636b4af23dS[email protected] }
6646b4af23dS[email protected] 
66535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
66635454696SMatthias Ringwald int hci_can_send_acl_classic_packet_now(void){
66735454696SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
668f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
66935454696SMatthias Ringwald }
67035454696SMatthias Ringwald 
671701e3307SMatthias Ringwald int hci_can_send_prepared_sco_packet_now(void){
672d057580eSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
673f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
674f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
675f234b250SMatthias Ringwald     } else {
676701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
67744d0e3d5S[email protected]     }
678f234b250SMatthias Ringwald }
67944d0e3d5S[email protected] 
680701e3307SMatthias Ringwald int hci_can_send_sco_packet_now(void){
681d057580eSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
682701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
68344d0e3d5S[email protected] }
68444d0e3d5S[email protected] 
685d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
686d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
687d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
688d057580eSMatthias Ringwald }
68935454696SMatthias Ringwald #endif
690d057580eSMatthias Ringwald 
69195d71764SMatthias Ringwald // used for internal checks in l2cap.c
692c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
693c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
694c8b9416aS[email protected] }
695c8b9416aS[email protected] 
6966b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
6976b4af23dS[email protected] int hci_reserve_packet_buffer(void){
6989d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
6999d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
7009d14b626S[email protected]         return 0;
7019d14b626S[email protected]     }
7026b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
7036b4af23dS[email protected]     return 1;
7046b4af23dS[email protected] }
7056b4af23dS[email protected] 
70668a0fcf7S[email protected] void hci_release_packet_buffer(void){
70768a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
70868a0fcf7S[email protected] }
70968a0fcf7S[email protected] 
7106b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
7117f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
7126b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
7136b4af23dS[email protected] }
7146b4af23dS[email protected] 
715452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
716452cf3bbS[email protected] 
717452cf3bbS[email protected]     // 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);
718452cf3bbS[email protected] 
719452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
720452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
7214ea43905SMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
722452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
723452cf3bbS[email protected]     }
724452cf3bbS[email protected] 
7250f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
726fcf88f47SMatthias Ringwald     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
7270f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
7280f3b27c5SMatthias Ringwald     }
7290f3b27c5SMatthias Ringwald #endif
730452cf3bbS[email protected] 
731d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
732d999b54eSMatthias Ringwald 
733452cf3bbS[email protected]     int err;
734452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
735ff3cc4a5SMatthias Ringwald     while (true){
736452cf3bbS[email protected] 
737d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
738d999b54eSMatthias Ringwald 
739452cf3bbS[email protected]         // get current data
7404ea43905SMatthias Ringwald         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
741452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
7421979f09cSMatthias Ringwald         bool more_fragments = false;
743452cf3bbS[email protected] 
744452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
745452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
7461979f09cSMatthias Ringwald             more_fragments = true;
747452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
748452cf3bbS[email protected]         }
749452cf3bbS[email protected] 
750452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
7514ea43905SMatthias Ringwald         if (acl_header_pos > 0u){
752f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
7534ea43905SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
754f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
755452cf3bbS[email protected]         }
756452cf3bbS[email protected] 
757452cf3bbS[email protected]         // update header len
7584ea43905SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
759452cf3bbS[email protected] 
760452cf3bbS[email protected]         // count packet
761ce41473eSMatthias Ringwald         connection->num_packets_sent++;
7621979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
763d999b54eSMatthias Ringwald 
764d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
765d999b54eSMatthias Ringwald         if (more_fragments){
766d999b54eSMatthias Ringwald             // update start of next fragment to send
767d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
768d999b54eSMatthias Ringwald         } else {
769d999b54eSMatthias Ringwald             // done
770d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
771d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
772d999b54eSMatthias Ringwald         }
773452cf3bbS[email protected] 
774452cf3bbS[email protected]         // send packet
775452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
776452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
7775bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
77881d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
779452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
780452cf3bbS[email protected] 
7811979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
782d999b54eSMatthias Ringwald 
783452cf3bbS[email protected]         // done yet?
784452cf3bbS[email protected]         if (!more_fragments) break;
785452cf3bbS[email protected] 
786452cf3bbS[email protected]         // can send more?
787452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
788452cf3bbS[email protected]     }
789452cf3bbS[email protected] 
790d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
791452cf3bbS[email protected] 
792d051460cS[email protected]     // release buffer now for synchronous transport
793203bace6S[email protected]     if (hci_transport_synchronous()){
79481d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
795452cf3bbS[email protected]         hci_release_packet_buffer();
796fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
797452cf3bbS[email protected]     }
798452cf3bbS[email protected] 
799452cf3bbS[email protected]     return err;
800452cf3bbS[email protected] }
801452cf3bbS[email protected] 
802826f7347S[email protected] // pre: caller has reserved the packet buffer
803826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
8047856c818Smatthias.ringwald 
805452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
806452cf3bbS[email protected] 
807826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
808826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
809826f7347S[email protected]         return 0;
810826f7347S[email protected]     }
811826f7347S[email protected] 
812d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
813d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
814d713a683S[email protected] 
815826f7347S[email protected]     // check for free places on Bluetooth module
816d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
817826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
81897b61c7bS[email protected]         hci_release_packet_buffer();
819068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
82097b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
82197b61c7bS[email protected]     }
8226218e6f1Smatthias.ringwald 
8235061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
82497b61c7bS[email protected]     if (!connection) {
8255fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
82697b61c7bS[email protected]         hci_release_packet_buffer();
827068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
82897b61c7bS[email protected]         return 0;
82997b61c7bS[email protected]     }
83052db98b2SMatthias Ringwald 
83152db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
83256cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
83352db98b2SMatthias Ringwald #endif
83456cf178bSmatthias.ringwald 
835452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
8367856c818Smatthias.ringwald 
837452cf3bbS[email protected]     // setup data
838452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
839452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
8406218e6f1Smatthias.ringwald 
841452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
842ee091cf1Smatthias.ringwald }
843ee091cf1Smatthias.ringwald 
84435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
84544d0e3d5S[email protected] // pre: caller has reserved the packet buffer
84644d0e3d5S[email protected] int hci_send_sco_packet_buffer(int size){
84744d0e3d5S[email protected] 
84844d0e3d5S[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
84944d0e3d5S[email protected] 
85044d0e3d5S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
85144d0e3d5S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
85244d0e3d5S[email protected]         return 0;
85344d0e3d5S[email protected]     }
85444d0e3d5S[email protected] 
85544d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
8564b3e1e19SMatthias Ringwald 
8574b3e1e19SMatthias Ringwald     // skip checks in loopback mode
8584b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
85944d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
86044d0e3d5S[email protected] 
86144d0e3d5S[email protected]         // check for free places on Bluetooth module
862701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
863cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
86444d0e3d5S[email protected]             hci_release_packet_buffer();
865068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
86644d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
86744d0e3d5S[email protected]         }
86844d0e3d5S[email protected] 
869e35edcc1S[email protected]         // track send packet in connection struct
870e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
871e35edcc1S[email protected]         if (!connection) {
872e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
873e35edcc1S[email protected]             hci_release_packet_buffer();
874068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
875e35edcc1S[email protected]             return 0;
876e35edcc1S[email protected]         }
877f234b250SMatthias Ringwald 
878f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
879f234b250SMatthias Ringwald             // token used
880f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 0;
881f234b250SMatthias Ringwald         } else {
882760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
883ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
8846f28d2eeSMatthias Ringwald             } else {
885e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
886760b20efSMatthias Ringwald             }
8874b3e1e19SMatthias Ringwald         }
888f234b250SMatthias Ringwald     }
88944d0e3d5S[email protected] 
89044d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
891543e835cSMatthias Ringwald 
89243149fc9SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
89343149fc9SMatthias Ringwald     hci_stack->sco_transport->send_packet(packet, size);
89443149fc9SMatthias Ringwald     hci_release_packet_buffer();
89543149fc9SMatthias Ringwald     hci_emit_transport_packet_sent();
89643149fc9SMatthias Ringwald 
89743149fc9SMatthias Ringwald     return 0;
89843149fc9SMatthias Ringwald #else
89943149fc9SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
900543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
901543e835cSMatthias Ringwald         hci_release_packet_buffer();
902fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
903543e835cSMatthias Ringwald     }
904543e835cSMatthias Ringwald 
905543e835cSMatthias Ringwald     return err;
90643149fc9SMatthias Ringwald #endif
90744d0e3d5S[email protected] }
90835454696SMatthias Ringwald #endif
90944d0e3d5S[email protected] 
910c3b46f5aSMatthias Ringwald static void acl_handler(uint8_t *packet, uint16_t size){
911e76a89eeS[email protected] 
9127856c818Smatthias.ringwald     // get info
9137856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
9145061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
9157856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
9167856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
9177856c818Smatthias.ringwald 
9187856c818Smatthias.ringwald     // ignore non-registered handle
9197856c818Smatthias.ringwald     if (!conn){
920c3b46f5aSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , con_handle);
9217856c818Smatthias.ringwald         return;
9227856c818Smatthias.ringwald     }
9237856c818Smatthias.ringwald 
924e76a89eeS[email protected]     // assert packet is complete
9254ea43905SMatthias Ringwald     if ((acl_length + 4u) != size){
926c3b46f5aSMatthias Ringwald         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
927e76a89eeS[email protected]         return;
928e76a89eeS[email protected]     }
929e76a89eeS[email protected] 
93052db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
9317856c818Smatthias.ringwald     // update idle timestamp
9327856c818Smatthias.ringwald     hci_connection_timestamp(conn);
93352db98b2SMatthias Ringwald #endif
9347856c818Smatthias.ringwald 
9352b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
9362b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
9372b838201SMatthias Ringwald     conn->num_packets_completed++;
9382b838201SMatthias Ringwald #endif
9392b838201SMatthias Ringwald 
9407856c818Smatthias.ringwald     // handle different packet types
9414ea43905SMatthias Ringwald     switch (acl_flags & 0x03u) {
9427856c818Smatthias.ringwald 
9437856c818Smatthias.ringwald         case 0x01: // continuation fragment
9447856c818Smatthias.ringwald 
9450ca847afS[email protected]             // sanity checks
9464ea43905SMatthias Ringwald             if (conn->acl_recombination_pos == 0u) {
9479da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
9487856c818Smatthias.ringwald                 return;
9497856c818Smatthias.ringwald             }
9504ea43905SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
9510ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
9520ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
9530ca847afS[email protected]                 conn->acl_recombination_pos = 0;
9540ca847afS[email protected]                 return;
9550ca847afS[email protected]             }
9567856c818Smatthias.ringwald 
9577856c818Smatthias.ringwald             // append fragment payload (header already stored)
9586535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
9596535961aSMatthias Ringwald                          &packet[4], acl_length);
9607856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
9617856c818Smatthias.ringwald 
9627856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
9634ea43905SMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
964d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
9657856c818Smatthias.ringwald                 // reset recombination buffer
9667856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
9677856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
9687856c818Smatthias.ringwald             }
9697856c818Smatthias.ringwald             break;
9707856c818Smatthias.ringwald 
9717856c818Smatthias.ringwald         case 0x02: { // first fragment
9727856c818Smatthias.ringwald 
97323a77e1aS[email protected]             // sanity check
97423a77e1aS[email protected]             if (conn->acl_recombination_pos) {
97523a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
97623a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
97723a77e1aS[email protected]             }
97823a77e1aS[email protected] 
9797856c818Smatthias.ringwald             // peek into L2CAP packet!
9807856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
9817856c818Smatthias.ringwald 
9827856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
9834ea43905SMatthias Ringwald             if (acl_length >= (l2cap_length + 4u)){
9847856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
9854ea43905SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4u);
9867856c818Smatthias.ringwald             } else {
9870ca847afS[email protected] 
9880ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
9890ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
9900ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
9910ca847afS[email protected]                     return;
9920ca847afS[email protected]                 }
9930ca847afS[email protected] 
9947856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
9956535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
9964ea43905SMatthias Ringwald                              packet, acl_length + 4u);
9974ea43905SMatthias Ringwald                 conn->acl_recombination_pos    = acl_length + 4u;
9987856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
9994ea43905SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
10007856c818Smatthias.ringwald             }
10017856c818Smatthias.ringwald             break;
10027856c818Smatthias.ringwald 
10037856c818Smatthias.ringwald         }
10047856c818Smatthias.ringwald         default:
1005c3b46f5aSMatthias Ringwald             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
10067856c818Smatthias.ringwald             return;
10077856c818Smatthias.ringwald     }
100894ab26f8Smatthias.ringwald 
100994ab26f8Smatthias.ringwald     // execute main loop
101094ab26f8Smatthias.ringwald     hci_run();
101116833f0aSmatthias.ringwald }
101222909952Smatthias.ringwald 
101367a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
10149da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
10153c4d4b90Smatthias.ringwald 
1016b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1017cb70c5abSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1018cb70c5abSMatthias Ringwald     bd_addr_type_t addr_type = conn->address_type;
1019cb70c5abSMatthias Ringwald #endif
1020cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1021cb70c5abSMatthias Ringwald     hci_con_handle_t con_handle = conn->con_handle;
1022ee752bb8SMatthias Ringwald #endif
1023b3264428SMatthias Ringwald #endif
1024ee752bb8SMatthias Ringwald 
1025528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
1026c785ef68Smatthias.ringwald 
1027665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1028a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
10293c4d4b90Smatthias.ringwald 
10303c4d4b90Smatthias.ringwald     // now it's gone
1031c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
1032ee752bb8SMatthias Ringwald 
1033b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1034034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1035ee752bb8SMatthias Ringwald     // update SCO
1036cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1037ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1038ee752bb8SMatthias Ringwald     }
1039034e9b53SMatthias Ringwald #endif
1040cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1041cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1042cb70c5abSMatthias Ringwald         hci_stack->sco_transport->close(con_handle);
1043cb70c5abSMatthias Ringwald     }
1044cb70c5abSMatthias Ringwald #endif
1045b3264428SMatthias Ringwald #endif
1046c7e0c5f6Smatthias.ringwald }
1047c7e0c5f6Smatthias.ringwald 
104835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
104935454696SMatthias Ringwald 
10500c042179S[email protected] static const uint16_t packet_type_sizes[] = {
10518f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
10528f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
10538f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
10548f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
10558f8108aaSmatthias.ringwald };
105665389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
105765389bfcS[email protected]      0, // 3 slot packets
105865389bfcS[email protected]      1, // 5 slot packets
105965389bfcS[email protected]     25, // EDR 2 mpbs
106065389bfcS[email protected]     26, // EDR 3 mbps
106165389bfcS[email protected]     39, // 3 slot EDR packts
106265389bfcS[email protected]     40, // 5 slot EDR packet
106365389bfcS[email protected] };
106465389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
106565389bfcS[email protected]     0x0f00, // 3 slot packets
106665389bfcS[email protected]     0xf000, // 5 slot packets
106765389bfcS[email protected]     0x1102, // EDR 2 mpbs
106865389bfcS[email protected]     0x2204, // EDR 3 mbps
106965389bfcS[email protected]     0x0300, // 3 slot EDR packts
107065389bfcS[email protected]     0x3000, // 5 slot EDR packet
107165389bfcS[email protected] };
10728f8108aaSmatthias.ringwald 
107365389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
107465389bfcS[email protected]     // enable packet types based on size
10758f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
1076f16a69bbS[email protected]     unsigned int i;
10778f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
10788f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
10798f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
10808f8108aaSmatthias.ringwald             packet_types |= 1 << i;
10818f8108aaSmatthias.ringwald         }
10828f8108aaSmatthias.ringwald     }
108365389bfcS[email protected]     // disable packet types due to missing local supported features
108465389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1085f04a0c31SMatthias Ringwald         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
108665389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
108765389bfcS[email protected]         if (feature_set) continue;
108865389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
108965389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
109065389bfcS[email protected]     }
10918f8108aaSmatthias.ringwald     // flip bits for "may not be used"
10928f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
10938f8108aaSmatthias.ringwald     return packet_types;
10948f8108aaSmatthias.ringwald }
10958f8108aaSmatthias.ringwald 
10968f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
10973a9fb326S[email protected]     return hci_stack->packet_types;
10988f8108aaSmatthias.ringwald }
109935454696SMatthias Ringwald #endif
11008f8108aaSmatthias.ringwald 
1101facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
11027dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
11033a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
11047dc17943Smatthias.ringwald }
11057dc17943Smatthias.ringwald 
1106f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
11073a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
11087dc17943Smatthias.ringwald }
11097dc17943Smatthias.ringwald 
111006b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
11113e68d23dSMatthias Ringwald int hci_extended_sco_link_supported(void){
11123e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
11133e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
11143e68d23dSMatthias Ringwald }
111506b9e820SMatthias Ringwald #endif
11163e68d23dSMatthias Ringwald 
11176ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
11186ac9a97eS[email protected]     // No. 54, byte 6, bit 6
11194ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
11206ac9a97eS[email protected] }
11216ac9a97eS[email protected] 
112215a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
11236ac9a97eS[email protected]     // No. 51, byte 6, bit 3
11244ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1125f5d8d141S[email protected] }
1126f5d8d141S[email protected] 
11277f02f414SMatthias Ringwald static int hci_classic_supported(void){
112835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
11296ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
11303a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
113135454696SMatthias Ringwald #else
113235454696SMatthias Ringwald     return 0;
113335454696SMatthias Ringwald #endif
1134f5d8d141S[email protected] }
1135f5d8d141S[email protected] 
11367f02f414SMatthias Ringwald static int hci_le_supported(void){
1137a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
11386ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
11394ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1140f5d8d141S[email protected] #else
1141f5d8d141S[email protected]     return 0;
1142f5d8d141S[email protected] #endif
1143f5d8d141S[email protected] }
1144f5d8d141S[email protected] 
1145b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1146b95a5a35SMatthias Ringwald 
1147f5873674SMatthias Ringwald static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
11486bcfa632SMatthias Ringwald     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
11496bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
115069a97523S[email protected]     } else {
11516bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
115269a97523S[email protected]     }
115369a97523S[email protected] }
115469a97523S[email protected] 
11556bcfa632SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
11566bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
11576bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
11586bcfa632SMatthias Ringwald }
11596bcfa632SMatthias Ringwald 
11606bcfa632SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
11616bcfa632SMatthias Ringwald void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
11626bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_advertisements_own_addr_type;
11636bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
11646bcfa632SMatthias Ringwald };
11656bcfa632SMatthias Ringwald #endif
11666bcfa632SMatthias Ringwald 
1167e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
11686bcfa632SMatthias Ringwald 
11696bcfa632SMatthias Ringwald /**
11706bcfa632SMatthias Ringwald  * @brief Get own addr type and address used for LE connections (Central)
11716bcfa632SMatthias Ringwald  */
11726bcfa632SMatthias Ringwald void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
11736bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_connection_own_addr_type;
11746bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
11756bcfa632SMatthias Ringwald }
11766bcfa632SMatthias Ringwald 
1177384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
11789ec2630cSMatthias Ringwald 
1179d1dc057bS[email protected]     int offset = 3;
1180d1dc057bS[email protected]     int num_reports = packet[offset];
1181d1dc057bS[email protected]     offset += 1;
1182d1dc057bS[email protected] 
118357c9da5bS[email protected]     int i;
11844f4e0224SMatthias Ringwald     // log_info("HCI: handle adv report with num reports: %d", num_reports);
118503fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1186a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
118733e6948bSMatthias Ringwald         // sanity checks on data_length:
118833e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
118933e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
11904ea43905SMatthias Ringwald         if ((offset + 9u + data_length + 1u) > size)    return;
119133e6948bSMatthias Ringwald         // setup event
11924ea43905SMatthias Ringwald         uint8_t event_size = 10u + data_length;
1193d1dc057bS[email protected]         int pos = 0;
1194045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
119557c9da5bS[email protected]         event[pos++] = event_size;
11966535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1197d1dc057bS[email protected]         offset += 8;
1198d1dc057bS[email protected]         pos += 8;
1199d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
120033e6948bSMatthias Ringwald         event[pos++] = data_length;
120133e6948bSMatthias Ringwald         offset++;
12026535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
120357c9da5bS[email protected]         pos +=    data_length;
12044ea43905SMatthias Ringwald         offset += data_length + 1u; // rssi
1205d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
120657c9da5bS[email protected]     }
120757c9da5bS[email protected] }
1208b2f949feS[email protected] #endif
1209e8c8828eSMatthias Ringwald #endif
121057c9da5bS[email protected] 
12112b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
12122b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1213bbc366e6SMatthias Ringwald static void hci_update_advertisements_enabled_for_current_roles(void){
1214bbc366e6SMatthias Ringwald     if (hci_stack->le_advertisements_enabled){
12152b6ab3e6SMatthias Ringwald         // get number of active le slave connections
12162b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
12172b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
12182b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
12192b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
12202b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
12212b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
12222b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
12232b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
12242b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
12252b6ab3e6SMatthias Ringwald             num_slave_connections++;
12262b6ab3e6SMatthias Ringwald         }
12272b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1228bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1229bbc366e6SMatthias Ringwald     } else {
1230bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = false;
12312b6ab3e6SMatthias Ringwald     }
12322b6ab3e6SMatthias Ringwald }
12332b6ab3e6SMatthias Ringwald #endif
12342b6ab3e6SMatthias Ringwald #endif
12352b6ab3e6SMatthias Ringwald 
1236cd77dd38SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
123706b9e820SMatthias Ringwald 
123896b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
123996b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
12409796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
124196b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
1242a1df452eSMatthias Ringwald     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
124396b53536SMatthias Ringwald         baud_rate = 3000000;
124496b53536SMatthias Ringwald     }
124596b53536SMatthias Ringwald     return baud_rate;
124696b53536SMatthias Ringwald }
124796b53536SMatthias Ringwald 
1248ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
12499ec2630cSMatthias Ringwald     UNUSED(ds);
12509ec2630cSMatthias Ringwald 
12510305bdeaSMatthias Ringwald     switch (hci_stack->substate){
12520305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
12537b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
12540305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
12557b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
12560305bdeaSMatthias Ringwald             hci_run();
12570305bdeaSMatthias Ringwald             break;
12589f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
12599f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
12609f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
12619f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
12629f007422SMatthias Ringwald             }
1263cf373d3aSMatthias Ringwald 
1264cf373d3aSMatthias Ringwald             /* fall through */
1265cf373d3aSMatthias Ringwald 
1266e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1267e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1268e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1269e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1270e47e68c7SMatthias Ringwald             hci_run();
1271688c2635SMatthias Ringwald             break;
12727224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
12737224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
127496b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1275cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
12767dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
12777224be7eSMatthias Ringwald             }
1278834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
127961f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1280834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1281834bce8cSMatthias Ringwald                     log_info("Link Reset");
1282834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1283834bce8cSMatthias Ringwald                 }
1284772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1285772a36d3SMatthias Ringwald                 hci_run();
1286772a36d3SMatthias Ringwald             }
12874696bddbSMatthias Ringwald             break;
1288559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1289559961d0SMatthias Ringwald             // otherwise continue
1290559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1291559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1292559961d0SMatthias Ringwald             break;
12930305bdeaSMatthias Ringwald         default:
12940305bdeaSMatthias Ringwald             break;
12950305bdeaSMatthias Ringwald     }
12960305bdeaSMatthias Ringwald }
129706b9e820SMatthias Ringwald #endif
12980305bdeaSMatthias Ringwald 
129971de195eSMatthias Ringwald static void hci_initializing_next_state(void){
130074b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
130174b323a9SMatthias Ringwald }
130274b323a9SMatthias Ringwald 
130374b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
130471de195eSMatthias Ringwald static void hci_initializing_run(void){
1305148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
130674b323a9SMatthias Ringwald     switch (hci_stack->substate){
130774b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
130874b323a9SMatthias Ringwald             hci_state_reset();
1309a0cf2f3fSMatthias Ringwald 
131006b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
13110305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1312659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1313528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1314528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1315a0cf2f3fSMatthias Ringwald #endif
13160305bdeaSMatthias Ringwald             // send command
131774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
13180305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
131974b323a9SMatthias Ringwald             break;
132076fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
132176fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
132276fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
132376fcb19bSMatthias Ringwald             break;
1324e90bae01SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
1325e90bae01SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
1326e90bae01SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1327e90bae01SMatthias Ringwald             break;
132806b9e820SMatthias Ringwald 
132906b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1330e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1331e47e68c7SMatthias Ringwald             hci_state_reset();
1332e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1333659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1334528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1335528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1336e47e68c7SMatthias Ringwald             // send command
1337e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1338e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1339e47e68c7SMatthias Ringwald             break;
13408d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
13418d29070eSMatthias Ringwald             hci_state_reset();
13428d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
13438d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
13448d29070eSMatthias Ringwald             break;
1345fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE: {
134696b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
13473fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1348f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
134974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
13504ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
13514696bddbSMatthias Ringwald             // STLC25000D: baudrate change happens within 0.5 s after command was send,
13524696bddbSMatthias Ringwald             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
135361f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1354659d758cSMatthias Ringwald                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1355528a4a3bSMatthias Ringwald                 btstack_run_loop_add_timer(&hci_stack->timeout);
13564696bddbSMatthias Ringwald             }
135774b323a9SMatthias Ringwald             break;
1358fab26ab3SMatthias Ringwald         }
1359fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
136096b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
13613fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1362f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1363eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
13644ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1365eb3a5314SMatthias Ringwald             break;
1366fab26ab3SMatthias Ringwald         }
136774b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
136874b323a9SMatthias Ringwald             // Custom initialization
13693fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1370ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
13711979f09cSMatthias Ringwald                 bool send_cmd = false;
1372ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1373f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
13741979f09cSMatthias Ringwald                         send_cmd = true;
1375e47e68c7SMatthias Ringwald                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1376e47e68c7SMatthias Ringwald                         break;
1377f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
13781979f09cSMatthias Ringwald                         send_cmd = true;
1379f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1380e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1381659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1382528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1383528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
1384a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1385772a36d3SMatthias Ringwald                             && hci_stack->config
13863fb36a29SMatthias Ringwald                             && hci_stack->chipset
13873fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1388772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
13892caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
1390772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1391772a36d3SMatthias Ringwald                         } else {
13929f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1393772a36d3SMatthias Ringwald                         }
1394e47e68c7SMatthias Ringwald                         break;
1395f41911edSMatthias Ringwald                     default:
1396f41911edSMatthias Ringwald                         break;
1397e47e68c7SMatthias Ringwald                 }
1398ee720f3aSMatthias Ringwald 
1399ee720f3aSMatthias Ringwald                 if (send_cmd){
14004ea43905SMatthias Ringwald                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1401ee720f3aSMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1402ee720f3aSMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
14030305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
140474b323a9SMatthias Ringwald                     break;
140574b323a9SMatthias Ringwald                 }
1406148ca237SMatthias Ringwald                 log_info("Init script done");
140792a0d36dSMatthias Ringwald 
1408559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1409ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1410a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1411a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1412e021ff1eSMatthias Ringwald 
1413559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
141492a0d36dSMatthias Ringwald                     int need_baud_change = hci_stack->config
14153fb36a29SMatthias Ringwald                         && hci_stack->chipset
14163fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
141792a0d36dSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
14189796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
141992a0d36dSMatthias Ringwald                     if (need_baud_change) {
14209796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1421cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
142292a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
142392a0d36dSMatthias Ringwald                     }
1424559961d0SMatthias Ringwald 
1425f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
1426f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1427f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
1428f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1429559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1430f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1431559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1432559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
1433559961d0SMatthias Ringwald                     break;
143492a0d36dSMatthias Ringwald                 }
143574b323a9SMatthias Ringwald             }
143674b323a9SMatthias Ringwald             // otherwise continue
1437a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1438a828a756SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1439a828a756SMatthias Ringwald             break;
144053860077SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
144153860077SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
14423fb36a29SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1443f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
144453860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
14454ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
144653860077SMatthias Ringwald             break;
144706b9e820SMatthias Ringwald #endif
144806b9e820SMatthias Ringwald 
144906b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
145006b9e820SMatthias Ringwald             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
145106b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
145206b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
145306b9e820SMatthias Ringwald             break;
145453860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
145553860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
145653860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
145753860077SMatthias Ringwald             break;
145874b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
145974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
14600305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_buffer_size);
146174b323a9SMatthias Ringwald             break;
146253860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
146353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
14640305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
146574b323a9SMatthias Ringwald             break;
14662b838201SMatthias Ringwald 
14672b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
14682b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
14692b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
14702b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
14712b838201SMatthias Ringwald             break;
14722b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
14732b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
14742b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
14752b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
14762b838201SMatthias Ringwald             break;
14772b838201SMatthias Ringwald #endif
14782b838201SMatthias Ringwald 
147974b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
14800305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
148174b323a9SMatthias Ringwald             if (hci_le_supported()){
14825ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
148374b323a9SMatthias Ringwald             } else {
148474b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
14855ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
148674b323a9SMatthias Ringwald             }
148774b323a9SMatthias Ringwald             break;
14882b838201SMatthias Ringwald 
148935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
149074b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
149174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
14920305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
149374b323a9SMatthias Ringwald             break;
149474b323a9SMatthias Ringwald         case HCI_INIT_WRITE_PAGE_TIMEOUT:
149574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
14960305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
149774b323a9SMatthias Ringwald             break;
1498c33e56d3SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1499c33e56d3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1500c33e56d3SMatthias Ringwald             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1501c33e56d3SMatthias Ringwald             break;
150274b323a9SMatthias Ringwald         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
150374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
15040305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
150574b323a9SMatthias Ringwald             break;
15061c2a62f5SMatthias Ringwald         case HCI_INIT_WRITE_LOCAL_NAME: {
15070305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
15081c2a62f5SMatthias Ringwald             hci_reserve_packet_buffer();
15091c2a62f5SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
15101c2a62f5SMatthias Ringwald             // construct HCI Command and send
15111c2a62f5SMatthias Ringwald             uint16_t opcode = hci_write_local_name.opcode;
15121c2a62f5SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
15131c2a62f5SMatthias Ringwald             packet[0] = opcode & 0xff;
15141c2a62f5SMatthias Ringwald             packet[1] = opcode >> 8;
15151c2a62f5SMatthias Ringwald             packet[2] = DEVICE_NAME_LEN;
15161c2a62f5SMatthias Ringwald             memset(&packet[3], 0, DEVICE_NAME_LEN);
151779186815SMatthias Ringwald             uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
151879186815SMatthias Ringwald             uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
151979186815SMatthias Ringwald             // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
152079186815SMatthias Ringwald             (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
15211c2a62f5SMatthias Ringwald             // expand '00:00:00:00:00:00' in name with bd_addr
15223c9da642SMatthias Ringwald             btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
15231c2a62f5SMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
152474b323a9SMatthias Ringwald             break;
15251c2a62f5SMatthias Ringwald         }
152629af07f3SMatthias Ringwald         case HCI_INIT_WRITE_EIR_DATA: {
15278a114470SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
152829af07f3SMatthias Ringwald             hci_reserve_packet_buffer();
152929af07f3SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
153063873210SMatthias Ringwald             // construct HCI Command in-place and send
153129af07f3SMatthias Ringwald             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
153229af07f3SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
153363873210SMatthias Ringwald             uint16_t offset = 0;
153463873210SMatthias Ringwald             packet[offset++] = opcode & 0xff;
153563873210SMatthias Ringwald             packet[offset++] = opcode >> 8;
153663873210SMatthias Ringwald             packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
153763873210SMatthias Ringwald             packet[offset++] = 0;  // FEC not required
153863873210SMatthias Ringwald             memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1539ad0d1108SMatthias Ringwald             if (hci_stack->eir_data){
154063873210SMatthias Ringwald                 // copy items and expand '00:00:00:00:00:00' in name with bd_addr
154163873210SMatthias Ringwald                 ad_context_t context;
154263873210SMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
154363873210SMatthias Ringwald                     uint8_t data_type   = ad_iterator_get_data_type(&context);
154463873210SMatthias Ringwald                     uint8_t size        = ad_iterator_get_data_len(&context);
154563873210SMatthias Ringwald                     const uint8_t *data = ad_iterator_get_data(&context);
154663873210SMatthias Ringwald                     // copy item
154763873210SMatthias Ringwald                     packet[offset++] = size + 1;
154863873210SMatthias Ringwald                     packet[offset++] = data_type;
154963873210SMatthias Ringwald                     memcpy(&packet[offset], data, size);
155063873210SMatthias Ringwald                     // update name item
155163873210SMatthias Ringwald                     if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
15523c9da642SMatthias Ringwald                         btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
155363873210SMatthias Ringwald                     }
155463873210SMatthias Ringwald                     offset += size;
155563873210SMatthias Ringwald                 }
1556ad0d1108SMatthias Ringwald             } else {
155779186815SMatthias Ringwald                 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
155879186815SMatthias Ringwald                 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
155963873210SMatthias Ringwald                 packet[offset++] = bytes_to_copy + 1;
156063873210SMatthias Ringwald                 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
156179186815SMatthias Ringwald                 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
156229af07f3SMatthias Ringwald                 // expand '00:00:00:00:00:00' in name with bd_addr
15633c9da642SMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
156463873210SMatthias Ringwald             }
1565a8c4e5adSMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1566ff00ed1cSMatthias Ringwald             break;
156729af07f3SMatthias Ringwald         }
1568f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
1569f6858d14SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
15708a114470SMatthias Ringwald             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1571f6858d14SMatthias Ringwald             break;
15725d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
15735d23aae8SMatthias Ringwald             hci_send_cmd(&hci_write_secure_connections_host_support, 1);
1574c214d65bSMatthias Ringwald 			hci_stack->secure_connections_active = true;
15755d23aae8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
15765d23aae8SMatthias Ringwald             break;
157774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SCAN_ENABLE:
157874b323a9SMatthias Ringwald             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
157974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
158074b323a9SMatthias Ringwald             break;
1581483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
1582729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1583729ed62eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1584729ed62eSMatthias Ringwald             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1585729ed62eSMatthias Ringwald             break;
1586483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1587483c5078SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1588483c5078SMatthias Ringwald             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1589483c5078SMatthias Ringwald             break;
15908051253fSMatthias Ringwald         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
1591a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1592a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
15938051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1594a42798c3SMatthias Ringwald             log_info("BCM: Route SCO data via HCI transport");
1595a42798c3SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
15968051253fSMatthias Ringwald #endif
15978051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
15988051253fSMatthias Ringwald             log_info("BCM: Route SCO data via PCM interface");
15991d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
16001d2bbd54SMatthias Ringwald             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
16011d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
16021d2bbd54SMatthias Ringwald #else
16031d2bbd54SMatthias Ringwald             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
16041d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
16051d2bbd54SMatthias Ringwald #endif
16068051253fSMatthias Ringwald #endif
1607a42798c3SMatthias Ringwald             break;
16084e821764SMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
16094e821764SMatthias Ringwald         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
16104e821764SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
16114e821764SMatthias Ringwald             log_info("BCM: Config PCM interface for I2S");
16121d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
16131d2bbd54SMatthias Ringwald             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
16141d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
16151d2bbd54SMatthias Ringwald #else
16161d2bbd54SMatthias Ringwald             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
16171d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
16181d2bbd54SMatthias Ringwald #endif
16194e821764SMatthias Ringwald             break;
162035454696SMatthias Ringwald #endif
16214e821764SMatthias Ringwald #endif
16224e821764SMatthias Ringwald 
1623a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
162474b323a9SMatthias Ringwald         // LE INIT
162574b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
162674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
16270305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_read_buffer_size);
162874b323a9SMatthias Ringwald             break;
1629daabb8b8SMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
1630daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1631729710c0SMatthias Ringwald             hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1632daabb8b8SMatthias Ringwald             break;
163374b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
163474b323a9SMatthias Ringwald             // LE Supported Host = 1, Simultaneous Host = 0
163574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
16360305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
163774b323a9SMatthias Ringwald             break;
1638b435e062SMatthias Ringwald #endif
1639b435e062SMatthias Ringwald 
1640b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1641dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1642dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1643dcd678baSMatthias Ringwald             hci_send_cmd(&hci_le_read_maximum_data_length);
1644dcd678baSMatthias Ringwald             break;
1645dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1646dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1647b435e062SMatthias Ringwald             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1648dcd678baSMatthias Ringwald             break;
1649b435e062SMatthias Ringwald #endif
1650b435e062SMatthias Ringwald 
1651b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
16523b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
16533b6d4121SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
16543b6d4121SMatthias Ringwald             hci_send_cmd(&hci_le_read_white_list_size);
16553b6d4121SMatthias Ringwald             break;
165674b323a9SMatthias Ringwald         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
165774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
16588b69e4c7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
165974b323a9SMatthias Ringwald             break;
166074b323a9SMatthias Ringwald #endif
166174b323a9SMatthias Ringwald         default:
166274b323a9SMatthias Ringwald             return;
166374b323a9SMatthias Ringwald     }
166455975f88SMatthias Ringwald }
166555975f88SMatthias Ringwald 
1666a650ba4dSMatthias Ringwald static void hci_init_done(void){
1667a650ba4dSMatthias Ringwald     // done. tell the app
1668a650ba4dSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1669a650ba4dSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1670a650ba4dSMatthias Ringwald     hci_emit_state();
1671a650ba4dSMatthias Ringwald     hci_run();
1672a650ba4dSMatthias Ringwald }
1673a650ba4dSMatthias Ringwald 
167407fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
167507fd2f31SMatthias Ringwald     bool command_completed = false;
16760e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1677f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
16786155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
167907fd2f31SMatthias Ringwald             command_completed = true;
1680148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
16816155b3d3S[email protected]         } else {
1682d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
16836155b3d3S[email protected]         }
16846155b3d3S[email protected]     }
16850f97eae7SMatthias Ringwald 
16860e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
16876155b3d3S[email protected]         uint8_t  status = packet[2];
1688f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
16896155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
16906155b3d3S[email protected]             if (status){
169107fd2f31SMatthias Ringwald                 command_completed = true;
1692148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
16936155b3d3S[email protected]             } else {
16946155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
16956155b3d3S[email protected]             }
16966155b3d3S[email protected]         } else {
1697148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
16986155b3d3S[email protected]         }
16996155b3d3S[email protected]     }
170006b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1701e47e68c7SMatthias Ringwald     // Vendor == CSR
17020e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1703e47e68c7SMatthias Ringwald         // TODO: track actual command
170407fd2f31SMatthias Ringwald         command_completed = true;
1705e47e68c7SMatthias Ringwald     }
1706a2481739S[email protected] 
17074e9daa6fSMatthias Ringwald     // Vendor == Toshiba
17080e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
17094e9daa6fSMatthias Ringwald         // TODO: track actual command
171007fd2f31SMatthias Ringwald         command_completed = true;
1711004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1712004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
17134e9daa6fSMatthias Ringwald     }
171407fd2f31SMatthias Ringwald #endif
171507fd2f31SMatthias Ringwald 
171607fd2f31SMatthias Ringwald     return command_completed;
171707fd2f31SMatthias Ringwald }
171807fd2f31SMatthias Ringwald 
171907fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
172007fd2f31SMatthias Ringwald 
172107fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
172207fd2f31SMatthias Ringwald 
172307fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
172407fd2f31SMatthias Ringwald 
172507fd2f31SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
17264e9daa6fSMatthias Ringwald 
17270f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
17280f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
17290f97eae7SMatthias Ringwald     //
17300f97eae7SMatthias Ringwald     // HCI Reset
17310f97eae7SMatthias Ringwald     // Timeout 100 ms
17320f97eae7SMatthias Ringwald     // HCI Reset
17330f97eae7SMatthias Ringwald     // Command Complete Reset
17340f97eae7SMatthias Ringwald     // HCI Read Local Version Information
17350f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
17360f97eae7SMatthias Ringwald     // hang...
17370f97eae7SMatthias Ringwald     //
17380f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
17390f97eae7SMatthias Ringwald     if (!command_completed
1740a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
17410e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
17420f97eae7SMatthias Ringwald 
1743f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
17440f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
17450f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
17460f97eae7SMatthias Ringwald             return;
17470f97eae7SMatthias Ringwald         }
17480f97eae7SMatthias Ringwald     }
17490f97eae7SMatthias Ringwald 
17509f007422SMatthias Ringwald     // CSR & H5
17519f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
17529f007422SMatthias Ringwald     if (!command_completed
1753a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
17540e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
17559f007422SMatthias Ringwald 
17569f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
17579f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
17589f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
17599f007422SMatthias Ringwald             return;
17609f007422SMatthias Ringwald         }
17619f007422SMatthias Ringwald     }
17629f007422SMatthias Ringwald 
17639f007422SMatthias Ringwald     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
17649f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
17659f007422SMatthias Ringwald     if (command_completed){
17669f007422SMatthias Ringwald         switch (hci_stack->substate){
17679f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
17689f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
17699f007422SMatthias Ringwald                 break;
17709f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
17719f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
17729f007422SMatthias Ringwald                 break;
17739f007422SMatthias Ringwald             default:
17749f007422SMatthias Ringwald                 break;
17759f007422SMatthias Ringwald         }
17769f007422SMatthias Ringwald     }
17770f97eae7SMatthias Ringwald 
177806b9e820SMatthias Ringwald #endif
17790f97eae7SMatthias Ringwald 
1780a2481739S[email protected]     if (!command_completed) return;
1781a2481739S[email protected] 
178207fd2f31SMatthias Ringwald     bool need_baud_change = false;
178307fd2f31SMatthias Ringwald     bool need_addr_change = false;
178406b9e820SMatthias Ringwald 
178506b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
178606b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
17873fb36a29SMatthias Ringwald                         && hci_stack->chipset
17883fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
1789db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
17909796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1791db8bc6ffSMatthias Ringwald 
179206b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
17933fb36a29SMatthias Ringwald                         && hci_stack->chipset
17943fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
179506b9e820SMatthias Ringwald #endif
1796a80162e9SMatthias Ringwald 
17975c363727SMatthias Ringwald     switch(hci_stack->substate){
179806b9e820SMatthias Ringwald 
179906b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
18009f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
1801d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
18029f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
18039f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
18049f007422SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
18059f007422SMatthias Ringwald             break;
180674b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
1807528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
180876fcb19bSMatthias Ringwald             break;
1809e90bae01SMatthias Ringwald         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
181007fd2f31SMatthias Ringwald             log_info("Received local name, need baud change %d", (int) need_baud_change);
18112f48d920SMatthias Ringwald             if (need_baud_change){
18122f48d920SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
18132f48d920SMatthias Ringwald                 return;
18142f48d920SMatthias Ringwald             }
181553860077SMatthias Ringwald             // skip baud change
181674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
181774b323a9SMatthias Ringwald             return;
1818a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
18194696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
1820fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
182161f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
182296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1823cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
1824fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18254696bddbSMatthias Ringwald             }
182674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
182774b323a9SMatthias Ringwald             return;
1828a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1829528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
1830a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1831a80162e9SMatthias Ringwald             return;
183274b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
183374b323a9SMatthias Ringwald             // repeat custom init
183474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
183574b323a9SMatthias Ringwald             return;
183606b9e820SMatthias Ringwald #else
183706b9e820SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
183806b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
183906b9e820SMatthias Ringwald             return ;
184006b9e820SMatthias Ringwald #endif
184106b9e820SMatthias Ringwald 
1842a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
18430e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1844efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1845efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1846eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1847eb3a5314SMatthias Ringwald                 return;
1848eb3a5314SMatthias Ringwald             }
184953860077SMatthias Ringwald             if (need_addr_change){
185053860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
185153860077SMatthias Ringwald                 return;
185253860077SMatthias Ringwald             }
185353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
185453860077SMatthias Ringwald             return;
185506b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
18567224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
18577224be7eSMatthias Ringwald             if (need_baud_change){
185896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1859cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
1860fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18617224be7eSMatthias Ringwald             }
1862eb3a5314SMatthias Ringwald             if (need_addr_change){
1863eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1864eb3a5314SMatthias Ringwald                 return;
1865eb3a5314SMatthias Ringwald             }
1866eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1867eb3a5314SMatthias Ringwald             return;
186853860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
18696ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
18706ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
18716ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
187253860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
187353860077SMatthias Ringwald                 return;
187453860077SMatthias Ringwald             }
187553860077SMatthias Ringwald             // skipping st warm boot
187653860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
187753860077SMatthias Ringwald             return;
187853860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
187953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
188053860077SMatthias Ringwald             return;
188106b9e820SMatthias Ringwald #endif
188253860077SMatthias Ringwald         case HCI_INIT_W4_READ_BD_ADDR:
188353860077SMatthias Ringwald             // only read buffer size if supported
18844ea43905SMatthias Ringwald             if (hci_stack->local_supported_commands[0u] & 0x01u) {
188553860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
188653860077SMatthias Ringwald                 return;
188753860077SMatthias Ringwald             }
188853860077SMatthias Ringwald             // skipping read buffer size
188953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1890a828a756SMatthias Ringwald             return;
189174b323a9SMatthias Ringwald         case HCI_INIT_W4_SET_EVENT_MASK:
18926155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
18936155b3d3S[email protected]             if (!hci_classic_supported()){
18942c68f164SMatthias Ringwald #ifdef ENABLE_BLE
18956155b3d3S[email protected]                 if (hci_le_supported()){
189674b323a9SMatthias Ringwald                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
189774b323a9SMatthias Ringwald                     return;
18982c68f164SMatthias Ringwald                 }
18992c68f164SMatthias Ringwald #endif
19006155b3d3S[email protected]                 log_error("Neither BR/EDR nor LE supported");
1901a650ba4dSMatthias Ringwald                 hci_init_done();
190274b323a9SMatthias Ringwald                 return;
19036155b3d3S[email protected]             }
190415a95bd5SMatthias Ringwald             if (!gap_ssp_supported()){
19055c363727SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
190674b323a9SMatthias Ringwald                 return;
19076155b3d3S[email protected]             }
19086155b3d3S[email protected]             break;
1909903ea03aSMatthias Ringwald #ifdef ENABLE_BLE
1910a828a756SMatthias Ringwald         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1911a828a756SMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
19124ea43905SMatthias Ringwald             if (hci_stack->local_supported_commands[0u] & 0x02u) break;
1913daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1914daabb8b8SMatthias Ringwald             return;
1915daabb8b8SMatthias Ringwald 
1916b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1917b435e062SMatthias Ringwald         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
19186fab74dbSMatthias Ringwald             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
19194ea43905SMatthias Ringwald             if ((hci_stack->local_supported_commands[0u] & 0x30u) == 0x30u){
192080d7d618SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1921b435e062SMatthias Ringwald                 return;
1922b435e062SMatthias Ringwald             }
1923b435e062SMatthias Ringwald             // explicit fall through to reduce repetitions
1924b435e062SMatthias Ringwald 
1925b435e062SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1926b435e062SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1927903ea03aSMatthias Ringwald #else
1928903ea03aSMatthias Ringwald             hci_init_done();
1929903ea03aSMatthias Ringwald #endif
1930a828a756SMatthias Ringwald             return;
193106337f4fSMatthias Ringwald #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
193206337f4fSMatthias Ringwald 
193306337f4fSMatthias Ringwald #endif  /* ENABLE_BLE */
1934b435e062SMatthias Ringwald 
19355d23aae8SMatthias Ringwald         case HCI_INIT_W4_WRITE_INQUIRY_MODE:
19365d23aae8SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
19374ea43905SMatthias Ringwald             if (!hci_stack->secure_connections_enable || (hci_stack->local_supported_commands[1u] & 0x02u) == 0u) {
19385d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;
19395d23aae8SMatthias Ringwald                 return;
19405d23aae8SMatthias Ringwald             }
19415d23aae8SMatthias Ringwald             break;
19425d23aae8SMatthias Ringwald 
194347bc3ebbSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
19443b65523cSMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
19453905afbfSMatthias Ringwald             // skip write synchronous flow control if not supported
19463905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x04) break;
19473905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1948cf373d3aSMatthias Ringwald 
1949cf373d3aSMatthias Ringwald             /* fall through */
19503905afbfSMatthias Ringwald 
1951729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
19523905afbfSMatthias Ringwald             // skip write default erroneous data reporting if not supported
19533905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x08) break;
19543905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1955cf373d3aSMatthias Ringwald 
1956cf373d3aSMatthias Ringwald             /* fall through */
19573905afbfSMatthias Ringwald 
1958f064e0bbSMatthias Ringwald         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1959a42798c3SMatthias Ringwald             // skip bcm set sco pcm config on non-Broadcom chipsets
196061f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
19610168d82eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1962cf373d3aSMatthias Ringwald 
1963cf373d3aSMatthias Ringwald             /* fall through */
1964a42798c3SMatthias Ringwald 
1965a42798c3SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1966729ed62eSMatthias Ringwald             if (!hci_le_supported()){
1967729ed62eSMatthias Ringwald                 // SKIP LE init for Classic only configuration
1968a650ba4dSMatthias Ringwald                 hci_init_done();
1969729ed62eSMatthias Ringwald                 return;
1970729ed62eSMatthias Ringwald             }
1971afe9bf34SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1972729ed62eSMatthias Ringwald             break;
1973f3b012f9SMatthias Ringwald 
1974f3b012f9SMatthias Ringwald #else /* !ENABLE_SCO_OVER_HCI */
1975f3b012f9SMatthias Ringwald 
197674b323a9SMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
19778051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
19788051253fSMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) {
19798051253fSMatthias Ringwald                 hci_stack->substate = HCI_INIT_BCM_WRITE_SCO_PCM_INT;
19808051253fSMatthias Ringwald                 return;
19818051253fSMatthias Ringwald             }
19828051253fSMatthias Ringwald #endif
19838051253fSMatthias Ringwald             /* fall through */
19848051253fSMatthias Ringwald 
19854e821764SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
1986f3b012f9SMatthias Ringwald #ifdef ENABLE_BLE
1987f3b012f9SMatthias Ringwald             if (hci_le_supported()){
1988f3b012f9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
198974b323a9SMatthias Ringwald                 return;
19906155b3d3S[email protected]             }
1991729ed62eSMatthias Ringwald #endif
1992f3b012f9SMatthias Ringwald             // SKIP LE init for Classic only configuration
1993f3b012f9SMatthias Ringwald             hci_init_done();
1994f3b012f9SMatthias Ringwald             return;
1995f3b012f9SMatthias Ringwald #endif /* ENABLE_SCO_OVER_HCI */
1996f3b012f9SMatthias Ringwald 
1997a4e96e78SMatthias Ringwald // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1998a4e96e78SMatthias Ringwald #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1999a650ba4dSMatthias Ringwald         // Response to command before init done state -> init done
2000a650ba4dSMatthias Ringwald         case (HCI_INIT_DONE-1):
2001a650ba4dSMatthias Ringwald             hci_init_done();
2002a650ba4dSMatthias Ringwald             return;
2003a4e96e78SMatthias Ringwald #endif
2004a650ba4dSMatthias Ringwald 
20056155b3d3S[email protected]         default:
200674b323a9SMatthias Ringwald             break;
20076155b3d3S[email protected]     }
200855975f88SMatthias Ringwald     hci_initializing_next_state();
20096155b3d3S[email protected] }
20106155b3d3S[email protected] 
20110bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2012229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
20130bbba85bSMatthias Ringwald     bd_addr_t bd_address;
20146535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
20150bbba85bSMatthias Ringwald 
20166bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
20176bc9fa5eSMatthias Ringwald     // cache needed data
20186bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
20196bc9fa5eSMatthias Ringwald #endif
20206bc9fa5eSMatthias Ringwald 
20210bbba85bSMatthias Ringwald     // connection failed, remove entry
20220bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
20230bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
20240bbba85bSMatthias Ringwald 
20256bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
20260bbba85bSMatthias Ringwald     // notify client if dedicated bonding
20270bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
20280bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
20290bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
20300bbba85bSMatthias Ringwald     }
20310bbba85bSMatthias Ringwald 
20320bbba85bSMatthias Ringwald     // if authentication error, also delete link key
20330bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
20340bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
20350bbba85bSMatthias Ringwald     }
20361c79b5e3SMatthias Ringwald #else
20371c79b5e3SMatthias Ringwald     UNUSED(status);
20386bc9fa5eSMatthias Ringwald #endif
20390bbba85bSMatthias Ringwald }
20400bbba85bSMatthias Ringwald 
2041be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
20422f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
20432f5c44baSMatthias Ringwald     // SSP Controller
20442f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
20452f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
20462f5c44baSMatthias Ringwald     }
20472f5c44baSMatthias Ringwald     // eSCO
20482f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
20492f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
20502f5c44baSMatthias Ringwald     }
20512f5c44baSMatthias Ringwald     // Extended features
20522f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
20532f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
20542f5c44baSMatthias Ringwald     }
20552f5c44baSMatthias Ringwald }
20562f5c44baSMatthias Ringwald 
20572f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
20582f5c44baSMatthias Ringwald     // SSP Host
20592f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
20602f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
20612f5c44baSMatthias Ringwald     }
206250c51a77SMatthias Ringwald     // SC Host
206350c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
206450c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
206550c51a77SMatthias Ringwald     }
206650c51a77SMatthias Ringwald }
206750c51a77SMatthias Ringwald 
206850c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
206950c51a77SMatthias Ringwald     // SC Controller
207050c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
207150c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
207250c51a77SMatthias Ringwald     }
20732f5c44baSMatthias Ringwald }
20742f5c44baSMatthias Ringwald 
2075de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
2076de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
207749bafb5eSMatthias Ringwald     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2078de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
2079de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2080de0df013SMatthias Ringwald     }
2081de0df013SMatthias Ringwald }
2082128825c3SMatthias Ringwald static bool hci_remote_sc_enabled(hci_connection_t * connection){
2083128825c3SMatthias Ringwald     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2084128825c3SMatthias Ringwald     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2085128825c3SMatthias Ringwald }
2086128825c3SMatthias Ringwald 
2087be500194SMatthias Ringwald #endif
2088de0df013SMatthias Ringwald 
208967c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
209067c6c9dcSMatthias Ringwald     // handle BT initialization
209167c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
209267c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
209367c6c9dcSMatthias Ringwald     }
209467c6c9dcSMatthias Ringwald 
209567c6c9dcSMatthias Ringwald     // help with BT sleep
209667c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
209767c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
209867c6c9dcSMatthias Ringwald         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)) {
209967c6c9dcSMatthias Ringwald         hci_initializing_next_state();
210067c6c9dcSMatthias Ringwald     }
210167c6c9dcSMatthias Ringwald }
210267c6c9dcSMatthias Ringwald 
21039866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
21049866fdc7SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
21058daf94bcSMatthias Ringwald     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
21069866fdc7SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
2107abdad579SMatthias Ringwald 
21088daf94bcSMatthias Ringwald     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
21091cf0a6c8SMatthias Ringwald         conn->requested_security_level = LEVEL_0;
21109866fdc7SMatthias Ringwald         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
2111abdad579SMatthias Ringwald         return;
2112abdad579SMatthias Ringwald     }
2113abdad579SMatthias Ringwald 
2114abdad579SMatthias Ringwald     // Request Authentication if not already done
2115abdad579SMatthias Ringwald     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2116abdad579SMatthias Ringwald     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
21179866fdc7SMatthias Ringwald }
21189866fdc7SMatthias Ringwald #endif
21199866fdc7SMatthias Ringwald 
21204f781026SMatthias Ringwald static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2121b08371a9SMilanka Ringwald     UNUSED(size);
2122e76a89eeS[email protected] 
21239cbd2215SMatthias Ringwald     uint16_t manufacturer;
21249cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
2125fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
21261f7b95a1Smatthias.ringwald     hci_connection_t * conn;
2127645b7c25SMatthias Ringwald     uint8_t status;
21289cbd2215SMatthias Ringwald #endif
21296bef4003SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
21306bef4003SMatthias Ringwald     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
21317ec5eeaaSmatthias.ringwald 
2132645b7c25SMatthias Ringwald     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2133645b7c25SMatthias Ringwald     switch (opcode){
2134645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2135645b7c25SMatthias Ringwald             if (packet[5]) break;
21369e263bd7SMatthias Ringwald             // terminate, name 248 chars
21379e263bd7SMatthias Ringwald             packet[6+248] = 0;
21389e263bd7SMatthias Ringwald             log_info("local name: %s", &packet[6]);
2139645b7c25SMatthias Ringwald             break;
2140645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
21411d279b20Smatthias.ringwald             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2142c3b46f5aSMatthias Ringwald             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2143429122ccSMatthias Ringwald                 uint16_t acl_len = little_endian_read_16(packet, 6);
2144429122ccSMatthias Ringwald                 uint16_t sco_len = packet[8];
2145429122ccSMatthias Ringwald 
2146429122ccSMatthias Ringwald                 // determine usable ACL/SCO payload size
2147429122ccSMatthias Ringwald                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2148429122ccSMatthias Ringwald                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2149429122ccSMatthias Ringwald 
2150f8fbdce0SMatthias Ringwald                 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9);
2151f8fbdce0SMatthias Ringwald                 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11);
2152a8b12447S[email protected] 
2153429122ccSMatthias Ringwald                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2154429122ccSMatthias Ringwald                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
21551a06f663S[email protected]                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2156c3b46f5aSMatthias Ringwald             }
2157645b7c25SMatthias Ringwald             break;
2158645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_RSSI:
2159645b7c25SMatthias Ringwald             if (packet[5] == ERROR_CODE_SUCCESS){
2160891b9fc2SMatthias Ringwald                 uint8_t event[5];
2161891b9fc2SMatthias Ringwald                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2162891b9fc2SMatthias Ringwald                 event[1] = 3;
21636535961aSMatthias Ringwald                 (void)memcpy(&event[2], &packet[6], 3);
2164891b9fc2SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2165891b9fc2SMatthias Ringwald             }
2166645b7c25SMatthias Ringwald             break;
2167a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2168645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2169f8fbdce0SMatthias Ringwald             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2170ee303eddS[email protected]             hci_stack->le_acl_packets_total_num = packet[8];
21716c26b087S[email protected]             // determine usable ACL payload size
21726c26b087S[email protected]             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
21736c26b087S[email protected]                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
21746c26b087S[email protected]             }
21759da54300S[email protected]             log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
2176645b7c25SMatthias Ringwald             break;
2177b435e062SMatthias Ringwald #endif
2178b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2179645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2180dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2181dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2182dcd678baSMatthias Ringwald             log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2183645b7c25SMatthias Ringwald             break;
2184b435e062SMatthias Ringwald #endif
2185d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2186645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2187e691bb38SMatthias Ringwald             hci_stack->le_whitelist_capacity = packet[6];
218815d0a15bSMatthias Ringwald             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2189645b7c25SMatthias Ringwald             break;
219065a46ef3S[email protected] #endif
2191645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BD_ADDR:
2192645b7c25SMatthias Ringwald             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2193645b7c25SMatthias Ringwald             log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
219433373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
21951624665aSMatthias Ringwald             if (hci_stack->link_key_db){
21961624665aSMatthias Ringwald                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
21971624665aSMatthias Ringwald             }
219833373e40SMatthias Ringwald #endif
2199645b7c25SMatthias Ringwald             break;
220035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2201645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
22023a9fb326S[email protected]             hci_emit_discoverable_enabled(hci_stack->discoverable);
2203645b7c25SMatthias Ringwald             break;
2204645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2205f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2206f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2207f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2208f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2209f5875de5SMatthias Ringwald             }
2210645b7c25SMatthias Ringwald             break;
221135454696SMatthias Ringwald #endif
2212645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
22134f781026SMatthias Ringwald             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
221465389bfcS[email protected] 
221535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2216a5a23fc2S[email protected]             // determine usable ACL packet types based on host buffer size and supported features
2217a5a23fc2S[email protected]             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
22188b96126aSMatthias Ringwald             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
221935454696SMatthias Ringwald #endif
2220f5d8d141S[email protected]             // Classic/LE
2221f5d8d141S[email protected]             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2222645b7c25SMatthias Ringwald             break;
2223645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2224645b7c25SMatthias Ringwald             manufacturer = little_endian_read_16(packet, 10);
2225c21d89f3SMatthias Ringwald             // map Cypress to Broadcom
2226c21d89f3SMatthias Ringwald             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2227c21d89f3SMatthias Ringwald                 log_info("Treat Cypress as Broadcom");
2228c21d89f3SMatthias Ringwald                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2229c21d89f3SMatthias Ringwald                 little_endian_store_16(packet, 10, manufacturer);
2230c21d89f3SMatthias Ringwald             }
2231c21d89f3SMatthias Ringwald             hci_stack->manufacturer = manufacturer;
22324696bddbSMatthias Ringwald             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2233645b7c25SMatthias Ringwald             break;
2234645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2235a828a756SMatthias Ringwald             hci_stack->local_supported_commands[0] =
22364ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+14u] & 0x80u) >> 7u) |  // bit  0 = Octet 14, bit 7 / Read Buffer Size
22374ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+24u] & 0x40u) >> 5u) |  // bit  1 = Octet 24, bit 6 / Write Le Host Supported
22384ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+10u] & 0x10u) >> 2u) |  // bit  2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
22394ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+18u] & 0x08u)     )  |  // bit  3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
22404ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x01u) << 4u) |  // bit  4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
22414ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x08u) << 2u) |  // bit  5 = Octet 35, bit 3 / LE Read Maximum Data Length
22424ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x20u) << 1u) |  // bit  6 = Octet 35, bit 5 / LE Set Default PHY
22434ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+20u] & 0x10u) << 3u);   // bit  7 = Octet 20, bit 4 / Read Encryption Key Size
22448d2d8af1SMatthias Ringwald             hci_stack->local_supported_commands[1] =
22454ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+ 2u] & 0x40u) >> 6u) |  // bit  8 = Octet  2, bit 6 / Read Remote Extended Features
224699b14827SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x08u) >> 2u) |  // bit  9 = Octet 32, bit 3 / Write Secure Connections Host
2247f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x02u) << 1u) |  // bit 10 = Octet 35, bit 1 / LE Set Address Resolution Enable
2248f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x02u) << 2u) |  // bit 11 = Octet 32, bit 1 / Remote OOB Extended Data Request Reply
2249f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x40u) >> 2u);   // bit 12 = Octet 32, bit 6 / Read Local OOB Extended Data command
22508d2d8af1SMatthias Ringwald             log_info("Local supported commands summary %02x - %02x", hci_stack->local_supported_commands[0],  hci_stack->local_supported_commands[1]);
2251645b7c25SMatthias Ringwald             break;
2252e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
2253645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
22544f781026SMatthias Ringwald             if (packet[5]) return;
22555b9b590fSMatthias Ringwald             hci_stack->synchronous_flow_control_enabled = 1;
2256645b7c25SMatthias Ringwald             break;
2257645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2258645b7c25SMatthias Ringwald             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2259573897a0SMatthias Ringwald             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2260573897a0SMatthias Ringwald             conn   = hci_connection_for_handle(handle);
2261c3b46f5aSMatthias Ringwald             if (conn != NULL) {
22629866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
2263573897a0SMatthias Ringwald                 if (status == 0){
22649866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
22654a659b0eSMatthias Ringwald                     log_info("Handle %04x key Size: %u", handle, key_size);
2266170fafaeSMatthias Ringwald                 } else {
2267e9f98c4aSMatthias Ringwald                     key_size = 1;
22689866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2269573897a0SMatthias Ringwald                 }
22709866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2271c3b46f5aSMatthias Ringwald             }
2272645b7c25SMatthias Ringwald             break;
2273cc15bb2cSMatthias Ringwald         // assert pairing complete event is emitted.
2274cc15bb2cSMatthias Ringwald         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2275cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2276cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2277cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
2278cc15bb2cSMatthias Ringwald             // lookup connection by gap pairing addr
2279cc15bb2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2280cc15bb2cSMatthias Ringwald             if (conn == NULL) break;
2281cc15bb2cSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2282cc15bb2cSMatthias Ringwald             break;
2283cc15bb2cSMatthias Ringwald 
228475a8e4faSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
228575a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
228675a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
228775a8e4faSMatthias Ringwald             uint8_t event[67];
228875a8e4faSMatthias Ringwald             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
228975a8e4faSMatthias Ringwald             event[1] = 65;
229075a8e4faSMatthias Ringwald             (void)memset(&event[2], 0, 65);
229175a8e4faSMatthias Ringwald             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
229275a8e4faSMatthias Ringwald                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
229375a8e4faSMatthias Ringwald                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
229475a8e4faSMatthias Ringwald                     event[2] = 3;
229575a8e4faSMatthias Ringwald                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
229675a8e4faSMatthias Ringwald                 } else {
229775a8e4faSMatthias Ringwald                     event[2] = 1;
229875a8e4faSMatthias Ringwald                 }
229975a8e4faSMatthias Ringwald             }
230075a8e4faSMatthias Ringwald             hci_emit_event(event, sizeof(event), 0);
230175a8e4faSMatthias Ringwald             break;
230275a8e4faSMatthias Ringwald         }
23031ae74bf3SMatthias Ringwald 
23041ae74bf3SMatthias Ringwald         // note: only needed if user does not provide OOB data
23051ae74bf3SMatthias Ringwald         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
23061ae74bf3SMatthias Ringwald             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
23071ae74bf3SMatthias Ringwald             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
23081ae74bf3SMatthias Ringwald             if (conn == NULL) break;
23091ae74bf3SMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
23101ae74bf3SMatthias Ringwald             break;
2311e8c8828eSMatthias Ringwald #endif
231275a8e4faSMatthias Ringwald #endif
23136f35bb46SMatthias Ringwald         default:
23146f35bb46SMatthias Ringwald             break;
23154f781026SMatthias Ringwald     }
2316645b7c25SMatthias Ringwald }
23174f781026SMatthias Ringwald 
23180ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
23190ce3f217SMatthias Ringwald static void event_handle_le_connection_complete(const uint8_t * packet){
23200ce3f217SMatthias Ringwald 	bd_addr_t addr;
23210ce3f217SMatthias Ringwald 	bd_addr_type_t addr_type;
23220ce3f217SMatthias Ringwald 	hci_connection_t * conn;
23230ce3f217SMatthias Ringwald 
23240ce3f217SMatthias Ringwald 	// Connection management
23250ce3f217SMatthias Ringwald 	reverse_bd_addr(&packet[8], addr);
23260ce3f217SMatthias Ringwald 	addr_type = (bd_addr_type_t)packet[7];
23270ce3f217SMatthias Ringwald 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
23280ce3f217SMatthias Ringwald 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
23290ce3f217SMatthias Ringwald 
23300ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23310ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
23320ce3f217SMatthias Ringwald 	if (packet[3]){
23330ce3f217SMatthias Ringwald 
23340ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
23350ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
23360ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
23370ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
23380ce3f217SMatthias Ringwald 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
23391f468175SMatthias Ringwald 		    // reset state
23400ce3f217SMatthias Ringwald             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
23411f468175SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
23420ce3f217SMatthias Ringwald 			// get outgoing connection conn struct for direct connect
23430ce3f217SMatthias Ringwald 			conn = gap_get_outgoing_connection();
23440ce3f217SMatthias Ringwald 		}
23450ce3f217SMatthias Ringwald 
23460ce3f217SMatthias Ringwald 		// outgoing le connection establishment is done
23470ce3f217SMatthias Ringwald 		if (conn){
23480ce3f217SMatthias Ringwald 			// remove entry
23490ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
23500ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
23510ce3f217SMatthias Ringwald 		}
23520ce3f217SMatthias Ringwald 		return;
23530ce3f217SMatthias Ringwald 	}
23540ce3f217SMatthias Ringwald #endif
23550ce3f217SMatthias Ringwald 
23560ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
23570ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_MASTER){
23580ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23590ce3f217SMatthias Ringwald 		// if we're master on an le connection, it was an outgoing connection and we're done with it
23600ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
23610ce3f217SMatthias Ringwald 		if (hci_is_le_connection_type(addr_type)){
23620ce3f217SMatthias Ringwald 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
23630ce3f217SMatthias Ringwald 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
23640ce3f217SMatthias Ringwald 		}
23650ce3f217SMatthias Ringwald #endif
23660ce3f217SMatthias Ringwald 	} else {
23670ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23680ce3f217SMatthias Ringwald 		// if we're slave, it was an incoming connection, advertisements have stopped
23690ce3f217SMatthias Ringwald 		hci_stack->le_advertisements_active = false;
23700ce3f217SMatthias Ringwald #endif
23710ce3f217SMatthias Ringwald 	}
23720ce3f217SMatthias Ringwald 
23730ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
23740ce3f217SMatthias Ringwald 	if (!conn){
23750ce3f217SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
23760ce3f217SMatthias Ringwald 	}
23770ce3f217SMatthias Ringwald 
23780ce3f217SMatthias Ringwald 	// no memory, sorry.
23790ce3f217SMatthias Ringwald 	if (!conn){
23800ce3f217SMatthias Ringwald 		return;
23810ce3f217SMatthias Ringwald 	}
23820ce3f217SMatthias Ringwald 
23830ce3f217SMatthias Ringwald 	conn->state = OPEN;
23840ce3f217SMatthias Ringwald 	conn->role  = packet[6];
23850ce3f217SMatthias Ringwald 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
23860ce3f217SMatthias Ringwald 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
23870ce3f217SMatthias Ringwald 
23880ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23890ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_SLAVE){
23900ce3f217SMatthias Ringwald 		hci_update_advertisements_enabled_for_current_roles();
23910ce3f217SMatthias Ringwald 	}
23920ce3f217SMatthias Ringwald #endif
23930ce3f217SMatthias Ringwald 
2394dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
2395dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
2396dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
2397dde9ff1eSMatthias Ringwald 
23980ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
23990ce3f217SMatthias Ringwald 
24000ce3f217SMatthias Ringwald 	// restart timer
24010ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
24020ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
24030ce3f217SMatthias Ringwald 
24040ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
24050ce3f217SMatthias Ringwald 
24060ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
24070ce3f217SMatthias Ringwald }
24080ce3f217SMatthias Ringwald #endif
24090ce3f217SMatthias Ringwald 
241017c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
241117c6fe5cSMatthias Ringwald static bool hci_ssp_security_level_possible_for_io_cap(gap_security_level_t level, uint8_t io_cap_local, uint8_t io_cap_remote){
241217c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
241317c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
24149a8f78c1SMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
24159a8f78c1SMatthias Ringwald     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
241617c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
24179a8f78c1SMatthias Ringwald         // MITM not possible without keyboard or display
241817c6fe5cSMatthias Ringwald         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
241917c6fe5cSMatthias Ringwald         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
24209a8f78c1SMatthias Ringwald 
24219a8f78c1SMatthias Ringwald         // MITM possible if one side has keyboard and the other has keyboard or display
24229a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
24239a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
24249a8f78c1SMatthias Ringwald 
24259a8f78c1SMatthias Ringwald         // MITM not possible if one side has only display and other side has no keyboard
24269a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
24279a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
242817c6fe5cSMatthias Ringwald     }
242917c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
243017c6fe5cSMatthias Ringwald     return true;
243117c6fe5cSMatthias Ringwald }
24323817f9dfSMatthias Ringwald 
24333817f9dfSMatthias Ringwald static bool btstack_is_null(uint8_t * data, uint16_t size){
24343817f9dfSMatthias Ringwald     uint16_t i;
24353817f9dfSMatthias Ringwald     for (i=0; i < size ; i++){
24363817f9dfSMatthias Ringwald         if (data[i] != 0) {
24373817f9dfSMatthias Ringwald             return false;
24383817f9dfSMatthias Ringwald         }
24393817f9dfSMatthias Ringwald     }
24403817f9dfSMatthias Ringwald     return true;
24413817f9dfSMatthias Ringwald }
24423817f9dfSMatthias Ringwald 
244317c6fe5cSMatthias Ringwald #endif
244417c6fe5cSMatthias Ringwald 
2445c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
24464f781026SMatthias Ringwald 
24474f781026SMatthias Ringwald     uint16_t event_length = packet[1];
24484f781026SMatthias Ringwald 
24494f781026SMatthias Ringwald     // assert packet is complete
24504ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
24514f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
24524f781026SMatthias Ringwald         return;
24534f781026SMatthias Ringwald     }
24544f781026SMatthias Ringwald 
24554f781026SMatthias Ringwald     bd_addr_type_t addr_type;
24564f781026SMatthias Ringwald     hci_con_handle_t handle;
24574f781026SMatthias Ringwald     hci_connection_t * conn;
24584f781026SMatthias Ringwald     int i;
24594f781026SMatthias Ringwald     int create_connection_cmd;
24604f781026SMatthias Ringwald 
24614f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
24625e91d96cSMatthias Ringwald     hci_link_type_t link_type;
246348f33f37SMatthias Ringwald     bd_addr_t addr;
24644f781026SMatthias Ringwald #endif
24654f781026SMatthias Ringwald 
24664f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
24674f781026SMatthias Ringwald 
24684f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
24694f781026SMatthias Ringwald 
24704f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
24714f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
247256cf178bSmatthias.ringwald             break;
247356cf178bSmatthias.ringwald 
24747ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
24756bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
24766bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2477229331c6SMatthias Ringwald 
2478229331c6SMatthias Ringwald             // check command status to detected failed outgoing connections
2479c57fa566SMatthias Ringwald             create_connection_cmd = 0;
2480c57fa566SMatthias Ringwald #ifdef ENABLE_CLASSIC
2481c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2482c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2483c57fa566SMatthias Ringwald             }
2484c57fa566SMatthias Ringwald #endif
2485c57fa566SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2486c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2487c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2488c57fa566SMatthias Ringwald             }
2489c57fa566SMatthias Ringwald #endif
2490c57fa566SMatthias Ringwald             if (create_connection_cmd) {
2491229331c6SMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
24928da98cbeSMatthias Ringwald                 addr_type = hci_stack->outgoing_addr_type;
24936ea9315cSMatthias Ringwald                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
24946ea9315cSMatthias Ringwald                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), addr_type);
2495229331c6SMatthias Ringwald 
2496229331c6SMatthias Ringwald                 // reset outgoing address info
2497229331c6SMatthias Ringwald                 memset(hci_stack->outgoing_addr, 0, 6);
2498229331c6SMatthias Ringwald                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2499229331c6SMatthias Ringwald 
25006ea9315cSMatthias Ringwald                 // on error
25016ea9315cSMatthias Ringwald                 if (status != ERROR_CODE_SUCCESS){
2502f75e06adSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
25036ea9315cSMatthias Ringwald                     if (hci_is_le_connection_type(addr_type)){
25046ea9315cSMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2505f7e6a692SMatthias Ringwald                         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
25066ea9315cSMatthias Ringwald                     }
2507f75e06adSMatthias Ringwald #endif
2508229331c6SMatthias Ringwald                     // error => outgoing connection failed
25096ea9315cSMatthias Ringwald                     if (conn != NULL){
2510229331c6SMatthias Ringwald                         hci_handle_connection_failed(conn, status);
2511229331c6SMatthias Ringwald                     }
2512229331c6SMatthias Ringwald                 }
25136ea9315cSMatthias Ringwald             }
2514beb3c81dSMatthias Ringwald 
2515beb3c81dSMatthias Ringwald #ifdef ENABLE_CLASSIC
2516beb3c81dSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_inquiry)) {
2517beb3c81dSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2518beb3c81dSMatthias Ringwald                 log_info("command status (inquiry), status %x", status);
2519beb3c81dSMatthias Ringwald                 if (status == ERROR_CODE_SUCCESS) {
2520beb3c81dSMatthias Ringwald                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2521beb3c81dSMatthias Ringwald                 } else {
2522beb3c81dSMatthias Ringwald                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2523beb3c81dSMatthias Ringwald                 }
2524beb3c81dSMatthias Ringwald             }
2525beb3c81dSMatthias Ringwald #endif
25267ec5eeaaSmatthias.ringwald             break;
25277ec5eeaaSmatthias.ringwald 
25282e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
25299784dac1SMatthias Ringwald             if (size < 3) return;
25309784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
25314ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
25329784dac1SMatthias Ringwald             uint16_t offset = 3;
25339784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
25344ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
25354ea43905SMatthias Ringwald                 offset += 2u;
2536f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
25374ea43905SMatthias Ringwald                 offset += 2u;
25382e440c8aS[email protected] 
25395061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
254056cf178bSmatthias.ringwald                 if (!conn){
25419da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
254256cf178bSmatthias.ringwald                     continue;
254356cf178bSmatthias.ringwald                 }
254423bed257S[email protected] 
2545ce41473eSMatthias Ringwald                 if (conn->num_packets_sent >= num_packets){
2546ce41473eSMatthias Ringwald                     conn->num_packets_sent -= num_packets;
2547e35edcc1S[email protected]                 } else {
2548ce41473eSMatthias Ringwald                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2549ce41473eSMatthias Ringwald                     conn->num_packets_sent = 0;
2550e35edcc1S[email protected]                 }
2551ce41473eSMatthias Ringwald                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2552760b20efSMatthias Ringwald 
2553760b20efSMatthias Ringwald #ifdef ENABLE_CLASSIC
2554760b20efSMatthias Ringwald                 // For SCO, we do the can_send_now_check here
2555760b20efSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
2556760b20efSMatthias Ringwald #endif
255756cf178bSmatthias.ringwald             }
25586772a24cSmatthias.ringwald             break;
25592e440c8aS[email protected]         }
256035454696SMatthias Ringwald 
256135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2562f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
2563f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2564f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2565f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2566f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2567f5875de5SMatthias Ringwald             }
2568f5875de5SMatthias Ringwald             break;
2569b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2570b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2571b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2572b7f1ee76SMatthias Ringwald             }
2573b7f1ee76SMatthias Ringwald             break;
25741f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
2575724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
25765e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
257772cf8859SMatthias Ringwald 
257872cf8859SMatthias Ringwald             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
257972cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
258072cf8859SMatthias Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
258172cf8859SMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
258272cf8859SMatthias Ringwald                 break;
258372cf8859SMatthias Ringwald             }
258472cf8859SMatthias Ringwald 
258507e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
25865e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
25874536712cSMilanka Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
258807e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
258907e010b6SMilanka Ringwald                     break;
259007e010b6SMilanka Ringwald                 }
259107e010b6SMilanka Ringwald             }
259207e010b6SMilanka Ringwald 
259337eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
25945e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
25955e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
25962e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
25971f7b95a1Smatthias.ringwald             if (!conn) {
25985293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
25991f7b95a1Smatthias.ringwald             }
2600ce4c8fabSmatthias.ringwald             if (!conn) {
2601ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
26024536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2603058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
2604ce4c8fabSmatthias.ringwald                 break;
2605ce4c8fabSmatthias.ringwald             }
26065cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
260732ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
2608f3a16b9aSMatthias Ringwald             // store info about eSCO
26095e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
261076ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
2611f3a16b9aSMatthias Ringwald             }
261232ab9390Smatthias.ringwald             hci_run();
26131f7b95a1Smatthias.ringwald             break;
26141f7b95a1Smatthias.ringwald 
26156772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2616fe1ed1b8Smatthias.ringwald             // Connection management
2617724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
26189da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2619f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
26202e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2621fe1ed1b8Smatthias.ringwald             if (conn) {
2622b448a0e7Smatthias.ringwald                 if (!packet[2]){
2623c8e4258aSmatthias.ringwald                     conn->state = OPEN;
2624f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
26256909f064SMatthias Ringwald 
26266909f064SMatthias Ringwald                     // queue get remote feature
2627ba018746SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2628ee091cf1Smatthias.ringwald 
2629e6c51921SMatthias Ringwald                     // queue set supervision timeout if we're master
2630d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
26318daf94bcSMatthias Ringwald                         connectionSetAuthenticationFlags(conn, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
26326909f064SMatthias Ringwald                     }
26336909f064SMatthias Ringwald 
2634c785ef68Smatthias.ringwald                     // restart timer
2635528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2636528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
2637c785ef68Smatthias.ringwald 
26389da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
263943bfb1bdSmatthias.ringwald 
264043bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
2641b448a0e7Smatthias.ringwald                 } else {
26420bbba85bSMatthias Ringwald                     // connection failed
26430bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
2644fe1ed1b8Smatthias.ringwald                 }
2645fe1ed1b8Smatthias.ringwald             }
26466772a24cSmatthias.ringwald             break;
2647fe1ed1b8Smatthias.ringwald 
264844d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2649724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
265044d0e3d5S[email protected]             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
26511a06f663S[email protected]             if (packet[2]){
265244d0e3d5S[email protected]                 // connection failed
265344d0e3d5S[email protected]                 break;
265444d0e3d5S[email protected]             }
26552e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2656e35edcc1S[email protected]             if (!conn) {
2657e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2658e35edcc1S[email protected]             }
2659e35edcc1S[email protected]             if (!conn) {
2660e35edcc1S[email protected]                 break;
2661e35edcc1S[email protected]             }
26621a06f663S[email protected]             conn->state = OPEN;
2663f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
2664ee752bb8SMatthias Ringwald 
2665ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2666ee752bb8SMatthias Ringwald             // update SCO
2667ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2668ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2669ee752bb8SMatthias Ringwald             }
2670f234b250SMatthias Ringwald             // trigger can send now
2671f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
2672f234b250SMatthias Ringwald                 hci_stack->sco_can_send_now = 1;
2673f234b250SMatthias Ringwald             }
2674ee752bb8SMatthias Ringwald #endif
2675cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
2676cb70c5abSMatthias Ringwald             // configure sco transport
2677cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
2678cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
2679cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
2680cb70c5abSMatthias Ringwald             }
2681cb70c5abSMatthias Ringwald #endif
268244d0e3d5S[email protected]             break;
268344d0e3d5S[email protected] 
2684afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2685f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2686afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
2687afd4e962S[email protected]             if (!conn) break;
2688afd4e962S[email protected]             if (!packet[2]){
26892f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
26902f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
26912f5c44baSMatthias Ringwald 
26925ccef624SMatthias Ringwald                 // read extended features if possible
26935ccef624SMatthias Ringwald                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
26945ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
26955ccef624SMatthias Ringwald                     break;
26965ccef624SMatthias Ringwald                 }
26975ccef624SMatthias Ringwald             }
26985ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
26995ccef624SMatthias Ringwald             break;
27005ccef624SMatthias Ringwald 
27015ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
27025ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
27035ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
27045ccef624SMatthias Ringwald             if (!conn) break;
27055ccef624SMatthias Ringwald             // status = ok, page = 1
270650c51a77SMatthias Ringwald             if (!packet[2]) {
270750c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
270850c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
27095ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
271050c51a77SMatthias Ringwald                 bool done = false;
271150c51a77SMatthias Ringwald                 switch (page_number){
271250c51a77SMatthias Ringwald                     case 1:
27132f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
271450c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
271550c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
271650c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
271750c51a77SMatthias Ringwald                         } else {
271850c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
271950c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
272050c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
272150c51a77SMatthias Ringwald                             }
272250c51a77SMatthias Ringwald                             done = true;
272350c51a77SMatthias Ringwald                         }
272450c51a77SMatthias Ringwald                         break;
272550c51a77SMatthias Ringwald                     case 2:
272650c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
272750c51a77SMatthias Ringwald                         done = true;
272850c51a77SMatthias Ringwald                         break;
272950c51a77SMatthias Ringwald                     default:
273050c51a77SMatthias Ringwald                         break;
273150c51a77SMatthias Ringwald                 }
273250c51a77SMatthias Ringwald                 if (!done) break;
2733afd4e962S[email protected]             }
2734de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
2735afd4e962S[email protected]             break;
2736afd4e962S[email protected] 
27377fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
2738608f51bbSMatthias Ringwald             // request handled by hci_run()
27398daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
2740608f51bbSMatthias Ringwald             break;
27417fde4af9Smatthias.ringwald 
27429ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
27431714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
2744f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
27459ab95c90S[email protected]             if (!conn) break;
27461714cbbdSMatthias Ringwald 
27471714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
27481714cbbdSMatthias Ringwald 
27493817f9dfSMatthias Ringwald             // CVE-2020-26555: ignore NULL link key
27503817f9dfSMatthias Ringwald             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
27513817f9dfSMatthias Ringwald             if (btstack_is_null(&packet[8], 16)) break;
27523817f9dfSMatthias Ringwald 
27537bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
27549ab95c90S[email protected]             // Change Connection Encryption keeps link key type
27559ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
27569ab95c90S[email protected]                 conn->link_key_type = link_key_type;
27579ab95c90S[email protected]             }
27583817f9dfSMatthias Ringwald 
2759e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
2760e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
2761e9f98c4aSMatthias Ringwald 
2762bec5f683SMatthias Ringwald             // only store link key:
2763bec5f683SMatthias Ringwald             // - if bondable enabled
2764bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
27656edaed7fSMatthias Ringwald             // - if security level sufficient
27666edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
2767bec5f683SMatthias Ringwald             // - for SSP, also check if remote side requested bonding as well
2768bec5f683SMatthias Ringwald             if (conn->link_key_type != COMBINATION_KEY){
2769532454f9SMatthias Ringwald                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2770532454f9SMatthias Ringwald                 if (!remote_bonding){
2771bec5f683SMatthias Ringwald                     break;
2772bec5f683SMatthias Ringwald                 }
2773bec5f683SMatthias Ringwald             }
277455597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
27757fde4af9Smatthias.ringwald             break;
27769ab95c90S[email protected]         }
27777fde4af9Smatthias.ringwald 
27787fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
27791714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
27801714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
27811714cbbdSMatthias Ringwald             if (!conn) break;
27821714cbbdSMatthias Ringwald 
27831714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
2784a800d95eSMatthias Ringwald             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
27853a9fb326S[email protected]             if (!hci_stack->bondable ){
27868daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
27871714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
2788f8fb5f6eS[email protected]                 hci_run();
2789f8fb5f6eS[email protected]                 return;
27904c57c146S[email protected]             }
2791a800d95eSMatthias Ringwald             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
2792a800d95eSMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
2793a800d95eSMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
279450dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
279550dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
279650dcc63cSMatthias Ringwald                 hci_run();
279750dcc63cSMatthias Ringwald                 return;
279850dcc63cSMatthias Ringwald             }
27997fde4af9Smatthias.ringwald             break;
28007fde4af9Smatthias.ringwald 
280150d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
280250d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
280350d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
280450d7398cSMatthias Ringwald             if (!conn) break;
28051714cbbdSMatthias Ringwald 
28068daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
28071714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
280850d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
2809e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
2810d22b82d6SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
2811d22b82d6SMatthias Ringwald             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
2812d22b82d6SMatthias Ringwald #endif
281350d7398cSMatthias Ringwald             break;
281450d7398cSMatthias Ringwald 
28151d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
28161714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
28171714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
28181714cbbdSMatthias Ringwald             if (!conn) break;
28191714cbbdSMatthias Ringwald 
28209671e615SMatthias Ringwald             hci_connection_timestamp(conn);
28219671e615SMatthias Ringwald 
28221714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
28239671e615SMatthias Ringwald 
2824*ebde8a60SMatthias Ringwald             // assess security: LEVEL 4 requires SC
28259671e615SMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode || (conn->requested_security_level == LEVEL_4)) && !hci_remote_sc_enabled(conn)){
28269671e615SMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
28279671e615SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
28289671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
28299671e615SMatthias Ringwald                 break;
28309671e615SMatthias Ringwald             }
28319671e615SMatthias Ringwald 
2832*ebde8a60SMatthias Ringwald             // assess security based on io capabilities
2833*ebde8a60SMatthias Ringwald             if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
2834*ebde8a60SMatthias Ringwald                 // responder: fully validate io caps of both sides
2835*ebde8a60SMatthias Ringwald                 if (!hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)){
2836*ebde8a60SMatthias Ringwald                     log_info("IOCap insufficient for level %u -> abort", conn->requested_security_level);
2837*ebde8a60SMatthias Ringwald                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2838*ebde8a60SMatthias Ringwald                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2839*ebde8a60SMatthias Ringwald                     break;
2840*ebde8a60SMatthias Ringwald                 }
2841*ebde8a60SMatthias Ringwald             } else {
2842*ebde8a60SMatthias Ringwald                 // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
2843*ebde8a60SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
2844*ebde8a60SMatthias Ringwald                 if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
2845*ebde8a60SMatthias Ringwald                     log_info("Level 3+ required, but no input/output -> abort");
2846*ebde8a60SMatthias Ringwald                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2847*ebde8a60SMatthias Ringwald                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2848*ebde8a60SMatthias Ringwald                     break;
2849*ebde8a60SMatthias Ringwald                 }
2850*ebde8a60SMatthias Ringwald #endif
2851*ebde8a60SMatthias Ringwald             }
2852*ebde8a60SMatthias Ringwald 
285344565b0cSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
28548dbd6159SMatthias Ringwald             if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
28559671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
285611b03efaSMatthias Ringwald             } else {
28579671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
285811b03efaSMatthias Ringwald             }
285944565b0cSMatthias Ringwald #endif
2860dbe1a790S[email protected]             break;
2861dbe1a790S[email protected] 
28621849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
28631849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
28647ca4a7edSMatthias Ringwald             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
28657ca4a7edSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
28667ca4a7edSMatthias Ringwald             if (!conn) break;
28677ca4a7edSMatthias Ringwald 
28687ca4a7edSMatthias Ringwald             hci_connection_timestamp(conn);
28697ca4a7edSMatthias Ringwald 
28707ca4a7edSMatthias Ringwald             hci_pairing_started(conn, true);
28717ca4a7edSMatthias Ringwald 
28727ca4a7edSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
28731849becdSMatthias Ringwald             break;
28741849becdSMatthias Ringwald #endif
28751849becdSMatthias Ringwald 
2876dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
287717c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
2878367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2879367aedc0SMatthias Ringwald             if (!conn) break;
2880367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
2881367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
28828daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
2883367aedc0SMatthias Ringwald                 };
2884367aedc0SMatthias Ringwald             } else {
2885367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2886367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
2887367aedc0SMatthias Ringwald                 // don't forward event to app
2888367aedc0SMatthias Ringwald                 hci_run();
2889367aedc0SMatthias Ringwald                 return;
2890367aedc0SMatthias Ringwald             }
2891dbe1a790S[email protected]             break;
2892dbe1a790S[email protected] 
2893dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
2894367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
2895367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
28968daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
2897367aedc0SMatthias Ringwald             };
28981d6b20aeS[email protected]             break;
28991849becdSMatthias Ringwald 
29003dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
29013dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
29023dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
29033dce6128SMatthias Ringwald             if (!conn) break;
29043dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
29053dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
29063dce6128SMatthias Ringwald             break;
290735454696SMatthias Ringwald #endif
29081d6b20aeS[email protected] 
2909f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
2910254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
2911f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
2912f0944df2S[email protected]             if (!conn) break;
29134ea43905SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == 0u) {
2914254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2915254b78eeSMatthias Ringwald                 if (encryption_enabled){
2916573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
2917573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
29188daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2919573897a0SMatthias Ringwald                     }
2920573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
2921573897a0SMatthias Ringwald                     else {
2922fcaf38b9SMatthias Ringwald 
2923fcaf38b9SMatthias Ringwald                         // dedicated bonding: send result and disconnect
2924fcaf38b9SMatthias Ringwald                         if (conn->bonding_flags & BONDING_DEDICATED){
2925fcaf38b9SMatthias Ringwald                             conn->bonding_flags &= ~BONDING_DEDICATED;
2926fcaf38b9SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2927fcaf38b9SMatthias Ringwald                             conn->bonding_status = packet[2];
2928fcaf38b9SMatthias Ringwald                             break;
2929fcaf38b9SMatthias Ringwald                         }
2930fcaf38b9SMatthias Ringwald 
2931254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2932254b78eeSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2933254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2934edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
2935254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
29369ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2937254b78eeSMatthias Ringwald                             break;
2938254b78eeSMatthias Ringwald                         }
2939254b78eeSMatthias Ringwald 
2940aa2fe986SMatthias Ringwald                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
2941aa2fe986SMatthias Ringwald                         if (connected_uses_aes_ccm){
2942aa2fe986SMatthias Ringwald                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
2943aa2fe986SMatthias Ringwald                         }
2944aa2fe986SMatthias Ringwald 
2945aa2fe986SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2946aa2fe986SMatthias Ringwald                         // work around for issue with PTS dongle
2947aa2fe986SMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
2948aa2fe986SMatthias Ringwald #endif
2949aa2fe986SMatthias Ringwald 
29506e058d3fSMatthias Ringwald                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
29516e058d3fSMatthias Ringwald                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
2952573897a0SMatthias Ringwald                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
29536e058d3fSMatthias Ringwald                         } else {
29546e058d3fSMatthias Ringwald                             // if not, pretend everything is perfect
29559866fdc7SMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, 16);
29566e058d3fSMatthias Ringwald                         }
2957573897a0SMatthias Ringwald                     }
2958573897a0SMatthias Ringwald #endif
2959f0944df2S[email protected]                 } else {
29608daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
2961f0944df2S[email protected]                 }
2962ad83dc6aS[email protected]             }
2963573897a0SMatthias Ringwald 
2964f0944df2S[email protected]             break;
2965f0944df2S[email protected] 
296635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
29671eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2968abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
29691eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
29701eb2563eS[email protected]             if (!conn) break;
2971ad83dc6aS[email protected] 
2972dbd5dcc3SMatthias Ringwald             // clear authentication active flag
2973dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
29741714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
2975dbd5dcc3SMatthias Ringwald 
2976abdad579SMatthias Ringwald             // authenticated only if auth status == 0
2977abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
2978abdad579SMatthias Ringwald                 // authenticated
29798daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
2980abdad579SMatthias Ringwald 
2981131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
29828daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
29831eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2984ad83dc6aS[email protected]                     break;
2985ad83dc6aS[email protected]                 }
2986abdad579SMatthias Ringwald             }
2987abdad579SMatthias Ringwald 
2988abdad579SMatthias Ringwald             // emit updated security level
29891eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
29901eb2563eS[email protected]             break;
29911714cbbdSMatthias Ringwald 
29921714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
29931714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
29941714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
29951714cbbdSMatthias Ringwald             if (!conn) break;
29961714cbbdSMatthias Ringwald 
2997aa2fe986SMatthias Ringwald             // treat successfully paired connection as authenticated
2998aa2fe986SMatthias Ringwald             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
2999f3aafff1SMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3000aa2fe986SMatthias Ringwald             }
3001aa2fe986SMatthias Ringwald 
30021714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
30031714cbbdSMatthias Ringwald             break;
300435454696SMatthias Ringwald #endif
300534d2123cS[email protected] 
300686805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
3007ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
3008ccda6e14S[email protected]         // see end of function, too.
3009a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
3010a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
3011f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
301281d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
30134ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
3014c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
30154ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
301681d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3017c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
3018c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
301981d2bdb2SMatthias Ringwald                     if (release_buffer){
302081d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
302181d2bdb2SMatthias Ringwald                     }
3022c6a37cfdSMatthias Ringwald                 }
3023c6a37cfdSMatthias Ringwald             }
302435454696SMatthias Ringwald 
3025c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
3026c6a37cfdSMatthias Ringwald             if (!conn) break;
30271714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
30281714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
30291714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
30301714cbbdSMatthias Ringwald #endif
3031046ec007SMatthias Ringwald             // mark connection for shutdown
3032a70e17d4SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3033046ec007SMatthias Ringwald 
3034046ec007SMatthias Ringwald             // emit dedicatd bonding event
3035046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3036046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3037046ec007SMatthias Ringwald             }
3038046ec007SMatthias Ringwald 
303935454696SMatthias Ringwald #ifdef ENABLE_BLE
3040d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3041046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
30422b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
3043bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
30449a2e4658SMatthias Ringwald             }
304535454696SMatthias Ringwald #endif
3046d70217a2SMatthias Ringwald #endif
3047ccda6e14S[email protected]             break;
30486772a24cSmatthias.ringwald 
3049c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
3050313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
3051d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
3052c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
30537586ee35S[email protected]             } else {
30547586ee35S[email protected]                 // if no special requests, just reboot stack
30557586ee35S[email protected]                 hci_power_control_off();
30567586ee35S[email protected]                 hci_power_control_on();
3057c68bdf90Smatthias.ringwald             }
3058c68bdf90Smatthias.ringwald             break;
3059c68bdf90Smatthias.ringwald 
30600e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
30615cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
30625cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
3063c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
3064f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
3065c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3066c4c88f1bSJakob Krantz             if (!conn) break;
30675cf766e8SMatthias Ringwald             conn->role = packet[9];
30685cf766e8SMatthias Ringwald             break;
30690e6f3837SMatthias Ringwald #endif
30705cf766e8SMatthias Ringwald 
307163fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3072d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
30734fa24b5fS[email protected]             if (hci_transport_synchronous()) {
307463fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
30754fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
30764fa24b5fS[email protected]             }
307781d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
3078d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
3079d051460cS[email protected]             hci_release_packet_buffer();
3080701e3307SMatthias Ringwald 
308163fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
308263fa3374SMatthias Ringwald 
308335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
308463fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
3085701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
308635454696SMatthias Ringwald #endif
30876b4af23dS[email protected]             break;
30886b4af23dS[email protected] 
308935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
309063fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
309163fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
3092f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 1;
309363fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
309463fa3374SMatthias Ringwald             return;
30951cfb383eSMatthias Ringwald 
30961cfb383eSMatthias Ringwald         // explode inquriy results for easier consumption
30971cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
30981cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
30991cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
31009784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
31011cfb383eSMatthias Ringwald             break;
310235454696SMatthias Ringwald #endif
310363fa3374SMatthias Ringwald 
3104a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
31055909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
31065909f7f2Smatthias.ringwald             switch (packet[2]){
3107d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
310857c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
31094f4e0224SMatthias Ringwald                     // log_info("advertising report received");
31106fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
311157c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
31127bdc6798S[email protected]                     break;
3113d70217a2SMatthias Ringwald #endif
31145909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
31150ce3f217SMatthias Ringwald 					event_handle_le_connection_complete(packet);
31165909f7f2Smatthias.ringwald                     break;
31175909f7f2Smatthias.ringwald 
3118f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3119c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3120c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3121c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
3122c9db5c21SMilanka Ringwald                     if (!conn) break;
3123c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3124c9db5c21SMilanka Ringwald                     break;
312565a46ef3S[email protected] 
312673cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
312773cd8a2aSMatthias Ringwald                     // connection
312873cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
312973cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
313073cd8a2aSMatthias Ringwald                     if (conn) {
313173cd8a2aSMatthias Ringwald                         // read arguments
313273cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
313373cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
313473cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
313573cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
313673cd8a2aSMatthias Ringwald 
313773cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
313873cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
313973cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
314073cd8a2aSMatthias Ringwald                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
314173cd8a2aSMatthias Ringwald                         if (update_parameter){
314273cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
314373cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
314473cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
314573cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
314673cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
314773cd8a2aSMatthias Ringwald                         } else {
3148c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
314973cd8a2aSMatthias Ringwald                         }
315073cd8a2aSMatthias Ringwald                     }
315173cd8a2aSMatthias Ringwald                     break;
31520f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
31530f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
31540f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
31550f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
31560f3b27c5SMatthias Ringwald                     if (conn) {
31570f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
31580f3b27c5SMatthias Ringwald                     }
31590f3b27c5SMatthias Ringwald                     break;
31600f3b27c5SMatthias Ringwald #endif
31615909f7f2Smatthias.ringwald                 default:
31625909f7f2Smatthias.ringwald                     break;
31635909f7f2Smatthias.ringwald             }
31645909f7f2Smatthias.ringwald             break;
31655909f7f2Smatthias.ringwald #endif
31660b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
31670b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
31680b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
31690b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
31700b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
31710b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
31720b36101dSMatthias Ringwald                     break;
31730b36101dSMatthias Ringwald                 default:
31740b36101dSMatthias Ringwald                     break;
31750b36101dSMatthias Ringwald             }
31760b36101dSMatthias Ringwald             break;
31776772a24cSmatthias.ringwald         default:
31786772a24cSmatthias.ringwald             break;
3179fe1ed1b8Smatthias.ringwald     }
3180fe1ed1b8Smatthias.ringwald 
318167c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
318289db417bSmatthias.ringwald 
318386805605S[email protected]     // notify upper stack
3184d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
318594ab26f8Smatthias.ringwald 
318686805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3187797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3188f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
318905ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3190046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
3191797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
319205ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
3193b0136355SMatthias Ringwald 		}
319486805605S[email protected]     }
319586805605S[email protected] 
319694ab26f8Smatthias.ringwald 	// execute main loop
319794ab26f8Smatthias.ringwald 	hci_run();
319816833f0aSmatthias.ringwald }
319916833f0aSmatthias.ringwald 
320035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
32016f28d2eeSMatthias Ringwald 
32026be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
32036f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
32046f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn);
32056f28d2eeSMatthias Ringwald 
32066f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
320759c33575SMatthias Ringwald     log_debug("SCO TX Timeout");
32085a6b2dbdSMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
32096f28d2eeSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
32106f28d2eeSMatthias Ringwald     if (!conn) return;
32116f28d2eeSMatthias Ringwald 
3212afaddd67SMatthias Ringwald     // trigger send
3213afaddd67SMatthias Ringwald     conn->sco_tx_ready = 1;
3214e4157653SMatthias Ringwald     // extra packet if CVSD but SCO buffer is too short
3215a1df452eSMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3216e4157653SMatthias Ringwald         conn->sco_tx_ready++;
3217e4157653SMatthias Ringwald     }
3218afaddd67SMatthias Ringwald     hci_notify_if_sco_can_send_now();
32196f28d2eeSMatthias Ringwald }
32206f28d2eeSMatthias Ringwald 
322159c33575SMatthias Ringwald 
322259c33575SMatthias Ringwald #define SCO_TX_AFTER_RX_MS (6)
322359c33575SMatthias Ringwald 
32246f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn){
322559c33575SMatthias Ringwald 
32266f28d2eeSMatthias Ringwald     uint32_t now = btstack_run_loop_get_time_ms();
322759c33575SMatthias Ringwald     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
322859c33575SMatthias Ringwald     int time_delta_ms = sco_tx_ms - now;
322959c33575SMatthias Ringwald 
323059c33575SMatthias Ringwald     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
323159c33575SMatthias Ringwald 
323259c33575SMatthias Ringwald     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3233ddbec4ceSMatthias Ringwald     btstack_run_loop_remove_timer(timer);
323459c33575SMatthias Ringwald     btstack_run_loop_set_timer(timer, time_delta_ms);
323559c33575SMatthias Ringwald     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
323659c33575SMatthias Ringwald     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
323759c33575SMatthias Ringwald     btstack_run_loop_add_timer(timer);
32386f28d2eeSMatthias Ringwald }
32396be3cf7fSMatthias Ringwald #endif
32406f28d2eeSMatthias Ringwald 
3241c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
32420b3f95dfSMatthias Ringwald     // lookup connection struct
32432b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
32442b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
32450b3f95dfSMatthias Ringwald     if (!conn) return;
32460b3f95dfSMatthias Ringwald 
32476be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3248760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3249760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3250a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3251760b20efSMatthias Ringwald             packet[2] = 0x3c;
3252760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
3253760b20efSMatthias Ringwald             size = 63;
32540b3f95dfSMatthias Ringwald         }
32550b3f95dfSMatthias Ringwald     }
3256760b20efSMatthias Ringwald 
3257f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
3258f234b250SMatthias Ringwald         // Nothing to do
3259f234b250SMatthias Ringwald     } else {
326049205f5dSMatthias Ringwald         // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent);
3261760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
32626f28d2eeSMatthias Ringwald             uint32_t now = btstack_run_loop_get_time_ms();
326359c33575SMatthias Ringwald 
326459c33575SMatthias Ringwald             if (!conn->sco_rx_valid){
326559c33575SMatthias Ringwald                 // ignore first 10 packets
32666f28d2eeSMatthias Ringwald                 conn->sco_rx_count++;
326759c33575SMatthias Ringwald                 // log_debug("sco rx count %u", conn->sco_rx_count);
326859c33575SMatthias Ringwald                 if (conn->sco_rx_count == 10) {
326959c33575SMatthias Ringwald                     // use first timestamp as is and pretent it just started
32706f28d2eeSMatthias Ringwald                     conn->sco_rx_ms = now;
32716f28d2eeSMatthias Ringwald                     conn->sco_rx_valid = 1;
327259c33575SMatthias Ringwald                     conn->sco_rx_count = 0;
327359c33575SMatthias Ringwald                     sco_schedule_tx(conn);
327459c33575SMatthias Ringwald                 }
327559c33575SMatthias Ringwald             } else {
327659c33575SMatthias Ringwald                 // track expected arrival timme
327759c33575SMatthias Ringwald                 conn->sco_rx_count++;
327859c33575SMatthias Ringwald                 conn->sco_rx_ms += 7;
327959c33575SMatthias Ringwald                 int delta = (int32_t) (now - conn->sco_rx_ms);
328059c33575SMatthias Ringwald                 if (delta > 0){
328159c33575SMatthias Ringwald                     conn->sco_rx_ms++;
328259c33575SMatthias Ringwald                 }
328359c33575SMatthias Ringwald                 // log_debug("sco rx %u", conn->sco_rx_ms);
32846f28d2eeSMatthias Ringwald                 sco_schedule_tx(conn);
32856f28d2eeSMatthias Ringwald             }
3286760b20efSMatthias Ringwald         }
3287f234b250SMatthias Ringwald     }
32886be3cf7fSMatthias Ringwald #endif
32896be3cf7fSMatthias Ringwald 
32900b3f95dfSMatthias Ringwald     // deliver to app
32910b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
32920b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
32930b3f95dfSMatthias Ringwald     }
32940b3f95dfSMatthias Ringwald 
3295ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3296ed325439SMatthias Ringwald     // We can send one packet for each received packet
3297ed325439SMatthias Ringwald     conn->sco_tx_ready++;
3298ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
3299ed325439SMatthias Ringwald #endif
3300ed325439SMatthias Ringwald 
33010b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
33022b838201SMatthias Ringwald     conn->num_packets_completed++;
33032b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
33042b838201SMatthias Ringwald     hci_run();
33052b838201SMatthias Ringwald #endif
3306c91d150bS[email protected] }
330735454696SMatthias Ringwald #endif
3308c91d150bS[email protected] 
33090a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
33105bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
331110e830c9Smatthias.ringwald     switch (packet_type) {
331210e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
331310e830c9Smatthias.ringwald             event_handler(packet, size);
331410e830c9Smatthias.ringwald             break;
331510e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
331610e830c9Smatthias.ringwald             acl_handler(packet, size);
331710e830c9Smatthias.ringwald             break;
331835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3319c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
3320c91d150bS[email protected]             sco_handler(packet, size);
3321202c8a4cSMatthias Ringwald             break;
332235454696SMatthias Ringwald #endif
332310e830c9Smatthias.ringwald         default:
332410e830c9Smatthias.ringwald             break;
332510e830c9Smatthias.ringwald     }
332610e830c9Smatthias.ringwald }
332710e830c9Smatthias.ringwald 
3328d6b06661SMatthias Ringwald /**
3329d6b06661SMatthias Ringwald  * @brief Add event packet handler.
3330d6b06661SMatthias Ringwald  */
3331d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3332d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3333d6b06661SMatthias Ringwald }
3334d6b06661SMatthias Ringwald 
3335d6b06661SMatthias Ringwald 
3336fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
33373d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3338fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
333916833f0aSmatthias.ringwald }
334016833f0aSmatthias.ringwald 
334135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
33428abbe8b5SMatthias Ringwald /**
33438abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
33448abbe8b5SMatthias Ringwald  */
33453d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
33468abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
33478abbe8b5SMatthias Ringwald }
334835454696SMatthias Ringwald #endif
33498abbe8b5SMatthias Ringwald 
335071de195eSMatthias Ringwald static void hci_state_reset(void){
3351595bdbfbS[email protected]     // no connections yet
3352595bdbfbS[email protected]     hci_stack->connections = NULL;
335374308b23Smatthias.ringwald 
335474308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
335574308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
335674308b23Smatthias.ringwald     // hci_stack->connectable = 0;
335774308b23Smatthias.ringwald     // hci_stack->bondable = 1;
3358b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
3359595bdbfbS[email protected] 
336044935e40S[email protected]     // buffer is free
336144935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
336244935e40S[email protected] 
3363595bdbfbS[email protected]     // no pending cmds
3364595bdbfbS[email protected]     hci_stack->decline_reason = 0;
3365595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
3366595bdbfbS[email protected] 
3367c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
3368c214d65bSMatthias Ringwald 
3369bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
3370bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = 0xffff;
3371bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = 0xffff;
3372bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = 0xff;
3373496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3374bea424a5SMatthias Ringwald #endif
3375bea424a5SMatthias Ringwald 
3376cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3377cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
33781ae74bf3SMatthias Ringwald     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3379cf01e888SMatthias Ringwald #endif
3380cf01e888SMatthias Ringwald 
3381595bdbfbS[email protected]     // LE
3382b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
3383b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
3384b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
3385d70217a2SMatthias Ringwald #endif
3386d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3387a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
3388b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3389d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3390e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
3391d70217a2SMatthias Ringwald #endif
3392a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3393a61834b6SMatthias Ringwald     hci_stack->le_advertisements_active = false;
3394a61834b6SMatthias Ringwald     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3395a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3396a61834b6SMatthias Ringwald     }
3397a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
3398a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3399a61834b6SMatthias Ringwald     }
3400a61834b6SMatthias Ringwald #endif
3401595bdbfbS[email protected] }
3402595bdbfbS[email protected] 
340335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
34042d5e09d6SMatthias Ringwald /**
34052d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
34062d5e09d6SMatthias Ringwald  */
34072d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
34082d5e09d6SMatthias Ringwald     // store and open remote device db
34092d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
34102d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
34112d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
34122d5e09d6SMatthias Ringwald     }
34132d5e09d6SMatthias Ringwald }
341435454696SMatthias Ringwald #endif
34152d5e09d6SMatthias Ringwald 
34162d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
3417475c8125Smatthias.ringwald 
34183a9fb326S[email protected] #ifdef HAVE_MALLOC
34193a9fb326S[email protected]     if (!hci_stack) {
34203a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
34213a9fb326S[email protected]     }
34223a9fb326S[email protected] #else
34233a9fb326S[email protected]     hci_stack = &hci_stack_static;
34243a9fb326S[email protected] #endif
342566fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
34263a9fb326S[email protected] 
3427475c8125Smatthias.ringwald     // reference to use transport layer implementation
34283a9fb326S[email protected]     hci_stack->hci_transport = transport;
3429475c8125Smatthias.ringwald 
343011e23e5fSmatthias.ringwald     // reference to used config
34313a9fb326S[email protected]     hci_stack->config = config;
343211e23e5fSmatthias.ringwald 
343326a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
343426a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
343526a9b6daSMatthias Ringwald 
34368fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
34373a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
34388fcba05dSmatthias.ringwald 
343916833f0aSmatthias.ringwald     // register packet handlers with transport
344010e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
3441f5454fc6Smatthias.ringwald 
34423a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
3443e2386ba1S[email protected] 
3444e2386ba1S[email protected]     // class of device
34453a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
3446a45d6b9fS[email protected] 
3447f20168b8Smatthias.ringwald     // bondable by default
3448f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
3449f20168b8Smatthias.ringwald 
3450e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
345163168530SMatthias Ringwald     // classic name
345263168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
3453c4c88f1bSJakob Krantz 
3454c4c88f1bSJakob Krantz     // Master slave policy
3455c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
3456170fafaeSMatthias Ringwald 
3457b4eb4420SMatthias Ringwald     // Allow Role Switch
3458b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
3459b4eb4420SMatthias Ringwald 
346078315a58SMatthias Ringwald     // Default / minimum security level = 2
346178315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
346278315a58SMatthias Ringwald 
34635dbec6b3SMatthias Ringwald     // Default Security Mode 4
34645dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
34655dbec6b3SMatthias Ringwald 
3466cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3467cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
3468d821984bSMatthias Ringwald 
3469d821984bSMatthias Ringwald     // Link Supervision Timeout
3470d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3471d821984bSMatthias Ringwald 
3472e9f343c8SMatthias Ringwald #endif
347363168530SMatthias Ringwald 
347463048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
34753a9fb326S[email protected]     hci_stack->ssp_enable = 1;
34763a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
34773a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
34783a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
347969a97523S[email protected] 
34805d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
34815d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
34825d23aae8SMatthias Ringwald 
3483fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
3484fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
3485d950d659SMatthias Ringwald 
3486831711daSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3487831711daSMatthias Ringwald     // connection parameter to use for outgoing connections
3488cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3489cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3490831711daSMatthias Ringwald     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3491831711daSMatthias Ringwald     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3492831711daSMatthias Ringwald     hci_stack->le_connection_latency      = 4;         // 4
3493831711daSMatthias Ringwald     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3494831711daSMatthias Ringwald     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3495831711daSMatthias Ringwald     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
34967261e5d8SMatthias Ringwald 
34977261e5d8SMatthias Ringwald     // default LE Scanning
34988b69e4c7SMatthias Ringwald     hci_stack->le_scan_type     =   0x1; // active
34998b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
35008b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
3501831711daSMatthias Ringwald #endif
3502831711daSMatthias Ringwald 
35032b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
35042b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
35052b6ab3e6SMatthias Ringwald #endif
35062b6ab3e6SMatthias Ringwald 
3507831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
3508831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3509831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3510831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3511831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3512831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3513831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3514831711daSMatthias Ringwald 
3515595bdbfbS[email protected]     hci_state_reset();
3516475c8125Smatthias.ringwald }
3517475c8125Smatthias.ringwald 
35184688f216SMatthias Ringwald void hci_deinit(void){
35194688f216SMatthias Ringwald #ifdef HAVE_MALLOC
35204688f216SMatthias Ringwald     if (hci_stack) {
35214688f216SMatthias Ringwald         free(hci_stack);
35224688f216SMatthias Ringwald     }
35234688f216SMatthias Ringwald #endif
35244688f216SMatthias Ringwald     hci_stack = NULL;
3525b5bbcbf4SMatthias Ringwald 
3526b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
35274688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
3528b5bbcbf4SMatthias Ringwald #endif
35294688f216SMatthias Ringwald }
35304688f216SMatthias Ringwald 
35313fb36a29SMatthias Ringwald /**
35323fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
35333fb36a29SMatthias Ringwald  */
35343fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
35353fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
35363fb36a29SMatthias Ringwald 
35373fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
35383fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
35393fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
35403fb36a29SMatthias Ringwald     }
35413fb36a29SMatthias Ringwald }
35423fb36a29SMatthias Ringwald 
3543fb55bd0aSMatthias Ringwald /**
3544d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3545fb55bd0aSMatthias Ringwald  */
3546fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
3547fb55bd0aSMatthias Ringwald     // references to used control implementation
3548fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
3549d0b87befSMatthias Ringwald     // init with transport config
3550d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
3551fb55bd0aSMatthias Ringwald }
3552fb55bd0aSMatthias Ringwald 
355371de195eSMatthias Ringwald void hci_close(void){
3554e6d6524dSMatthias Ringwald 
3555e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
3556404843c1Smatthias.ringwald     // close remote device db
3557a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
3558a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
3559404843c1Smatthias.ringwald     }
3560e6d6524dSMatthias Ringwald #endif
35617224be7eSMatthias Ringwald 
35627224be7eSMatthias Ringwald     btstack_linked_list_iterator_t lit;
35637224be7eSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
35647224be7eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
35657224be7eSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
35667224be7eSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
35677224be7eSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
35687224be7eSMatthias Ringwald         hci_shutdown_connection(connection);
3569f5454fc6Smatthias.ringwald     }
35707224be7eSMatthias Ringwald 
3571f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
35723a9fb326S[email protected] 
35733a9fb326S[email protected] #ifdef HAVE_MALLOC
35743a9fb326S[email protected]     free(hci_stack);
35753a9fb326S[email protected] #endif
35763a9fb326S[email protected]     hci_stack = NULL;
3577404843c1Smatthias.ringwald }
3578404843c1Smatthias.ringwald 
3579cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3580cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3581cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
3582cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
3583cb70c5abSMatthias Ringwald }
3584cb70c5abSMatthias Ringwald #endif
3585cb70c5abSMatthias Ringwald 
358635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3587170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3588170fafaeSMatthias Ringwald     // validate ranage and set
3589170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
3590170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
3591170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3592170fafaeSMatthias Ringwald }
359378315a58SMatthias Ringwald 
3594137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3595137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
35965dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
3597137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
3598137715ebSMatthias Ringwald     } else {
3599137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3600137715ebSMatthias Ringwald     }
36015dbec6b3SMatthias Ringwald }
36025dbec6b3SMatthias Ringwald 
36035dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
36045dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
36055dbec6b3SMatthias Ringwald }
36065dbec6b3SMatthias Ringwald 
360778315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
360878315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
360978315a58SMatthias Ringwald }
361078315a58SMatthias Ringwald 
361178315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
3612d7387af3SMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
3613d7387af3SMatthias Ringwald         return LEVEL_4;
3614d7387af3SMatthias Ringwald     }
361578315a58SMatthias Ringwald     return hci_stack->gap_security_level;
361678315a58SMatthias Ringwald }
361730cdf3c6SMatthias Ringwald 
36188ad4dfffSMatthias Ringwald void gap_set_minimal_service_security_level(gap_security_level_t security_level){
36198ad4dfffSMatthias Ringwald     hci_stack->gap_minimal_service_security_level = security_level;
36208ad4dfffSMatthias Ringwald }
36218ad4dfffSMatthias Ringwald 
362230cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
362330cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
362430cdf3c6SMatthias Ringwald }
362530cdf3c6SMatthias Ringwald 
362630cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
362730cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
362830cdf3c6SMatthias Ringwald }
3629170fafaeSMatthias Ringwald #endif
3630170fafaeSMatthias Ringwald 
3631170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
363260b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
36339e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
36349e61646fS[email protected] }
363576f27cffSMatthias Ringwald 
3636c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3637c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
3638c33e56d3SMatthias Ringwald }
3639c33e56d3SMatthias Ringwald 
3640b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
3641b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3642b4eb4420SMatthias Ringwald }
3643b4eb4420SMatthias Ringwald 
3644b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
3645b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
3646b4eb4420SMatthias Ringwald }
3647b4eb4420SMatthias Ringwald 
36480c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
36490c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
36500c3eb48dSMatthias Ringwald }
36510c3eb48dSMatthias Ringwald 
365276f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
365376f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
365476f27cffSMatthias Ringwald }
365535454696SMatthias Ringwald #endif
36569e61646fS[email protected] 
365776f27cffSMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3658f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3659f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
36606535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3661f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
3662f456b2d0S[email protected] }
366376f27cffSMatthias Ringwald #endif
3664f456b2d0S[email protected] 
36658d213e1aSmatthias.ringwald // State-Module-Driver overview
36668d213e1aSmatthias.ringwald // state                    module  low-level
36678d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
36688d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
36698d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
36708d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
3671d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
3672d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
3673c7e0c5f6Smatthias.ringwald 
367440d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
36757301ad89Smatthias.ringwald 
3676038bc64cSmatthias.ringwald     // power on
3677f9a30166Smatthias.ringwald     int err = 0;
36783a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
3679d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
3680f9a30166Smatthias.ringwald     }
3681038bc64cSmatthias.ringwald     if (err){
36829da54300S[email protected]         log_error( "POWER_ON failed");
3683038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3684038bc64cSmatthias.ringwald         return err;
3685038bc64cSmatthias.ringwald     }
3686038bc64cSmatthias.ringwald 
368724b3c629SMatthias Ringwald     // int chipset driver
36883fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
36893fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
36903fb36a29SMatthias Ringwald     }
36913fb36a29SMatthias Ringwald 
369224b3c629SMatthias Ringwald     // init transport
369324b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
369424b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
369524b3c629SMatthias Ringwald     }
369624b3c629SMatthias Ringwald 
369724b3c629SMatthias Ringwald     // open transport
369824b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
3699038bc64cSmatthias.ringwald     if (err){
37009da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
37013a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3702d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3703f9a30166Smatthias.ringwald         }
3704038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3705038bc64cSmatthias.ringwald         return err;
3706038bc64cSmatthias.ringwald     }
37078d213e1aSmatthias.ringwald     return 0;
37088d213e1aSmatthias.ringwald }
3709038bc64cSmatthias.ringwald 
371040d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
37118d213e1aSmatthias.ringwald 
37129da54300S[email protected]     log_info("hci_power_control_off");
37139418f9c9Smatthias.ringwald 
37148d213e1aSmatthias.ringwald     // close low-level device
371524b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
37168d213e1aSmatthias.ringwald 
37179da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
37189418f9c9Smatthias.ringwald 
37198d213e1aSmatthias.ringwald     // power off
37203a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
3721d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
37228d213e1aSmatthias.ringwald     }
37239418f9c9Smatthias.ringwald 
37249da54300S[email protected]     log_info("hci_power_control_off - control closed");
37259418f9c9Smatthias.ringwald 
37263a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
372772ea5239Smatthias.ringwald }
372872ea5239Smatthias.ringwald 
372940d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
373072ea5239Smatthias.ringwald 
37319da54300S[email protected]     log_info("hci_power_control_sleep");
37323144bce4Smatthias.ringwald 
3733b429b9b7Smatthias.ringwald #if 0
3734b429b9b7Smatthias.ringwald     // don't close serial port during sleep
3735b429b9b7Smatthias.ringwald 
373672ea5239Smatthias.ringwald     // close low-level device
37373a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
3738b429b9b7Smatthias.ringwald #endif
373972ea5239Smatthias.ringwald 
374072ea5239Smatthias.ringwald     // sleep mode
37413a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
3742d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
374372ea5239Smatthias.ringwald     }
3744b429b9b7Smatthias.ringwald 
37453a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
37468d213e1aSmatthias.ringwald }
37478d213e1aSmatthias.ringwald 
374840d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
3749b429b9b7Smatthias.ringwald 
37509da54300S[email protected]     log_info("hci_power_control_wake");
3751b429b9b7Smatthias.ringwald 
3752b429b9b7Smatthias.ringwald     // wake on
37533a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
3754d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
3755b429b9b7Smatthias.ringwald     }
3756b429b9b7Smatthias.ringwald 
3757b429b9b7Smatthias.ringwald #if 0
3758b429b9b7Smatthias.ringwald     // open low-level device
37593a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
3760b429b9b7Smatthias.ringwald     if (err){
37619da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
37623a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3763d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3764b429b9b7Smatthias.ringwald         }
3765b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
3766b429b9b7Smatthias.ringwald         return err;
3767b429b9b7Smatthias.ringwald     }
3768b429b9b7Smatthias.ringwald #endif
3769b429b9b7Smatthias.ringwald 
3770b429b9b7Smatthias.ringwald     return 0;
3771b429b9b7Smatthias.ringwald }
3772b429b9b7Smatthias.ringwald 
377344935e40S[email protected] static void hci_power_transition_to_initializing(void){
377444935e40S[email protected]     // set up state machine
377544935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
377644935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
377744935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
37785c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
377944935e40S[email protected] }
3780b429b9b7Smatthias.ringwald 
378142bd3d77SMatthias Ringwald // returns error
378242bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
378342bd3d77SMatthias Ringwald     int err;
37848d213e1aSmatthias.ringwald     switch (power_mode){
37858d213e1aSmatthias.ringwald         case HCI_POWER_ON:
37868d213e1aSmatthias.ringwald             err = hci_power_control_on();
378742bd3d77SMatthias Ringwald             if (err != 0) {
3788f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
378997b61c7bS[email protected]                 return err;
379097b61c7bS[email protected]             }
379144935e40S[email protected]             hci_power_transition_to_initializing();
37928d213e1aSmatthias.ringwald             break;
37938d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
37948d213e1aSmatthias.ringwald             // do nothing
37958d213e1aSmatthias.ringwald             break;
37968d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3797b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
37988d213e1aSmatthias.ringwald             break;
37997bbeb3adSMilanka Ringwald         default:
38007bbeb3adSMilanka Ringwald             btstack_assert(false);
38017bbeb3adSMilanka Ringwald             break;
38028d213e1aSmatthias.ringwald     }
380342bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
380442bd3d77SMatthias Ringwald }
38057301ad89Smatthias.ringwald 
380642bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
38078d213e1aSmatthias.ringwald     switch (power_mode){
38088d213e1aSmatthias.ringwald         case HCI_POWER_ON:
38098d213e1aSmatthias.ringwald             // do nothing
38108d213e1aSmatthias.ringwald             break;
38118d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
38128d213e1aSmatthias.ringwald             // no connections yet, just turn it off
38138d213e1aSmatthias.ringwald             hci_power_control_off();
38148d213e1aSmatthias.ringwald             break;
38158d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3816b546ac54Smatthias.ringwald             // no connections yet, just turn it off
381772ea5239Smatthias.ringwald             hci_power_control_sleep();
38188d213e1aSmatthias.ringwald             break;
38197bbeb3adSMilanka Ringwald         default:
38207bbeb3adSMilanka Ringwald             btstack_assert(false);
38217bbeb3adSMilanka Ringwald             break;
38228d213e1aSmatthias.ringwald     }
382342bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
382442bd3d77SMatthias Ringwald }
38257301ad89Smatthias.ringwald 
382642bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
38278d213e1aSmatthias.ringwald     switch (power_mode){
38288d213e1aSmatthias.ringwald         case HCI_POWER_ON:
38298d213e1aSmatthias.ringwald             // do nothing
38308d213e1aSmatthias.ringwald             break;
38318d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
3832c7e0c5f6Smatthias.ringwald             // see hci_run
38333a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3834beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
38358d213e1aSmatthias.ringwald             break;
38368d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3837b546ac54Smatthias.ringwald             // see hci_run
38383a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
383974b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
38408d213e1aSmatthias.ringwald             break;
38417bbeb3adSMilanka Ringwald         default:
38427bbeb3adSMilanka Ringwald             btstack_assert(false);
38437bbeb3adSMilanka Ringwald             break;
38448d213e1aSmatthias.ringwald     }
384542bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
384642bd3d77SMatthias Ringwald }
38477301ad89Smatthias.ringwald 
384842bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
38498d213e1aSmatthias.ringwald     switch (power_mode){
38508d213e1aSmatthias.ringwald         case HCI_POWER_ON:
385144935e40S[email protected]             hci_power_transition_to_initializing();
38528d213e1aSmatthias.ringwald             break;
38538d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
38548d213e1aSmatthias.ringwald             // do nothing
38558d213e1aSmatthias.ringwald             break;
38568d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3857b546ac54Smatthias.ringwald             // see hci_run
38583a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
385974b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
38608d213e1aSmatthias.ringwald             break;
38617bbeb3adSMilanka Ringwald         default:
38627bbeb3adSMilanka Ringwald             btstack_assert(false);
38637bbeb3adSMilanka Ringwald             break;
38648d213e1aSmatthias.ringwald     }
386500278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
386642bd3d77SMatthias Ringwald }
38678d213e1aSmatthias.ringwald 
386842bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
38698d213e1aSmatthias.ringwald     switch (power_mode){
38708d213e1aSmatthias.ringwald         case HCI_POWER_ON:
387128171530Smatthias.ringwald 
3872423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
387328171530Smatthias.ringwald             // nothing to do, if H4 supports power management
3874d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
38753a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
387674b323a9SMatthias Ringwald                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
387728171530Smatthias.ringwald                         break;
387828171530Smatthias.ringwald                     }
387928171530Smatthias.ringwald #endif
388044935e40S[email protected]             hci_power_transition_to_initializing();
38818d213e1aSmatthias.ringwald             break;
38828d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
3883b546ac54Smatthias.ringwald             // see hci_run
38843a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3885beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
38868d213e1aSmatthias.ringwald             break;
38878d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3888b546ac54Smatthias.ringwald             // do nothing
38898d213e1aSmatthias.ringwald             break;
38907bbeb3adSMilanka Ringwald         default:
38917bbeb3adSMilanka Ringwald             btstack_assert(false);
38927bbeb3adSMilanka Ringwald             break;
38938d213e1aSmatthias.ringwald     }
389442bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
389542bd3d77SMatthias Ringwald }
38968d213e1aSmatthias.ringwald 
389742bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
389842bd3d77SMatthias Ringwald     int err;
38998d213e1aSmatthias.ringwald     switch (power_mode){
39008d213e1aSmatthias.ringwald         case HCI_POWER_ON:
3901423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
390228171530Smatthias.ringwald             // nothing to do, if H4 supports power management
3903d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
39043a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
39055c363727SMatthias Ringwald                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3906758b46ceSmatthias.ringwald                         hci_update_scan_enable();
390728171530Smatthias.ringwald                         break;
390828171530Smatthias.ringwald                     }
390928171530Smatthias.ringwald #endif
39103144bce4Smatthias.ringwald             err = hci_power_control_wake();
39113144bce4Smatthias.ringwald             if (err) return err;
391244935e40S[email protected]             hci_power_transition_to_initializing();
39138d213e1aSmatthias.ringwald             break;
39148d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
39153a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3916beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
39178d213e1aSmatthias.ringwald             break;
39188d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3919b546ac54Smatthias.ringwald             // do nothing
39208d213e1aSmatthias.ringwald             break;
39217bbeb3adSMilanka Ringwald         default:
39227bbeb3adSMilanka Ringwald             btstack_assert(false);
39237bbeb3adSMilanka Ringwald             break;
39248d213e1aSmatthias.ringwald     }
392542bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
392642bd3d77SMatthias Ringwald }
39277bbeb3adSMilanka Ringwald 
392842bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
392942bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
393024f87726SMatthias Ringwald     int err = 0;
393142bd3d77SMatthias Ringwald     switch (hci_stack->state){
393242bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
393342bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
393442bd3d77SMatthias Ringwald             break;
393542bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
393642bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
393742bd3d77SMatthias Ringwald             break;
393842bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
393942bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
394042bd3d77SMatthias Ringwald             break;
394142bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
394242bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
394342bd3d77SMatthias Ringwald             break;
394442bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
394542bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
394642bd3d77SMatthias Ringwald             break;
394742bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
394842bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
394942bd3d77SMatthias Ringwald             break;
39507bbeb3adSMilanka Ringwald         default:
39517bbeb3adSMilanka Ringwald             btstack_assert(false);
39527bbeb3adSMilanka Ringwald             break;
395311e23e5fSmatthias.ringwald     }
395424f87726SMatthias Ringwald     if (err != 0){
395542bd3d77SMatthias Ringwald         return err;
395642bd3d77SMatthias Ringwald     }
395768d92d03Smatthias.ringwald 
3958038bc64cSmatthias.ringwald     // create internal event
3959ee8bf225Smatthias.ringwald 	hci_emit_state();
3960ee8bf225Smatthias.ringwald 
396168d92d03Smatthias.ringwald 	// trigger next/first action
396268d92d03Smatthias.ringwald 	hci_run();
396368d92d03Smatthias.ringwald 
3964475c8125Smatthias.ringwald     return 0;
3965475c8125Smatthias.ringwald }
3966475c8125Smatthias.ringwald 
396735454696SMatthias Ringwald 
396835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
396935454696SMatthias Ringwald 
3970758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
3971758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
3972a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3973758b46ceSmatthias.ringwald     hci_run();
3974758b46ceSmatthias.ringwald }
3975758b46ceSmatthias.ringwald 
397615a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
3977381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
3978381fbed8Smatthias.ringwald 
39793a9fb326S[email protected]     if (hci_stack->discoverable == enable){
39803a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
3981381fbed8Smatthias.ringwald         return;
3982381fbed8Smatthias.ringwald     }
3983381fbed8Smatthias.ringwald 
39843a9fb326S[email protected]     hci_stack->discoverable = enable;
3985758b46ceSmatthias.ringwald     hci_update_scan_enable();
3986758b46ceSmatthias.ringwald }
3987b031bebbSmatthias.ringwald 
398815a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
3989758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
3990758b46ceSmatthias.ringwald 
3991758b46ceSmatthias.ringwald     // don't emit event
39923a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
3993758b46ceSmatthias.ringwald 
39943a9fb326S[email protected]     hci_stack->connectable = enable;
3995758b46ceSmatthias.ringwald     hci_update_scan_enable();
3996381fbed8Smatthias.ringwald }
399735454696SMatthias Ringwald #endif
3998381fbed8Smatthias.ringwald 
399915a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
40006535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
40015061f3afS[email protected] }
40025061f3afS[email protected] 
40032b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
40042b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
40052b838201SMatthias Ringwald 
40062b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
40072b838201SMatthias Ringwald     hci_reserve_packet_buffer();
40082b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
40092b838201SMatthias Ringwald 
40102b838201SMatthias Ringwald     uint16_t size = 0;
40112b838201SMatthias Ringwald     uint16_t num_handles = 0;
40122b838201SMatthias Ringwald     packet[size++] = 0x35;
40132b838201SMatthias Ringwald     packet[size++] = 0x0c;
40142b838201SMatthias Ringwald     size++;  // skip param len
40152b838201SMatthias Ringwald     size++;  // skip num handles
40162b838201SMatthias Ringwald 
40172b838201SMatthias Ringwald     // add { handle, packets } entries
40182b838201SMatthias Ringwald     btstack_linked_item_t * it;
40192b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
40202b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
40212b838201SMatthias Ringwald         if (connection->num_packets_completed){
40222b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
40232b838201SMatthias Ringwald             size += 2;
40242b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
40252b838201SMatthias Ringwald             size += 2;
40262b838201SMatthias Ringwald             //
40272b838201SMatthias Ringwald             num_handles++;
40282b838201SMatthias Ringwald             connection->num_packets_completed = 0;
40292b838201SMatthias Ringwald         }
40302b838201SMatthias Ringwald     }
40312b838201SMatthias Ringwald 
40322b838201SMatthias Ringwald     packet[2] = size - 3;
40332b838201SMatthias Ringwald     packet[3] = num_handles;
40342b838201SMatthias Ringwald 
40352b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
40362b838201SMatthias Ringwald 
40372b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
40382b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
40392b838201SMatthias Ringwald 
40402b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
40412b838201SMatthias Ringwald     if (hci_transport_synchronous()){
4042e2d22487SMatthias Ringwald         hci_release_packet_buffer();
4043068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
40442b838201SMatthias Ringwald     }
40452b838201SMatthias Ringwald }
40462b838201SMatthias Ringwald #endif
40472b838201SMatthias Ringwald 
404826fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
404926fe9592SMatthias Ringwald     UNUSED(ds);
405026fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
4051beceeddeSMatthias Ringwald     // allow packet handlers to defer final shutdown
4052beceeddeSMatthias Ringwald     hci_emit_state();
405326fe9592SMatthias Ringwald     hci_run();
405426fe9592SMatthias Ringwald }
405526fe9592SMatthias Ringwald 
4056f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
40574ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
4058b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4059b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4060b5d8b22bS[email protected]         if (connection) {
406128a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4062b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
4063f30077b7SMatthias Ringwald                 return true;
4064b5d8b22bS[email protected]             }
406528a0332dSMatthias Ringwald         } else {
4066b5d8b22bS[email protected]             // connection gone -> discard further fragments
406728a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4068b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
4069b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
4070b5d8b22bS[email protected]         }
4071b5d8b22bS[email protected]     }
4072f30077b7SMatthias Ringwald     return false;
40732b838201SMatthias Ringwald }
4074b031bebbSmatthias.ringwald 
407535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4076f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
4077f30077b7SMatthias Ringwald 
4078b031bebbSmatthias.ringwald     // decline incoming connections
40793a9fb326S[email protected]     if (hci_stack->decline_reason){
40803a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
40813a9fb326S[email protected]         hci_stack->decline_reason = 0;
40823a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4083f30077b7SMatthias Ringwald         return true;
4084ce4c8fabSmatthias.ringwald     }
4085bea424a5SMatthias Ringwald     // write page scan activity
4086bea424a5SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_interval != 0xffff) && hci_classic_supported()){
4087bea424a5SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
4088bea424a5SMatthias Ringwald         hci_stack->new_page_scan_interval = 0xffff;
4089bea424a5SMatthias Ringwald         hci_stack->new_page_scan_window = 0xffff;
4090bea424a5SMatthias Ringwald         return true;
4091bea424a5SMatthias Ringwald     }
4092bea424a5SMatthias Ringwald     // write page scan type
4093bea424a5SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_type != 0xff) && hci_classic_supported()){
4094bea424a5SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
4095bea424a5SMatthias Ringwald         hci_stack->new_page_scan_type = 0xff;
4096bea424a5SMatthias Ringwald         return true;
4097bea424a5SMatthias Ringwald     }
4098b031bebbSmatthias.ringwald     // send scan enable
40990e588213SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
41003a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
41013a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
4102f30077b7SMatthias Ringwald         return true;
4103b031bebbSmatthias.ringwald     }
4104f5875de5SMatthias Ringwald     // start/stop inquiry
4105a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4106f5875de5SMatthias Ringwald         uint8_t duration = hci_stack->inquiry_state;
4107beb3c81dSMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4108496bb884SMatthias Ringwald         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4109f30077b7SMatthias Ringwald         return true;
4110f5875de5SMatthias Ringwald     }
4111f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4112f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4113f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
4114f30077b7SMatthias Ringwald         return true;
4115f5875de5SMatthias Ringwald     }
4116b7f1ee76SMatthias Ringwald     // remote name request
4117b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4118b7f1ee76SMatthias Ringwald         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4119b7f1ee76SMatthias Ringwald         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4120ee8a36c8SMatthias Ringwald                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4121f30077b7SMatthias Ringwald         return true;
4122b7f1ee76SMatthias Ringwald     }
4123cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
4124cf01e888SMatthias Ringwald     // Local OOB data
4125cf01e888SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){
4126cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
4127cf01e888SMatthias Ringwald         if (hci_stack->local_supported_commands[1] & 0x10u){
4128cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
4129cf01e888SMatthias Ringwald         } else {
4130cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
4131cf01e888SMatthias Ringwald         }
4132cf01e888SMatthias Ringwald     }
4133cf01e888SMatthias Ringwald #endif
41340a51f88bSMatthias Ringwald     // pairing
41350a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
41360a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
41373f659ee4SMilanka Ringwald         uint8_t pin_code[16];
41380a51f88bSMatthias Ringwald         switch (state){
41390a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
4140cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
41413f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
41423f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
41433f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
41440a51f88bSMatthias Ringwald                 break;
41450a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4146cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
41470a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
41480a51f88bSMatthias Ringwald                 break;
41490a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
4150cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4151d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
41520a51f88bSMatthias Ringwald                 break;
41530a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4154cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
41550a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
41560a51f88bSMatthias Ringwald                 break;
41570a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4158cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
41590a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
41600a51f88bSMatthias Ringwald                 break;
41610a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4162cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
41630a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
41640a51f88bSMatthias Ringwald                 break;
41650a51f88bSMatthias Ringwald             default:
41660a51f88bSMatthias Ringwald                 break;
41670a51f88bSMatthias Ringwald         }
4168f30077b7SMatthias Ringwald         return true;
4169f30077b7SMatthias Ringwald     }
4170f30077b7SMatthias Ringwald     return false;
41710a51f88bSMatthias Ringwald }
417235454696SMatthias Ringwald #endif
4173b031bebbSmatthias.ringwald 
4174a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4175f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
4176f30077b7SMatthias Ringwald 
4177f30077b7SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4178f30077b7SMatthias Ringwald 
4179f30077b7SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
41804ea43905SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4181d70217a2SMatthias Ringwald 
4182a41310b7SMatthias Ringwald 
4183a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
4184a41310b7SMatthias Ringwald 
4185a41310b7SMatthias Ringwald     bool scanning_stop = false;
4186a41310b7SMatthias Ringwald     bool connecting_stop = false;
4187a41310b7SMatthias Ringwald     bool advertising_stop = false;
4188a41310b7SMatthias Ringwald 
4189a41310b7SMatthias Ringwald #ifndef ENABLE_LE_CENTRAL
4190a41310b7SMatthias Ringwald     UNUSED(scanning_stop);
41910abd9f64SMatthias Ringwald     UNUSED(connecting_stop);
4192a41310b7SMatthias Ringwald #endif
4193a41310b7SMatthias Ringwald #ifndef ENABLE_LE_PERIPHERAL
4194a41310b7SMatthias Ringwald     UNUSED(advertising_stop);
4195a41310b7SMatthias Ringwald #endif
4196a41310b7SMatthias Ringwald 
419729c24bebSMatthias Ringwald     // check if whitelist needs modification
419829c24bebSMatthias Ringwald     bool whitelist_modification_pending = false;
419929c24bebSMatthias Ringwald     btstack_linked_list_iterator_t lit;
420029c24bebSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
420129c24bebSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
420229c24bebSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
420329c24bebSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
420429c24bebSMatthias Ringwald             whitelist_modification_pending = true;
420529c24bebSMatthias Ringwald             break;
420629c24bebSMatthias Ringwald         }
420729c24bebSMatthias Ringwald     }
420821debf25SMatthias Ringwald     // check if resolving list needs modification
420921debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
421021debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4211ea151974SMatthias Ringwald     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4212ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
421321debf25SMatthias Ringwald         resolving_list_modification_pending = true;
421421debf25SMatthias Ringwald     }
421521debf25SMatthias Ringwald #endif
421629c24bebSMatthias Ringwald 
4217d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4218fde725feSMatthias Ringwald     // scanning control
42193251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
422029c24bebSMatthias Ringwald         // stop if:
422129c24bebSMatthias Ringwald         // - parameter change required
422229c24bebSMatthias Ringwald         // - it's disabled
422329c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
422421debf25SMatthias Ringwald         // - resolving list modified
422529c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
422621debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
422721debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
422821debf25SMatthias Ringwald             scanning_uses_whitelist ||
422921debf25SMatthias Ringwald             resolving_list_modification_pending){
423021debf25SMatthias Ringwald 
42312d5c2a27SMatthias Ringwald             scanning_stop = true;
4232fde725feSMatthias Ringwald         }
4233fde725feSMatthias Ringwald     }
423429c24bebSMatthias Ringwald #endif
4235fde725feSMatthias Ringwald 
423629c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
423729c24bebSMatthias Ringwald     // connecting control
4238f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
4239f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
4240f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
4241f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
4242af64f147SMatthias Ringwald             // stop connecting if:
4243af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
4244af64f147SMatthias Ringwald             // - if it got disabled
424521debf25SMatthias Ringwald             // - resolving list modified
4246f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4247f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
424821debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
424921debf25SMatthias Ringwald                 resolving_list_modification_pending) {
425021debf25SMatthias Ringwald 
425129c24bebSMatthias Ringwald                 connecting_stop = true;
425229c24bebSMatthias Ringwald             }
4253f496d06eSMatthias Ringwald             break;
4254f496d06eSMatthias Ringwald         default:
4255f496d06eSMatthias Ringwald             break;
425629c24bebSMatthias Ringwald     }
4257d70217a2SMatthias Ringwald #endif
425829c24bebSMatthias Ringwald 
4259d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
426045c102fdSMatthias Ringwald     // le advertisement control
4261bbc366e6SMatthias Ringwald     if (hci_stack->le_advertisements_active){
426229c24bebSMatthias Ringwald         // stop if:
426329c24bebSMatthias Ringwald         // - parameter change required
426429c24bebSMatthias Ringwald         // - it's disabled
4265ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
426621debf25SMatthias Ringwald         // - resolving list modified
4267a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
42684e5d21eaSMatthias Ringwald         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4269a61834b6SMatthias Ringwald         if (advertising_change ||
4270a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
427121debf25SMatthias Ringwald             (advertising_uses_whitelist & whitelist_modification_pending) ||
427221debf25SMatthias Ringwald             resolving_list_modification_pending) {
427321debf25SMatthias Ringwald 
4274fde725feSMatthias Ringwald             advertising_stop = true;
4275fde725feSMatthias Ringwald         }
4276fde725feSMatthias Ringwald     }
4277a41310b7SMatthias Ringwald #endif
4278fde725feSMatthias Ringwald 
4279a41310b7SMatthias Ringwald 
4280a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
4281a41310b7SMatthias Ringwald 
4282a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4283a41310b7SMatthias Ringwald     if (scanning_stop){
42845226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
4285a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4286a41310b7SMatthias Ringwald         return true;
4287a41310b7SMatthias Ringwald     }
4288a41310b7SMatthias Ringwald #endif
4289a41310b7SMatthias Ringwald 
4290a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4291a41310b7SMatthias Ringwald     if (connecting_stop){
4292a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
4293a41310b7SMatthias Ringwald         return true;
4294a41310b7SMatthias Ringwald     }
4295a41310b7SMatthias Ringwald #endif
4296a41310b7SMatthias Ringwald 
4297a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4298fde725feSMatthias Ringwald     if (advertising_stop){
42995226d7f2SMatthias Ringwald         hci_stack->le_advertisements_active = false;
430045c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4301f30077b7SMatthias Ringwald         return true;
430245c102fdSMatthias Ringwald     }
4303a41310b7SMatthias Ringwald #endif
4304fde725feSMatthias Ringwald 
4305a41310b7SMatthias Ringwald     // Phase 3: modify
4306a41310b7SMatthias Ringwald 
4307a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4308a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
4309a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
4310a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4311a41310b7SMatthias Ringwald                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4312a41310b7SMatthias Ringwald         return true;
4313a41310b7SMatthias Ringwald     }
4314a41310b7SMatthias Ringwald #endif
4315a41310b7SMatthias Ringwald 
4316a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
431745c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
431845c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
43196bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
432045c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_parameters,
432145c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_min,
432245c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_max,
432345c102fdSMatthias Ringwald                      hci_stack->le_advertisements_type,
43246bcfa632SMatthias Ringwald                      hci_stack->le_advertisements_own_addr_type,
432545c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address_type,
432645c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address,
432745c102fdSMatthias Ringwald                      hci_stack->le_advertisements_channel_map,
432845c102fdSMatthias Ringwald                      hci_stack->le_advertisements_filter_policy);
4329f30077b7SMatthias Ringwald         return true;
433045c102fdSMatthias Ringwald     }
4331501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4332501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
43337a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
43347a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
43356535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
43366535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
43373c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
43387a85e4f5SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4339f30077b7SMatthias Ringwald         return true;
434045c102fdSMatthias Ringwald     }
4341501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4342501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4343f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
4344f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
43456535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
43466535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
43473c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4348214bfd60SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4349f30077b7SMatthias Ringwald         return true;
4350501f56b3SMatthias Ringwald     }
4351d70217a2SMatthias Ringwald #endif
43529956955bSMatthias Ringwald 
435313eb2a2eSMatthias Ringwald 
4354057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4355a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
4356a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4357057ab60cSMatthias Ringwald #endif
4358057ab60cSMatthias Ringwald 
4359a41310b7SMatthias Ringwald     // LE Whitelist Management
4360a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
43619956955bSMatthias Ringwald         // add/remove entries
4362665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4363665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
4364665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4365453459ddSMatthias Ringwald 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4366453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4367453459ddSMatthias Ringwald 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4368453459ddSMatthias Ringwald 				return true;
4369453459ddSMatthias Ringwald 			}
43709956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4371453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4372453459ddSMatthias Ringwald                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
43739956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4374f30077b7SMatthias Ringwald                 return true;
43759956955bSMatthias Ringwald             }
4376453459ddSMatthias Ringwald             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4377665d90f2SMatthias Ringwald 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
43789956955bSMatthias Ringwald 				btstack_memory_whitelist_entry_free(entry);
43799956955bSMatthias Ringwald             }
43809956955bSMatthias Ringwald         }
438191915b0bSMatthias Ringwald     }
43829956955bSMatthias Ringwald 
438321debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
438421debf25SMatthias Ringwald     // LE Resolving List Management
4385ea151974SMatthias Ringwald     if (resolving_list_supported) {
438621debf25SMatthias Ringwald 		uint16_t i;
438721debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
438821debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
438921debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
439021debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
439121debf25SMatthias Ringwald 				return true;
439221debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
439321debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
439421debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
439521debf25SMatthias Ringwald 				return true;
439621debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
439702b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4398ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4399ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
4400ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4401ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
440221debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
440321debf25SMatthias Ringwald 				return true;
440402b02cffSMatthias Ringwald 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
440502b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
440602b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
440702b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
440802b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
440902b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
441002b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
441102b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
441202b02cffSMatthias Ringwald 					sm_key_t peer_irk;
441302b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
441402b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4415f5228c62SMatthias Ringwald 
4416f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4417f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
4418f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4419f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
4420f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4421f5228c62SMatthias Ringwald 						if (entry->address_type != peer_identity_addr_type) continue;
4422f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4423f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4424f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4425f5228c62SMatthias Ringwald 					}
4426f5228c62SMatthias Ringwald #endif
4427f5228c62SMatthias Ringwald 
4428ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4429ea151974SMatthias Ringwald 								 peer_identity_addreses);
443002b02cffSMatthias Ringwald 					return true;
443102b02cffSMatthias Ringwald 				}
443202b02cffSMatthias Ringwald 
443302b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
443402b02cffSMatthias Ringwald 
443502b02cffSMatthias Ringwald 				/* fall through */
443602b02cffSMatthias Ringwald 
443721debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_ADD_ENTRIES:
443821debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
443921debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
444021debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
444102b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
444202b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
444321debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
444421debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
444521debf25SMatthias Ringwald 					sm_key_t peer_irk;
444621debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
444721debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
444821debf25SMatthias Ringwald 					const uint8_t *local_irk = gap_get_persistent_irk();
444921debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
445021debf25SMatthias Ringwald 					uint8_t local_irk_flipped[16];
445121debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
445221debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
445321debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
4454ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4455ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
445621debf25SMatthias Ringwald 					return true;
445721debf25SMatthias Ringwald 				}
445802b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
445921debf25SMatthias Ringwald 				break;
446002b02cffSMatthias Ringwald 
446121debf25SMatthias Ringwald 			default:
446221debf25SMatthias Ringwald 				break;
446321debf25SMatthias Ringwald 		}
4464ea151974SMatthias Ringwald 	}
446521debf25SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
446621debf25SMatthias Ringwald #endif
4467a41310b7SMatthias Ringwald 
4468a41310b7SMatthias Ringwald     // Phase 4: restore state
446929c24bebSMatthias Ringwald 
447029c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4471af64f147SMatthias Ringwald     // re-start scanning
447229c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
447329c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
447429c24bebSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
447529c24bebSMatthias Ringwald         return true;
447629c24bebSMatthias Ringwald     }
447729c24bebSMatthias Ringwald #endif
447829c24bebSMatthias Ringwald 
447913eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4480af64f147SMatthias Ringwald     // re-start connecting
4481af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
44829956955bSMatthias Ringwald         bd_addr_t null_addr;
44839956955bSMatthias Ringwald         memset(null_addr, 0, 6);
44846bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
44856bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
44869956955bSMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
4487cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4488cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
44899956955bSMatthias Ringwald                      1,         // use whitelist
44909956955bSMatthias Ringwald                      0,         // peer address type
44919956955bSMatthias Ringwald                      null_addr, // peer bd addr
44926bcfa632SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
449373044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_min,    // conn interval min
449473044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_max,    // conn interval max
449573044eb2SMatthias Ringwald                      hci_stack->le_connection_latency,         // conn latency
449673044eb2SMatthias Ringwald                      hci_stack->le_supervision_timeout,        // conn latency
449773044eb2SMatthias Ringwald                      hci_stack->le_minimum_ce_length,          // min ce length
449873044eb2SMatthias Ringwald                      hci_stack->le_maximum_ce_length           // max ce length
44999956955bSMatthias Ringwald         );
4500f30077b7SMatthias Ringwald         return true;
45019956955bSMatthias Ringwald     }
4502d70217a2SMatthias Ringwald #endif
4503a41310b7SMatthias Ringwald 
4504a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4505a41310b7SMatthias Ringwald     // re-start advertising
45068978dcf1SMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4507a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
45085226d7f2SMatthias Ringwald         hci_stack->le_advertisements_active = true;
45096bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_advertisements_own_address);
4510a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4511a41310b7SMatthias Ringwald         return true;
4512a41310b7SMatthias Ringwald     }
4513a41310b7SMatthias Ringwald #endif
4514a41310b7SMatthias Ringwald 
4515f30077b7SMatthias Ringwald     return false;
45167bdc6798S[email protected] }
4517b2f949feS[email protected] #endif
45187bdc6798S[email protected] 
451988a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
4520f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
4521a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
452205ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
452332ab9390Smatthias.ringwald 
45240bf6344aS[email protected]         switch(connection->state){
45250bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
45264f3229d8S[email protected]                 switch(connection->address_type){
452735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4528f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
45299da54300S[email protected]                         log_info("sending hci_create_connection");
4530b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
45314f3229d8S[email protected]                         break;
453235454696SMatthias Ringwald #endif
45334f3229d8S[email protected]                     default:
4534a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4535d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
45369da54300S[email protected]                         log_info("sending hci_le_create_connection");
45376bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
45386bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
45394f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
4540cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4541cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_window,      // conn scan windows
45424f3229d8S[email protected]                                      0,         // don't use whitelist
45434f3229d8S[email protected]                                      connection->address_type, // peer address type
45444f3229d8S[email protected]                                      connection->address,      // peer bd addr
45456bcfa632SMatthias Ringwald                                      hci_stack->le_connection_own_addr_type,   // our addr type:
454673044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_min,    // conn interval min
454773044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_max,    // conn interval max
454873044eb2SMatthias Ringwald                                      hci_stack->le_connection_latency,         // conn latency
454973044eb2SMatthias Ringwald                                      hci_stack->le_supervision_timeout,        // conn latency
455073044eb2SMatthias Ringwald                                      hci_stack->le_minimum_ce_length,          // min ce length
455173044eb2SMatthias Ringwald                                      hci_stack->le_maximum_ce_length          // max ce length
45524f3229d8S[email protected]                         );
45534f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
4554b2f949feS[email protected] #endif
4555d70217a2SMatthias Ringwald #endif
45564f3229d8S[email protected]                         break;
45574f3229d8S[email protected]                 }
4558f30077b7SMatthias Ringwald                 return true;
4559ad83dc6aS[email protected] 
456035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
45610bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
45625cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
4563f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
456476ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
4565895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4566c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4567e35edcc1S[email protected]                 }
4568f30077b7SMatthias Ringwald                 return true;
456935454696SMatthias Ringwald #endif
45700bf6344aS[email protected] 
4571a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4572d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
45730bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
45740bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
45750bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
4576f30077b7SMatthias Ringwald                 return true;
4577a6725849S[email protected] #endif
4578d70217a2SMatthias Ringwald #endif
45790bf6344aS[email protected]             case SEND_DISCONNECT:
45800bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
45816ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4582f30077b7SMatthias Ringwald                 return true;
45830bf6344aS[email protected] 
45840bf6344aS[email protected]             default:
45850bf6344aS[email protected]                 break;
4586c7e0c5f6Smatthias.ringwald         }
4587c7e0c5f6Smatthias.ringwald 
4588cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
4589cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
4590cabf004eSMatthias Ringwald 
45918daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
45928daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4593891b9fc2SMatthias Ringwald             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4594f30077b7SMatthias Ringwald             return true;
4595891b9fc2SMatthias Ringwald         }
4596891b9fc2SMatthias Ringwald 
459794418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
459894418890SMatthias Ringwald 
45998daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
46008daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
46016909f064SMatthias Ringwald             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4602f30077b7SMatthias Ringwald             return true;
46036909f064SMatthias Ringwald         }
46046909f064SMatthias Ringwald 
4605ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
460650f49832SMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
4607608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
46088daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
460930e72d78SMatthias Ringwald 
4610e9f98c4aSMatthias Ringwald             // lookup link key using cached key first
4611e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4612e9f98c4aSMatthias Ringwald             if (!have_link_key && (hci_stack->link_key_db != NULL)){
4613e9f98c4aSMatthias Ringwald                 have_link_key = hci_stack->link_key_db->get_link_key(connection->address, connection->link_key, &connection->link_key_type);
4614e9f98c4aSMatthias Ringwald             }
461530e72d78SMatthias Ringwald 
4616e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
461730e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
4618e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
461932ab9390Smatthias.ringwald             } else {
462032ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
462132ab9390Smatthias.ringwald             }
4622f30077b7SMatthias Ringwald             return true;
462332ab9390Smatthias.ringwald         }
46241d6b20aeS[email protected] 
46258daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
46269da54300S[email protected]             log_info("denying to pin request");
46278daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
462834d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4629f30077b7SMatthias Ringwald             return true;
46304c57c146S[email protected]         }
46314c57c146S[email protected] 
46328daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
46338daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4634a8d20135SMatthias Ringwald             // set authentication requirements:
4635a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4636532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4637a8d20135SMatthias Ringwald             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
46389faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
46399faad3abS[email protected]                 authreq |= 1;
4640106d6d11S[email protected]             }
4641532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
46428daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4643532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
4644532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4645532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
4646532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
4647532454f9SMatthias Ringwald                     bonding = false;
4648532454f9SMatthias Ringwald                 }
4649532454f9SMatthias Ringwald             }
4650532454f9SMatthias Ringwald             if (bonding){
4651a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
4652a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4653532454f9SMatthias Ringwald                 } else {
4654a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4655a8d20135SMatthias Ringwald                 }
4656532454f9SMatthias Ringwald             }
46571849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
46581849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
46591849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
46601849becdSMatthias Ringwald                     have_oob_data |= 1;
46611849becdSMatthias Ringwald             }
46621849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
46631849becdSMatthias Ringwald                 have_oob_data |= 2;
46641849becdSMatthias Ringwald             }
46651849becdSMatthias Ringwald #endif
46661849becdSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
466711b03efaSMatthias Ringwald             return true;
4668f8fb5f6eS[email protected]         }
466911b03efaSMatthias Ringwald 
46708daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
46718daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
467211b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4673f30077b7SMatthias Ringwald             return true;
467432ab9390Smatthias.ringwald         }
467532ab9390Smatthias.ringwald 
46761849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
46777ca4a7edSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
46787ca4a7edSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
46791849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
46801849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
46811849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
46821849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
46831849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
46841849becdSMatthias Ringwald             // verify P-256 OOB
46851849becdSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
46861849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
46871849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
46881849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
46891849becdSMatthias Ringwald                 }
46901849becdSMatthias Ringwald             }
46911849becdSMatthias Ringwald             // verify P-192 OOB
46921849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
46931849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
46941849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
46951849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
46961849becdSMatthias Ringwald                 }
46971849becdSMatthias Ringwald             }
46987ca4a7edSMatthias Ringwald 
46997ca4a7edSMatthias Ringwald             // assess security
47007ca4a7edSMatthias Ringwald             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
47017ca4a7edSMatthias Ringwald             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
47027ca4a7edSMatthias Ringwald             if (need_level_4 && !can_reach_level_4){
47037ca4a7edSMatthias Ringwald                 log_info("Level 4 required, but not possible -> abort");
47047ca4a7edSMatthias Ringwald                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
47057ca4a7edSMatthias Ringwald                 // send oob negative reply
47067ca4a7edSMatthias Ringwald                 c_256 = NULL;
47077ca4a7edSMatthias Ringwald                 c_192 = NULL;
47087ca4a7edSMatthias Ringwald             }
47097ca4a7edSMatthias Ringwald 
47101849becdSMatthias Ringwald             // Reply
47111849becdSMatthias Ringwald             if (c_256 != zero) {
47121849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
47131849becdSMatthias Ringwald             } else if (c_192 != zero){
47141849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
47151849becdSMatthias Ringwald             } else {
47161ae74bf3SMatthias Ringwald                 hci_stack->classic_oob_con_handle = connection->con_handle;
47171849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
47181849becdSMatthias Ringwald             }
47191849becdSMatthias Ringwald             return true;
47201849becdSMatthias Ringwald         }
47211849becdSMatthias Ringwald #endif
47221849becdSMatthias Ringwald 
47238daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
47248daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
472534d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4726f30077b7SMatthias Ringwald             return true;
4727dbe1a790S[email protected]         }
4728dbe1a790S[email protected] 
4729367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4730367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4731367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4732367aedc0SMatthias Ringwald             return true;
4733367aedc0SMatthias Ringwald         }
4734367aedc0SMatthias Ringwald 
47358daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
47368daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
473734d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4738f30077b7SMatthias Ringwald             return true;
4739dbe1a790S[email protected]         }
4740afd4e962S[email protected] 
4741ba018746SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4742ba018746SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
474334d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4744f30077b7SMatthias Ringwald             return true;
47452bd8b7e7S[email protected]         }
47462bd8b7e7S[email protected] 
47475ccef624SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
47485ccef624SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
47495ccef624SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
47505ccef624SMatthias Ringwald             return true;
47515ccef624SMatthias Ringwald         }
47525ccef624SMatthias Ringwald 
475382721f83SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
475482721f83SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
475582721f83SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
475682721f83SMatthias Ringwald             return true;
475782721f83SMatthias Ringwald         }
475882721f83SMatthias Ringwald 
4759ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4760ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
47611bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
47626ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
47636ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4764f30077b7SMatthias Ringwald             return true;
4765ad83dc6aS[email protected]         }
476676f27cffSMatthias Ringwald 
47672a75353aSMatthias Ringwald         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
476834d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4769abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
477034d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4771f30077b7SMatthias Ringwald             return true;
4772afd4e962S[email protected]         }
477376f27cffSMatthias Ringwald 
4774dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4775dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4776dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4777f30077b7SMatthias Ringwald             return true;
4778dce78009S[email protected]         }
4779573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4780573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4781573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4782f30077b7SMatthias Ringwald             return true;
4783573897a0SMatthias Ringwald         }
478476f27cffSMatthias Ringwald #endif
478576f27cffSMatthias Ringwald 
478676f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
478776f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
47881714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
47891714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
47901714cbbdSMatthias Ringwald #endif
47916ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
47926ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
47936ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4794f30077b7SMatthias Ringwald                 return true;
479576f27cffSMatthias Ringwald             }
47966ef3696aSMatthias Ringwald         }
4797da886c03S[email protected] 
47986cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
4799f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
4800f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
4801f8ee3071SMatthias Ringwald             case 0:
4802f8ee3071SMatthias Ringwald                 break;
4803f8ee3071SMatthias Ringwald             case 0xffff:
4804f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
4805f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4806f30077b7SMatthias Ringwald                 return true;
4807f8ee3071SMatthias Ringwald             default:
4808f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
4809f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
4810f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4811f30077b7SMatthias Ringwald                 return true;
4812f8ee3071SMatthias Ringwald         }
481388a03c8dSMatthias Ringwald 
4814140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
4815140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
4816140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
4817140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4818140c0557SMatthias Ringwald             return true;
4819140c0557SMatthias Ringwald         }
4820140c0557SMatthias Ringwald 
4821965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4822278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
4823965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4824278ff8a9SMatthias Ringwald             hci_send_cmd(&hci_qos_setup, connection->con_handle, 0, service_type, connection->qos_token_rate, connection->qos_peak_bandwidth, connection->qos_latency, connection->qos_delay_variation);
4825278ff8a9SMatthias Ringwald             return true;
4826278ff8a9SMatthias Ringwald         }
4827278ff8a9SMatthias Ringwald 
482888a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
482988a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
483088a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
483188a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
483288a03c8dSMatthias Ringwald             return true;
483388a03c8dSMatthias Ringwald         }
48346cdc2862SMatthias Ringwald #endif
4835f8ee3071SMatthias Ringwald 
4836a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
483773cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
483873cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
483973cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4840da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
484173cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4842c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4843c37a3166S[email protected]                              0x0000, 0xffff);
4844f30077b7SMatthias Ringwald                 return true;
484573cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
484673cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
484773cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
484873cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
484973cd8a2aSMatthias Ringwald                              0x0000, 0xffff);
4850f30077b7SMatthias Ringwald                 return true;
485173cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
485273cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
485373cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4854f30077b7SMatthias Ringwald                 return true;
485573cd8a2aSMatthias Ringwald             default:
485673cd8a2aSMatthias Ringwald                 break;
4857c37a3166S[email protected]         }
48584ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
4859b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
4860b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
4861b90f6e0aSMatthias Ringwald             hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options);
4862f30077b7SMatthias Ringwald             return true;
4863b90f6e0aSMatthias Ringwald         }
4864c37a3166S[email protected] #endif
4865dbe1a790S[email protected]     }
4866f30077b7SMatthias Ringwald     return false;
4867f30077b7SMatthias Ringwald }
4868c7e0c5f6Smatthias.ringwald 
4869f30077b7SMatthias Ringwald static void hci_run(void){
4870f30077b7SMatthias Ringwald 
4871f30077b7SMatthias Ringwald     bool done;
4872f30077b7SMatthias Ringwald 
4873f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
4874f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
4875f30077b7SMatthias Ringwald     if (done) return;
4876f30077b7SMatthias Ringwald 
4877f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4878f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
4879f30077b7SMatthias Ringwald     if (!hci_can_send_comand_packet_transport()) return;
4880f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
4881f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
4882f30077b7SMatthias Ringwald         return;
4883f30077b7SMatthias Ringwald     }
4884f30077b7SMatthias Ringwald #endif
4885f30077b7SMatthias Ringwald 
4886f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
4887f30077b7SMatthias Ringwald 
4888f30077b7SMatthias Ringwald     // global/non-connection oriented commands
4889f30077b7SMatthias Ringwald 
4890f30077b7SMatthias Ringwald 
4891f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
4892f30077b7SMatthias Ringwald     // general gap classic
4893f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
4894f30077b7SMatthias Ringwald     if (done) return;
4895f30077b7SMatthias Ringwald #endif
4896f30077b7SMatthias Ringwald 
4897f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
4898f30077b7SMatthias Ringwald     // general gap le
4899f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
4900f30077b7SMatthias Ringwald     if (done) return;
4901f30077b7SMatthias Ringwald #endif
4902f30077b7SMatthias Ringwald 
4903f30077b7SMatthias Ringwald     // send pending HCI commands
490488a03c8dSMatthias Ringwald     done = hci_run_general_pending_commands();
4905f30077b7SMatthias Ringwald     if (done) return;
4906f30077b7SMatthias Ringwald 
4907f30077b7SMatthias Ringwald     // stack state sub statemachines
490805ae8de3SMatthias Ringwald     hci_connection_t * connection;
49093a9fb326S[email protected]     switch (hci_stack->state){
49103429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
491174b323a9SMatthias Ringwald             hci_initializing_run();
49123429f56bSmatthias.ringwald             break;
4913c7e0c5f6Smatthias.ringwald 
4914c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
4915c7e0c5f6Smatthias.ringwald 
491626fe9592SMatthias Ringwald             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
491726fe9592SMatthias Ringwald             switch (hci_stack->substate){
4918beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4919beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4920beceeddeSMatthias Ringwald 
4921a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4922d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4923beceeddeSMatthias Ringwald                     // free whitelist entries
49249956955bSMatthias Ringwald                     {
4925665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_t lit;
4926665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4927665d90f2SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&lit)){
4928665d90f2SMatthias Ringwald                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4929665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
49309956955bSMatthias Ringwald                             btstack_memory_whitelist_entry_free(entry);
49319956955bSMatthias Ringwald                         }
49329956955bSMatthias Ringwald                     }
49339956955bSMatthias Ringwald #endif
4934d70217a2SMatthias Ringwald #endif
4935c7e0c5f6Smatthias.ringwald                     // close all open connections
49363a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
4937c7e0c5f6Smatthias.ringwald                     if (connection){
4938711e6c80SMatthias Ringwald                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4939d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
494032ab9390Smatthias.ringwald 
49418fca890eSMatthias Ringwald                         // check state
49428fca890eSMatthias Ringwald                         if (connection->state == SENT_DISCONNECT) return;
49438fca890eSMatthias Ringwald                         connection->state = SENT_DISCONNECT;
49448fca890eSMatthias Ringwald 
49458837e9efSMatthias Ringwald                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4946c7e0c5f6Smatthias.ringwald 
49478837e9efSMatthias Ringwald                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
49488837e9efSMatthias Ringwald                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
49498837e9efSMatthias Ringwald 
49508837e9efSMatthias Ringwald                         // ... which would be ignored anyway as we shutdown (free) the connection now
4951c7e0c5f6Smatthias.ringwald                         hci_shutdown_connection(connection);
49528837e9efSMatthias Ringwald 
49538837e9efSMatthias Ringwald                         // finally, send the disconnect command
49546ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4955c7e0c5f6Smatthias.ringwald                         return;
4956c7e0c5f6Smatthias.ringwald                     }
495726fe9592SMatthias Ringwald 
4958beceeddeSMatthias Ringwald                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4959beceeddeSMatthias Ringwald                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4960beceeddeSMatthias Ringwald                         log_info("HCI_STATE_HALTING: wait 50 ms");
496126fe9592SMatthias Ringwald                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4962beceeddeSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
496326fe9592SMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
496426fe9592SMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
496526fe9592SMatthias Ringwald                         break;
4966beceeddeSMatthias Ringwald                     }
496726fe9592SMatthias Ringwald 
4968cf373d3aSMatthias Ringwald                     /* fall through */
496926fe9592SMatthias Ringwald 
497026fe9592SMatthias Ringwald                 case HCI_HALTING_CLOSE:
49719da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling off");
4972c7e0c5f6Smatthias.ringwald 
497372ea5239Smatthias.ringwald                     // switch mode
4974c7e0c5f6Smatthias.ringwald                     hci_power_control_off();
49759418f9c9Smatthias.ringwald 
49769da54300S[email protected]                     log_info("HCI_STATE_HALTING, emitting state");
497772ea5239Smatthias.ringwald                     hci_emit_state();
49789da54300S[email protected]                     log_info("HCI_STATE_HALTING, done");
497972ea5239Smatthias.ringwald                     break;
4980beceeddeSMatthias Ringwald 
4981beceeddeSMatthias Ringwald                 case HCI_HALTING_W4_TIMER:
4982beceeddeSMatthias Ringwald                     // keep waiting
4983beceeddeSMatthias Ringwald 
4984beceeddeSMatthias Ringwald                     break;
498526fe9592SMatthias Ringwald                 default:
498626fe9592SMatthias Ringwald                     break;
498726fe9592SMatthias Ringwald             }
498826fe9592SMatthias Ringwald 
498926fe9592SMatthias Ringwald             break;
4990c7e0c5f6Smatthias.ringwald 
499172ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
49923a9fb326S[email protected]             switch(hci_stack->substate) {
499374b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_DISCONNECT:
49949da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
499572ea5239Smatthias.ringwald                     // close all open connections
49963a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
499766da7044Smatthias.ringwald 
4998423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
499966da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
5000d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
500166da7044Smatthias.ringwald                         connection = NULL;
500266da7044Smatthias.ringwald                     }
500366da7044Smatthias.ringwald #endif
500472ea5239Smatthias.ringwald                     if (connection){
500532ab9390Smatthias.ringwald 
500672ea5239Smatthias.ringwald                         // send disconnect
5007d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
500832ab9390Smatthias.ringwald 
50099da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
50106ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
501172ea5239Smatthias.ringwald 
501272ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
501372ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
501472ea5239Smatthias.ringwald                         return;
501572ea5239Smatthias.ringwald                     }
501672ea5239Smatthias.ringwald 
501792368cd3S[email protected]                     if (hci_classic_supported()){
501889db417bSmatthias.ringwald                         // disable page and inquiry scan
5019d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
502032ab9390Smatthias.ringwald 
50219da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
50223a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
502389db417bSmatthias.ringwald 
502489db417bSmatthias.ringwald                         // continue in next sub state
502574b323a9SMatthias Ringwald                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
502689db417bSmatthias.ringwald                         break;
502792368cd3S[email protected]                     }
5028cf373d3aSMatthias Ringwald 
5029cf373d3aSMatthias Ringwald                     /* fall through */
503092368cd3S[email protected] 
503174b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_COMPLETE:
50329da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
5033423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
503428171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
5035d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
503628171530Smatthias.ringwald                         // SLEEP MODE reached
50373a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
503828171530Smatthias.ringwald                         hci_emit_state();
503928171530Smatthias.ringwald                         break;
504028171530Smatthias.ringwald                     }
504128171530Smatthias.ringwald #endif
504272ea5239Smatthias.ringwald                     // switch mode
50433a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5044c7e0c5f6Smatthias.ringwald                     hci_emit_state();
504528171530Smatthias.ringwald                     break;
504628171530Smatthias.ringwald 
504789db417bSmatthias.ringwald                 default:
504889db417bSmatthias.ringwald                     break;
504989db417bSmatthias.ringwald             }
5050c7e0c5f6Smatthias.ringwald             break;
5051c7e0c5f6Smatthias.ringwald 
50523429f56bSmatthias.ringwald         default:
50533429f56bSmatthias.ringwald             break;
50541f504dbdSmatthias.ringwald     }
50553429f56bSmatthias.ringwald }
505616833f0aSmatthias.ringwald 
505731452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
505835454696SMatthias Ringwald     // house-keeping
505935454696SMatthias Ringwald 
506035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5061c8e4258aSmatthias.ringwald     bd_addr_t addr;
5062c8e4258aSmatthias.ringwald     hci_connection_t * conn;
5063c123d999SMatthias Ringwald #endif
5064c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
50656f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
50669cbd2215SMatthias Ringwald #endif
5067c8e4258aSmatthias.ringwald 
50686f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
50696f35bb46SMatthias Ringwald     switch (opcode) {
50709cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
50719cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
50729cbd2215SMatthias Ringwald             break;
50739cbd2215SMatthias Ringwald 
50749cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
50756f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5076724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
50779da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
5078c8e4258aSmatthias.ringwald 
507972cf8859SMatthias Ringwald             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
508072cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
508179e0fa07SMatthias Ringwald                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
508272cf8859SMatthias Ringwald                 return -1;
508372cf8859SMatthias Ringwald             }
508472cf8859SMatthias Ringwald 
5085f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5086ad83dc6aS[email protected]             if (!conn) {
5087f16129ceSMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
508817f1ba2aSmatthias.ringwald                 if (!conn) {
508917f1ba2aSmatthias.ringwald                     // notify client that alloc failed
50902deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5091f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
509217f1ba2aSmatthias.ringwald                 }
5093ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
5094f3e2cd2aSMatthias Ringwald                 conn->role  = HCI_ROLE_MASTER;
5095ad83dc6aS[email protected]             }
5096ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
5097ad83dc6aS[email protected]             switch (conn->state) {
5098ad83dc6aS[email protected]                 // if connection active exists
5099ad83dc6aS[email protected]                 case OPEN:
5100f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
510172cf8859SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5102f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
5103672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
5104672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
5105672e36abSMatthias Ringwald                     break;
5106ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
5107532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5108532f91a5SMatthias Ringwald                     break;
5109ad83dc6aS[email protected]                 default:
5110ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
5111f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
5112ad83dc6aS[email protected]             }
5113c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
5114229331c6SMatthias Ringwald 
5115229331c6SMatthias Ringwald             // track outgoing connection
5116f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
51176535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
51186f35bb46SMatthias Ringwald             break;
51196f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
5120a98592bcSMatthias Ringwald             if (hci_stack->link_key_db) {
5121724d70a2SMatthias Ringwald                 reverse_bd_addr(&packet[3], addr);
5122a98592bcSMatthias Ringwald                 hci_stack->link_key_db->delete_link_key(addr);
51238ef73945Smatthias.ringwald             }
51246f35bb46SMatthias Ringwald             break;
5125ee752bb8SMatthias Ringwald 
51265b7087c7SMatthias Ringwald #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
51276f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5128ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
5129ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
5130ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
51316f35bb46SMatthias Ringwald             break;
51326f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5133ee752bb8SMatthias Ringwald             // accept_synchronus_connection? Voice setting at offset 18
5134ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
5135ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
51366f35bb46SMatthias Ringwald             break;
5137ee752bb8SMatthias Ringwald #endif
513835454696SMatthias Ringwald #endif
51394b3e1e19SMatthias Ringwald 
5140a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
51416f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5142b95a5a35SMatthias Ringwald             hci_stack->le_random_address_set = 1;
5143b95a5a35SMatthias Ringwald             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
51446f35bb46SMatthias Ringwald             break;
51457e8d8b1dSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51466f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
51475226d7f2SMatthias Ringwald             hci_stack->le_advertisements_active = packet[3] != 0;
51486f35bb46SMatthias Ringwald             break;
5149d70217a2SMatthias Ringwald #endif
5150d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
51516f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5152b04dfa37SMatthias Ringwald             // white list used?
51536f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
5154b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
5155b04dfa37SMatthias Ringwald                 case 0:
5156b04dfa37SMatthias Ringwald                     // whitelist not used
5157b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5158b04dfa37SMatthias Ringwald                     break;
5159b04dfa37SMatthias Ringwald                 case 1:
5160b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5161b04dfa37SMatthias Ringwald                     break;
5162b04dfa37SMatthias Ringwald                 default:
5163b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5164b04dfa37SMatthias Ringwald                     break;
5165b04dfa37SMatthias Ringwald             }
5166c163146eSMatthias Ringwald             // track outgoing connection
516705002aecSMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5168c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
51696f35bb46SMatthias Ringwald             break;
51706f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
51716ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
51726f35bb46SMatthias Ringwald             break;
51739cbd2215SMatthias Ringwald #endif
51749cbd2215SMatthias Ringwald #endif
51756f35bb46SMatthias Ringwald         default:
51766f35bb46SMatthias Ringwald             break;
5177b04dfa37SMatthias Ringwald     }
517869a97523S[email protected] 
51793a9fb326S[email protected]     hci_stack->num_cmd_packets--;
51805bb5bc3eS[email protected] 
51815bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5182bfea0222SMatthias Ringwald     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
518331452debSmatthias.ringwald }
51848adf0ddaSmatthias.ringwald 
51852bd8b7e7S[email protected] // disconnect because of security block
51862bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
51872bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
51882bd8b7e7S[email protected]     if (!connection) return;
51892bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
51902bd8b7e7S[email protected] }
51912bd8b7e7S[email protected] 
51922bd8b7e7S[email protected] 
5193dbe1a790S[email protected] // Configure Secure Simple Pairing
5194dbe1a790S[email protected] 
519535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
519635454696SMatthias Ringwald 
5197dbe1a790S[email protected] // enable will enable SSP during init
519815a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
51993a9fb326S[email protected]     hci_stack->ssp_enable = enable;
5200dbe1a790S[email protected] }
5201dbe1a790S[email protected] 
520295d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
520315a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
52042bd8b7e7S[email protected] }
52052bd8b7e7S[email protected] 
5206dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
520715a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
52083a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
5209dbe1a790S[email protected] }
521015a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
52113a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
5212dbe1a790S[email protected] }
5213dbe1a790S[email protected] 
5214dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
521515a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
52163a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
5217dbe1a790S[email protected] }
52185d23aae8SMatthias Ringwald 
52195d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
52205d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
52215d23aae8SMatthias Ringwald }
52225d23aae8SMatthias Ringwald 
522335454696SMatthias Ringwald #endif
5224dbe1a790S[email protected] 
522594be1a66SMatthias Ringwald // va_list part of hci_send_cmd
522694be1a66SMatthias Ringwald int hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5227d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
52289d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
52299d14b626S[email protected]         return 0;
52309d14b626S[email protected]     }
52319d14b626S[email protected] 
52325127cc62S[email protected]     // for HCI INITIALIZATION
52339da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
52345127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
52355127cc62S[email protected] 
52369d14b626S[email protected]     hci_reserve_packet_buffer();
52379d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
523894be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5239bfea0222SMatthias Ringwald     int err = hci_send_cmd_packet(packet, size);
5240bfea0222SMatthias Ringwald 
5241593702caSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
5242593702caSMatthias Ringwald     if ((err < 0) || hci_transport_synchronous()){
5243e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5244068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
5245bfea0222SMatthias Ringwald     }
5246bfea0222SMatthias Ringwald 
5247bfea0222SMatthias Ringwald     return err;
524894be1a66SMatthias Ringwald }
52499d14b626S[email protected] 
525094be1a66SMatthias Ringwald /**
525194be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
525294be1a66SMatthias Ringwald  */
525394be1a66SMatthias Ringwald int hci_send_cmd(const hci_cmd_t * cmd, ...){
52541cd208adSmatthias.ringwald     va_list argptr;
52551cd208adSmatthias.ringwald     va_start(argptr, cmd);
525694be1a66SMatthias Ringwald     int res = hci_send_cmd_va_arg(cmd, argptr);
52571cd208adSmatthias.ringwald     va_end(argptr);
525894be1a66SMatthias Ringwald     return res;
525993b8dc03Smatthias.ringwald }
5260c8e4258aSmatthias.ringwald 
5261ee091cf1Smatthias.ringwald // Create various non-HCI events.
5262ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
5263ee091cf1Smatthias.ringwald 
5264d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5265fb37a842SMatthias Ringwald     // dump packet
5266d6b06661SMatthias Ringwald     if (dump) {
5267300c1ba4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5268d6b06661SMatthias Ringwald     }
52691ef6bb52SMatthias Ringwald 
5270fb37a842SMatthias Ringwald     // dispatch to all event handlers
52711ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
52721ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
52731ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
52741ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5275d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
52761ef6bb52SMatthias Ringwald     }
5277d6b06661SMatthias Ringwald }
5278d6b06661SMatthias Ringwald 
5279d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5280fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
52813d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5282d6b06661SMatthias Ringwald }
5283d6b06661SMatthias Ringwald 
528435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5285701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
52863bc639ceSMatthias Ringwald     // notify SCO sender if waiting
5287701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
5288701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
52893bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
5290701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5291701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
52923d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
52933bc639ceSMatthias Ringwald     }
52943bc639ceSMatthias Ringwald }
52951cfb383eSMatthias Ringwald 
52961cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
52979784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5298ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
52991cfb383eSMatthias Ringwald 
53001cfb383eSMatthias Ringwald     uint8_t * eir_data;
53011cfb383eSMatthias Ringwald     ad_context_t context;
53021cfb383eSMatthias Ringwald     const uint8_t * name;
53031cfb383eSMatthias Ringwald     uint8_t         name_len;
53041cfb383eSMatthias Ringwald 
53059784dac1SMatthias Ringwald     if (size < 3) return;
53069784dac1SMatthias Ringwald 
53071cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
5308a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
53091cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
53101cfb383eSMatthias Ringwald 
53119784dac1SMatthias Ringwald     switch (event_type){
53129784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
53139784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
53149784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
53159784dac1SMatthias Ringwald             break;
53169784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
53179784dac1SMatthias Ringwald             if (size != 257) return;
53189784dac1SMatthias Ringwald             if (num_responses != 1) return;
53199784dac1SMatthias Ringwald             break;
53209784dac1SMatthias Ringwald         default:
53219784dac1SMatthias Ringwald             return;
53229784dac1SMatthias Ringwald     }
53239784dac1SMatthias Ringwald 
53241cfb383eSMatthias Ringwald     // event[1] is set at the end
53251cfb383eSMatthias Ringwald     int i;
53261cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
53271cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
53281cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
5329ac973fd6SMatthias Ringwald         uint8_t event_size = 27;    // if name is not set by EIR
53301cfb383eSMatthias Ringwald 
53316535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
53320e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
53336535961aSMatthias Ringwald         (void)memcpy(&event[9],
53346535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
53356535961aSMatthias Ringwald                      3); // class of device
53366535961aSMatthias Ringwald         (void)memcpy(&event[12],
53376535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
53386535961aSMatthias Ringwald                      2); // clock offset
53391cfb383eSMatthias Ringwald 
53401cfb383eSMatthias Ringwald         switch (event_type){
53411cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
53421cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
53431cfb383eSMatthias Ringwald                 break;
53441cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
53451cfb383eSMatthias Ringwald                 event[14] = 1;
5346a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
53471cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
53481cfb383eSMatthias Ringwald                 break;
53491cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
53501cfb383eSMatthias Ringwald                 event[14] = 1;
5351a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
535279186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
53531cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
53541cfb383eSMatthias Ringwald                 name = NULL;
5355a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
5356a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
53571cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
53581cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
53591cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
5360ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
53611cfb383eSMatthias Ringwald                     switch (data_type){
53621cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
53631cfb383eSMatthias Ringwald                             if (name) continue;
5364cf373d3aSMatthias Ringwald                             /* fall through */
53651cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
53661cfb383eSMatthias Ringwald                             name = data;
53671cfb383eSMatthias Ringwald                             name_len = data_size;
53681cfb383eSMatthias Ringwald                             break;
5369ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5370ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
5371ac9136ccSMatthias Ringwald                             event[16] = 1;
53723c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
5373ac9136ccSMatthias Ringwald                             break;
53741cfb383eSMatthias Ringwald                         default:
53751cfb383eSMatthias Ringwald                             break;
53761cfb383eSMatthias Ringwald                     }
53771cfb383eSMatthias Ringwald                 }
53781cfb383eSMatthias Ringwald                 if (name){
5379ac9136ccSMatthias Ringwald                     event[25] = 1;
53801cfb383eSMatthias Ringwald                     // truncate name if needed
53811cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5382ac9136ccSMatthias Ringwald                     event[26] = len;
5383ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
53841cfb383eSMatthias Ringwald                     event_size += len;
53851cfb383eSMatthias Ringwald                 }
53861cfb383eSMatthias Ringwald                 break;
53877bbeb3adSMilanka Ringwald             default:
53887bbeb3adSMilanka Ringwald                 return;
53891cfb383eSMatthias Ringwald         }
53901cfb383eSMatthias Ringwald         event[1] = event_size - 2;
53911cfb383eSMatthias Ringwald         hci_emit_event(event, event_size, 1);
53921cfb383eSMatthias Ringwald     }
53931cfb383eSMatthias Ringwald }
539435454696SMatthias Ringwald #endif
53953bc639ceSMatthias Ringwald 
539671de195eSMatthias Ringwald void hci_emit_state(void){
53973a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5398425d1371Smatthias.ringwald     uint8_t event[3];
539980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
54004ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
54013a9fb326S[email protected]     event[2] = hci_stack->state;
5402d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5403c8e4258aSmatthias.ringwald }
5404c8e4258aSmatthias.ringwald 
540535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
54062deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5407425d1371Smatthias.ringwald     uint8_t event[13];
5408c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5409425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
541017f1ba2aSmatthias.ringwald     event[2] = status;
54112deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
54122deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
5413c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
5414c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
5415d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5416c8e4258aSmatthias.ringwald }
541752db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
541852db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
541952db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
542052db98b2SMatthias Ringwald     uint8_t event[4];
542152db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
542252db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
542352db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
542452db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
542552db98b2SMatthias Ringwald }
542635454696SMatthias Ringwald #endif
5427c8e4258aSmatthias.ringwald 
542835454696SMatthias Ringwald #ifdef ENABLE_BLE
5429d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5430667ba9d1SMatthias Ringwald static void hci_emit_le_connection_complete(uint8_t address_type, const bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
54314f3229d8S[email protected]     uint8_t event[21];
54324f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
54334ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
54344f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
54354f3229d8S[email protected]     event[3] = status;
5436fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
54374f3229d8S[email protected]     event[6] = 0; // TODO: role
54386e2e9a6bS[email protected]     event[7] = address_type;
5439724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
5440f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
5441f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
5442f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
54434f3229d8S[email protected]     event[20] = 0; // master clock accuracy
5444d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
54454f3229d8S[email protected] }
544635454696SMatthias Ringwald #endif
5447d70217a2SMatthias Ringwald #endif
54484f3229d8S[email protected] 
5449fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
5450fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
5451fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5452fd43c0e0SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5453fd43c0e0SMatthias Ringwald }
5454fd43c0e0SMatthias Ringwald 
5455fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5456425d1371Smatthias.ringwald     uint8_t event[6];
54573c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
54584ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
54593c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
5460fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
54613c4d4b90Smatthias.ringwald     event[5] = reason;
5462d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
54633c4d4b90Smatthias.ringwald }
54643c4d4b90Smatthias.ringwald 
5465b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
5466e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5467425d1371Smatthias.ringwald     uint8_t event[3];
546880d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
54694ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
547043bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
5471d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
547243bfb1bdSmatthias.ringwald }
5473038bc64cSmatthias.ringwald 
5474b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
5475e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
5476425d1371Smatthias.ringwald     uint8_t event[2];
547780d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
54784ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
5479d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5480038bc64cSmatthias.ringwald }
54811b0e3922Smatthias.ringwald 
548235454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
548335454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
548435454696SMatthias Ringwald     uint8_t event[9];
548535454696SMatthias Ringwald     int pos = 0;
548635454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
54874ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
548835454696SMatthias Ringwald     event[pos++] = status;
548935454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
5490d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5491381fbed8Smatthias.ringwald }
5492458bf4e8S[email protected] 
549335454696SMatthias Ringwald 
549435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
549535454696SMatthias Ringwald 
5496b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5497df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5498a00031e2S[email protected]     uint8_t event[5];
5499e00caf9cS[email protected]     int pos = 0;
55005611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5501e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
5502f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
5503e00caf9cS[email protected]     pos += 2;
5504e00caf9cS[email protected]     event[pos++] = level;
5505d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5506e00caf9cS[email protected] }
5507e00caf9cS[email protected] 
550835454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
550935454696SMatthias Ringwald     if (!connection) return LEVEL_0;
55108daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5511fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
55128daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5513170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
55144051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5515170fafaeSMatthias Ringwald     // LEVEL 4 always requires 128 bit encrytion key size
55160e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5517170fafaeSMatthias Ringwald         security_level = LEVEL_3;
5518170fafaeSMatthias Ringwald     }
5519170fafaeSMatthias Ringwald     return security_level;
552035454696SMatthias Ringwald }
552135454696SMatthias Ringwald 
552235454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled){
552335454696SMatthias Ringwald     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
552435454696SMatthias Ringwald     uint8_t event[3];
552535454696SMatthias Ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
552635454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
552735454696SMatthias Ringwald     event[2] = enabled;
5528d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5529ad83dc6aS[email protected] }
5530ad83dc6aS[email protected] 
553198a2fd1cSMatthias Ringwald // query if remote side supports eSCO
5532073bd0faSMatthias Ringwald int hci_remote_esco_supported(hci_con_handle_t con_handle){
553398a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
553498a2fd1cSMatthias Ringwald     if (!connection) return 0;
553576ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
553698a2fd1cSMatthias Ringwald }
553798a2fd1cSMatthias Ringwald 
553867aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
553967aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
554067aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
554167aae551SMatthias Ringwald }
554267aae551SMatthias Ringwald 
55432bd8b7e7S[email protected] // query if remote side supports SSP
55442bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
55452bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
55462bd8b7e7S[email protected]     if (!connection) return 0;
554767aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
55482bd8b7e7S[email protected] }
55492bd8b7e7S[email protected] 
555015a95bd5SMatthias Ringwald int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5551df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5552df3354fcS[email protected] }
5553df3354fcS[email protected] 
5554458bf4e8S[email protected] // GAP API
5555458bf4e8S[email protected] /**
5556458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
5557458bf4e8S[email protected]  * @praram enabled
5558458bf4e8S[email protected]  */
55594c57c146S[email protected] void gap_set_bondable_mode(int enable){
55603a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
5561458bf4e8S[email protected] }
55624ef6443cSMatthias Ringwald /**
55634ef6443cSMatthias Ringwald  * @brief Get bondable mode.
55644ef6443cSMatthias Ringwald  * @return 1 if bondable
55654ef6443cSMatthias Ringwald  */
55664ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
55674ef6443cSMatthias Ringwald     return hci_stack->bondable;
55684ef6443cSMatthias Ringwald }
5569cb230b9dS[email protected] 
5570cb230b9dS[email protected] /**
557134d2123cS[email protected]  * @brief map link keys to security levels
5572cb230b9dS[email protected]  */
557334d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
557434d2123cS[email protected]     switch (link_key_type){
55753c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
55763c68dfa9S[email protected]             return LEVEL_4;
55773c68dfa9S[email protected]         case COMBINATION_KEY:
55783c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
55793c68dfa9S[email protected]             return LEVEL_3;
55803c68dfa9S[email protected]         default:
55813c68dfa9S[email protected]             return LEVEL_2;
55823c68dfa9S[email protected]     }
5583cb230b9dS[email protected] }
5584cb230b9dS[email protected] 
55858b35e16aSMatthias Ringwald /**
55868b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
55878b35e16aSMatthias Ringwald  */
55888b35e16aSMatthias Ringwald int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
55898b35e16aSMatthias Ringwald     switch (link_key_type){
55908b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
55918b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
55928b35e16aSMatthias Ringwald             return 1;
55938b35e16aSMatthias Ringwald         default:
55948b35e16aSMatthias Ringwald             return 0;
55958b35e16aSMatthias Ringwald     }
55968b35e16aSMatthias Ringwald }
55978b35e16aSMatthias Ringwald 
55988b35e16aSMatthias Ringwald /**
55998b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
56008b35e16aSMatthias Ringwald  */
56018b35e16aSMatthias Ringwald int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
56028b35e16aSMatthias Ringwald     switch (link_key_type){
56038b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
56048b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
56058b35e16aSMatthias Ringwald             return 1;
56068b35e16aSMatthias Ringwald         default:
56078b35e16aSMatthias Ringwald             return 0;
56088b35e16aSMatthias Ringwald     }
56098b35e16aSMatthias Ringwald }
56108b35e16aSMatthias Ringwald 
5611106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
56125127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
5613106d6d11S[email protected]     return level > LEVEL_2;
5614106d6d11S[email protected] }
5615106d6d11S[email protected] 
561634d2123cS[email protected] /**
561734d2123cS[email protected]  * @brief get current security level
561834d2123cS[email protected]  */
561934d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
562034d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
562134d2123cS[email protected]     if (!connection) return LEVEL_0;
562234d2123cS[email protected]     return gap_security_level_for_connection(connection);
562334d2123cS[email protected] }
562434d2123cS[email protected] 
5625cb230b9dS[email protected] /**
5626cb230b9dS[email protected]  * @brief request connection to device to
5627cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
5628cb230b9dS[email protected]  */
562934d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
563034d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
563134d2123cS[email protected]     if (!connection){
5632a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
563334d2123cS[email protected]         return;
563434d2123cS[email protected]     }
5635defbf200SMatthias Ringwald 
5636defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
5637defbf200SMatthias Ringwald 
5638bc00e12cSMatthias Ringwald     // Core Spec 5.2, GAP 5.2.2: "When in Secure Connections Only mode, all services (except those allowed to have Security Mode 4, Level 0)
5639bc00e12cSMatthias Ringwald     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
5640bc00e12cSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
5641bc00e12cSMatthias Ringwald         requested_level = LEVEL_4;
5642bc00e12cSMatthias Ringwald     }
5643bc00e12cSMatthias Ringwald 
564434d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
564583d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
564683d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
564783d08d7cSMatthias Ringwald 
5648dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
5649dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5650dbd5dcc3SMatthias Ringwald     if (authentication_active){
56511cf0a6c8SMatthias Ringwald         // authentication already active
565283d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
565383d08d7cSMatthias Ringwald             // increase requested level as new level is higher
565483d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
565583d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
565683d08d7cSMatthias Ringwald         }
56571cf0a6c8SMatthias Ringwald     } else {
565883d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
565983d08d7cSMatthias Ringwald         if (requested_level <= current_level){
5660a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
566134d2123cS[email protected]             return;
566234d2123cS[email protected]         }
5663a00031e2S[email protected] 
5664e060c07dSMatthias Ringwald         // store request
566534d2123cS[email protected]         connection->requested_security_level = requested_level;
5666a00031e2S[email protected] 
56671cf0a6c8SMatthias Ringwald         // start to authenticate connection
56681eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5669e80b2cf9S[email protected]         hci_run();
5670e00caf9cS[email protected]     }
56711cf0a6c8SMatthias Ringwald }
5672ad83dc6aS[email protected] 
5673ad83dc6aS[email protected] /**
5674ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
5675ad83dc6aS[email protected]  * @param device
5676ad83dc6aS[email protected]  * @param request MITM protection
5677ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
5678ad83dc6aS[email protected]  */
5679ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5680ad83dc6aS[email protected] 
5681ad83dc6aS[email protected]     // create connection state machine
5682f16129ceSMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5683ad83dc6aS[email protected] 
5684ad83dc6aS[email protected]     if (!connection){
5685ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
5686ad83dc6aS[email protected]     }
5687ad83dc6aS[email protected] 
5688ad83dc6aS[email protected]     // delete linkn key
568915a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
5690ad83dc6aS[email protected] 
5691ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
5692ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
5693ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5694f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5695ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
5696ad83dc6aS[email protected] 
5697ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5698ad83dc6aS[email protected] 
5699ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
5700ad83dc6aS[email protected]     // handle: authentication failure
5701ad83dc6aS[email protected]     // handle: disconnect on done
5702ad83dc6aS[email protected] 
5703ad83dc6aS[email protected]     hci_run();
5704ad83dc6aS[email protected] 
5705ad83dc6aS[email protected]     return 0;
5706ad83dc6aS[email protected] }
570735454696SMatthias Ringwald #endif
57088e618f72S[email protected] 
57098e618f72S[email protected] void gap_set_local_name(const char * local_name){
57108e618f72S[email protected]     hci_stack->local_name = local_name;
57118e618f72S[email protected] }
57128e618f72S[email protected] 
571335454696SMatthias Ringwald 
571435454696SMatthias Ringwald #ifdef ENABLE_BLE
571535454696SMatthias Ringwald 
5716d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5717d8e8f12aSMatthias Ringwald void gap_start_scan(void){
5718fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
57197bdc6798S[email protected]     hci_run();
57207bdc6798S[email protected] }
57218e618f72S[email protected] 
5722d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
5723fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
57247bdc6798S[email protected]     hci_run();
57257bdc6798S[email protected] }
57264f3229d8S[email protected] 
5727a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5728ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
5729a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5730ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
5731ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
57328b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
5733ef11999fSmatthias.ringwald     hci_run();
5734ef11999fSmatthias.ringwald }
57354f3229d8S[email protected] 
5736a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5737a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5738a7a719e9SMatthias Ringwald }
5739a7a719e9SMatthias Ringwald 
5740667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
57414f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
57424f3229d8S[email protected]     if (!conn){
5743d32b3f05SMatthias Ringwald         // disallow if le connection is already outgoing
5744d32b3f05SMatthias Ringwald         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5745d32b3f05SMatthias Ringwald             log_error("le connection already active");
5746d32b3f05SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
5747d32b3f05SMatthias Ringwald         }
5748d32b3f05SMatthias Ringwald 
5749d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
57502e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
57514f3229d8S[email protected]         if (!conn){
57524f3229d8S[email protected]             // notify client that alloc failed
57536e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5754d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
5755472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
57564f3229d8S[email protected]         }
5757d5b1a89eSMatthias Ringwald 
5758d5b1a89eSMatthias Ringwald         // set le connecting state
5759d5b1a89eSMatthias Ringwald         if (hci_is_le_connection_type(addr_type)){
5760d5b1a89eSMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5761d5b1a89eSMatthias Ringwald         }
5762d5b1a89eSMatthias Ringwald 
57634f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
5764d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
5765564fca32S[email protected]         hci_run();
5766b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
57674f3229d8S[email protected]     }
57680bf6344aS[email protected] 
57690bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
5770a1df452eSMatthias Ringwald         (conn->state == SEND_CREATE_CONNECTION) ||
57710e588213SMatthias Ringwald         (conn->state == SENT_CREATE_CONNECTION)) {
57722e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5773d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
5774616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
57750bf6344aS[email protected]     }
57760bf6344aS[email protected] 
5777b0136355SMatthias Ringwald     // check if connection was just disconnected
5778b0136355SMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5779b0136355SMatthias Ringwald         log_info("gap_connect: send create connection (again)");
5780b0136355SMatthias Ringwald         conn->state = SEND_CREATE_CONNECTION;
5781b0136355SMatthias Ringwald         hci_run();
5782b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
5783b0136355SMatthias Ringwald     }
5784b0136355SMatthias Ringwald 
5785d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
5786d5b1a89eSMatthias Ringwald     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
57874f3229d8S[email protected]     hci_run();
5788b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
57894f3229d8S[email protected] }
57904f3229d8S[email protected] 
57917851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
5792d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
5793665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
5794a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
57950bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
57960bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
57970bf6344aS[email protected]         switch (conn->state){
5798a6725849S[email protected]             case SEND_CREATE_CONNECTION:
57997851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
58009c77c9dbSMatthias Ringwald             case SENT_CANCEL_CONNECTION:
58017851196eSmatthias.ringwald                 return conn;
58027851196eSmatthias.ringwald             default:
58037851196eSmatthias.ringwald                 break;
58047851196eSmatthias.ringwald         };
58057851196eSmatthias.ringwald     }
58067851196eSmatthias.ringwald     return NULL;
58077851196eSmatthias.ringwald }
58087851196eSmatthias.ringwald 
5809d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
5810d8e8f12aSMatthias Ringwald     hci_connection_t * conn = gap_get_outgoing_connection();
5811616edd56SMatthias Ringwald     if (!conn) return 0;
58127851196eSmatthias.ringwald     switch (conn->state){
58137851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
58147851196eSmatthias.ringwald             // skip sending create connection and emit event instead
581510f8f469SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
58162e77e513S[email protected]             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5817665d90f2SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
58187851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
58190bf6344aS[email protected]             break;
5820a6725849S[email protected]         case SENT_CREATE_CONNECTION:
58217851196eSmatthias.ringwald             // request to send cancel connection
58220bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
58230bf6344aS[email protected]             hci_run();
58240bf6344aS[email protected]             break;
58250bf6344aS[email protected]         default:
58260bf6344aS[email protected]             break;
58270bf6344aS[email protected]     }
5828616edd56SMatthias Ringwald     return 0;
5829e31f89a7S[email protected] }
5830d70217a2SMatthias Ringwald #endif
58314f3229d8S[email protected] 
583213e645d2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5833c37a3166S[email protected] /**
58346012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
5835cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5836cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
58376012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
58386012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
58396012052bSMatthias Ringwald  * @param conn_latency, default: 4
58406012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
58416012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
58426012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
58436012052bSMatthias Ringwald  */
58446012052bSMatthias Ringwald 
5845cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5846cbe54ab2SJakob Krantz     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5847cbe54ab2SJakob Krantz     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5848cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
5849cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
58506012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
58516012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
58526012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
58536012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
58546012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
58556012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
58566012052bSMatthias Ringwald }
585713e645d2SMatthias Ringwald #endif
58586012052bSMatthias Ringwald 
58596012052bSMatthias Ringwald /**
5860c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
5861c37a3166S[email protected]  * @param handle
5862c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
5863c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
5864c37a3166S[email protected]  * @param conn_latency
5865c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
5866c37a3166S[email protected]  * @returns 0 if ok
5867c37a3166S[email protected]  */
5868c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5869c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5870c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5871c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5872c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
5873c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
5874c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
5875c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
587684cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5877cfc59f1bSMatthias Ringwald     hci_run();
5878c37a3166S[email protected]     return 0;
5879c37a3166S[email protected] }
5880c37a3166S[email protected] 
588145c102fdSMatthias Ringwald /**
5882b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
5883b68d7bc3SMatthias Ringwald  * @param handle
5884b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
5885b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
5886b68d7bc3SMatthias Ringwald  * @param conn_latency
5887b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
5888b68d7bc3SMatthias Ringwald  * @returns 0 if ok
5889b68d7bc3SMatthias Ringwald  */
5890b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5891b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5892b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5893b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5894b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
5895b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
5896b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
5897b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
5898b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
589909c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
590009c9c963SMatthias Ringwald     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5901b68d7bc3SMatthias Ringwald     return 0;
5902b68d7bc3SMatthias Ringwald }
5903b68d7bc3SMatthias Ringwald 
5904d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5905d70217a2SMatthias Ringwald 
5906b68d7bc3SMatthias Ringwald /**
590745c102fdSMatthias Ringwald  * @brief Set Advertisement Data
590845c102fdSMatthias Ringwald  * @param advertising_data_length
590945c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
591045c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
591145c102fdSMatthias Ringwald  */
591245c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
591345c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
591445c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
5915501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5916bbc366e6SMatthias Ringwald     hci_run();
591745c102fdSMatthias Ringwald }
5918501f56b3SMatthias Ringwald 
5919501f56b3SMatthias Ringwald /**
5920501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
5921501f56b3SMatthias Ringwald  * @param advertising_data_length
5922501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
5923501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
5924501f56b3SMatthias Ringwald  */
5925501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5926501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
5927501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
5928501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5929bbc366e6SMatthias Ringwald     hci_run();
593045c102fdSMatthias Ringwald }
593145c102fdSMatthias Ringwald 
593245c102fdSMatthias Ringwald /**
593345c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
593445c102fdSMatthias Ringwald  * @param adv_int_min
593545c102fdSMatthias Ringwald  * @param adv_int_max
593645c102fdSMatthias Ringwald  * @param adv_type
593745c102fdSMatthias Ringwald  * @param direct_address_type
593845c102fdSMatthias Ringwald  * @param direct_address
593945c102fdSMatthias Ringwald  * @param channel_map
594045c102fdSMatthias Ringwald  * @param filter_policy
594145c102fdSMatthias Ringwald  *
594245c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
594345c102fdSMatthias Ringwald  */
594445c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5945b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
594645c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
594745c102fdSMatthias Ringwald 
594845c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
594945c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
595045c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
595145c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
595245c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
595345c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
59546535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
59556535961aSMatthias Ringwald                  6);
595645c102fdSMatthias Ringwald 
5957a61834b6SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
5958bbc366e6SMatthias Ringwald     hci_run();
595945c102fdSMatthias Ringwald  }
596045c102fdSMatthias Ringwald 
596145c102fdSMatthias Ringwald /**
596245c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
596345c102fdSMatthias Ringwald  * @param enabled
596445c102fdSMatthias Ringwald  */
596545c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
59665226d7f2SMatthias Ringwald     hci_stack->le_advertisements_enabled = enabled != 0;
5967bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
5968cfc59f1bSMatthias Ringwald     hci_run();
596945c102fdSMatthias Ringwald }
597045c102fdSMatthias Ringwald 
597135454696SMatthias Ringwald #endif
597206e5cf96SMatthias Ringwald 
597306e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
597406e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
597506e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
597606e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
597706e5cf96SMatthias Ringwald 
597864068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
597906e5cf96SMatthias Ringwald     // update advertisement parameters, too
598006e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5981bbc366e6SMatthias Ringwald     hci_run();
598264068776SMatthias Ringwald #endif
598364068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
598406e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
598564068776SMatthias Ringwald #endif
598606e5cf96SMatthias Ringwald }
598706e5cf96SMatthias Ringwald 
5988d70217a2SMatthias Ringwald #endif
598945c102fdSMatthias Ringwald 
5990616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
59915917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
59925917a5c5S[email protected]     if (!conn){
59937851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
5994616edd56SMatthias Ringwald         return 0;
59955917a5c5S[email protected]     }
59967fd7aa6fSMatthias Ringwald     // ignore if already disconnected
59977fd7aa6fSMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
59987fd7aa6fSMatthias Ringwald         return 0;
59997fd7aa6fSMatthias Ringwald     }
60005917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
60015917a5c5S[email protected]     hci_run();
6002616edd56SMatthias Ringwald     return 0;
60034f3229d8S[email protected] }
600404a6ef8cSmatthias.ringwald 
6005228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
6006228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6007228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
60088daf94bcSMatthias Ringwald     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
6009228e430cSMatthias Ringwald     hci_run();
6010228e430cSMatthias Ringwald     return 1;
6011228e430cSMatthias Ringwald }
6012228e430cSMatthias Ringwald 
6013a1bf5ae7SMatthias Ringwald /**
6014a1bf5ae7SMatthias Ringwald  * @brief Get connection type
6015a1bf5ae7SMatthias Ringwald  * @param con_handle
6016a1bf5ae7SMatthias Ringwald  * @result connection_type
6017a1bf5ae7SMatthias Ringwald  */
6018a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
6019a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6020a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6021a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
6022a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
6023a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6024a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
6025a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
6026a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
6027f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6028a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
6029a1bf5ae7SMatthias Ringwald         default:
6030a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
6031a1bf5ae7SMatthias Ringwald     }
6032a1bf5ae7SMatthias Ringwald }
6033a1bf5ae7SMatthias Ringwald 
60342dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
60352dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
60362dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
60372dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
60382dceb1d6SMatthias Ringwald }
60392dceb1d6SMatthias Ringwald 
60402dceb1d6SMatthias Ringwald 
604144f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
6042667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
604388a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
604488a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
604588a03c8dSMatthias Ringwald     conn->request_role = role;
604688a03c8dSMatthias Ringwald     hci_run();
6047d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
604888a03c8dSMatthias Ringwald }
604944f858f3SMatthias Ringwald #endif
605088a03c8dSMatthias Ringwald 
6051a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
60524f551432SMatthias Ringwald 
6053b45b7749SMilanka Ringwald uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
6054b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6055b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6056b90f6e0aSMatthias Ringwald 
6057b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
6058b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
6059b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
6060b90f6e0aSMatthias Ringwald     conn->le_phy_update_phy_options = phy_options;
6061b90f6e0aSMatthias Ringwald 
6062b90f6e0aSMatthias Ringwald     hci_run();
6063b90f6e0aSMatthias Ringwald 
6064b90f6e0aSMatthias Ringwald     return 0;
6065b90f6e0aSMatthias Ringwald }
6066b90f6e0aSMatthias Ringwald 
6067667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
60687a92a9dbSMatthias Ringwald     // check if already in list
60697a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
60707a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
60717a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
60727a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
60737a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
60747a92a9dbSMatthias Ringwald             continue;
60757a92a9dbSMatthias Ringwald         }
60767a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
60777a92a9dbSMatthias Ringwald             continue;
60787a92a9dbSMatthias Ringwald         }
6079287379ccSMatthias Ringwald 		// disallow if already scheduled to add
6080287379ccSMatthias Ringwald 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
60817a92a9dbSMatthias Ringwald 			return ERROR_CODE_COMMAND_DISALLOWED;
60827a92a9dbSMatthias Ringwald 		}
6083287379ccSMatthias Ringwald 		// still on controller, but scheduled to remove -> re-add
6084287379ccSMatthias Ringwald 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
6085287379ccSMatthias Ringwald 		return ERROR_CODE_SUCCESS;
6086287379ccSMatthias Ringwald     }
60877a92a9dbSMatthias Ringwald     // alloc and add to list
6088e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
6089e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
6090e83201bcSMatthias Ringwald     entry->address_type = address_type;
60916535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
6092e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
6093665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
6094226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6095ac9c45e0SMatthias Ringwald }
6096ac9c45e0SMatthias Ringwald 
6097667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6098665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
6099665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6100665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6101665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
61027a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
61037a92a9dbSMatthias Ringwald             continue;
61047a92a9dbSMatthias Ringwald         }
61057a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
61067a92a9dbSMatthias Ringwald             continue;
61077a92a9dbSMatthias Ringwald         }
6108e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6109e83201bcSMatthias Ringwald             // remove from controller if already present
6110e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6111a3b69fdeSMatthias Ringwald         }  else {
6112226db5efSMatthias Ringwald             // directly remove entry from whitelist
6113665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
6114e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
6115e83201bcSMatthias Ringwald         }
6116a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
6117a3b69fdeSMatthias Ringwald     }
6118a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
611942ff5ba1SMatthias Ringwald }
612042ff5ba1SMatthias Ringwald 
6121226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
6122665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
6123665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6124665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6125665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6126e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6127e83201bcSMatthias Ringwald             // remove from controller if already present
6128e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6129e83201bcSMatthias Ringwald             continue;
6130e83201bcSMatthias Ringwald         }
613191915b0bSMatthias Ringwald         // directly remove entry from whitelist
6132665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
6133e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
6134e83201bcSMatthias Ringwald     }
6135226db5efSMatthias Ringwald }
6136226db5efSMatthias Ringwald 
6137a3b69fdeSMatthias Ringwald /**
6138a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
6139a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6140a3b69fdeSMatthias Ringwald  */
6141a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
6142a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
6143a3b69fdeSMatthias Ringwald     hci_run();
6144a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6145a3b69fdeSMatthias Ringwald }
6146a3b69fdeSMatthias Ringwald 
6147a3b69fdeSMatthias Ringwald /**
6148a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
6149a3b69fdeSMatthias Ringwald  * @param address_typ
6150a3b69fdeSMatthias Ringwald  * @param address
6151a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6152a3b69fdeSMatthias Ringwald  */
6153667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6154a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
6155a3b69fdeSMatthias Ringwald     if (status){
6156a3b69fdeSMatthias Ringwald         return status;
6157a3b69fdeSMatthias Ringwald     }
6158a3b69fdeSMatthias Ringwald     hci_run();
6159a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6160a3b69fdeSMatthias Ringwald }
6161a3b69fdeSMatthias Ringwald 
6162a3b69fdeSMatthias Ringwald /**
6163a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
6164a3b69fdeSMatthias Ringwald  * @param address_typ
6165a3b69fdeSMatthias Ringwald  * @param address
6166a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6167a3b69fdeSMatthias Ringwald  */
6168667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6169a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
6170a3b69fdeSMatthias Ringwald     if (status){
6171a3b69fdeSMatthias Ringwald         return status;
6172a3b69fdeSMatthias Ringwald     }
6173a3b69fdeSMatthias Ringwald     hci_run();
6174a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6175a3b69fdeSMatthias Ringwald }
6176a3b69fdeSMatthias Ringwald 
6177226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6178226db5efSMatthias Ringwald /**
617995e257d9SMatthias Ringwald  *  @brief Connect with Whitelist
618095e257d9SMatthias Ringwald  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
618195e257d9SMatthias Ringwald  *  @returns - if ok
618295e257d9SMatthias Ringwald  */
618395e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
618495e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
618595e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
618695e257d9SMatthias Ringwald     }
618795e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
618895e257d9SMatthias Ringwald     hci_run();
618995e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
619095e257d9SMatthias Ringwald }
619195e257d9SMatthias Ringwald 
619295e257d9SMatthias Ringwald /**
6193226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
6194226db5efSMatthias Ringwald  * @param address_typ
6195226db5efSMatthias Ringwald  * @param address
6196226db5efSMatthias Ringwald  * @returns 0 if ok
6197226db5efSMatthias Ringwald  */
6198667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
619995e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6200226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
6201226db5efSMatthias Ringwald     }
6202226db5efSMatthias Ringwald 
6203226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
620463f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6205226db5efSMatthias Ringwald         return status;
6206226db5efSMatthias Ringwald     }
6207226db5efSMatthias Ringwald 
6208226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6209226db5efSMatthias Ringwald 
6210226db5efSMatthias Ringwald     hci_run();
621195e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6212226db5efSMatthias Ringwald }
6213226db5efSMatthias Ringwald 
6214226db5efSMatthias Ringwald /**
6215226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
6216226db5efSMatthias Ringwald  * @param address_typ
6217226db5efSMatthias Ringwald  * @param address
6218226db5efSMatthias Ringwald  * @returns 0 if ok
6219226db5efSMatthias Ringwald  */
6220667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
622195e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
622295e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
622395e257d9SMatthias Ringwald     }
622495e257d9SMatthias Ringwald 
6225226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
622695e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
622795e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
622895e257d9SMatthias Ringwald     }
6229226db5efSMatthias Ringwald     hci_run();
6230226db5efSMatthias Ringwald     return 0;
6231226db5efSMatthias Ringwald }
6232226db5efSMatthias Ringwald 
6233226db5efSMatthias Ringwald /**
6234226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
6235226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
6236226db5efSMatthias Ringwald  */
623795e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
623895e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
623995e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
624095e257d9SMatthias Ringwald     }
6241226db5efSMatthias Ringwald     hci_whitelist_clear();
6242226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6243e83201bcSMatthias Ringwald     hci_run();
624495e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6245ac9c45e0SMatthias Ringwald }
6246c9db5c21SMilanka Ringwald 
6247b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6248b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6249c9db5c21SMilanka Ringwald     if (!conn) return 0;
6250c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
6251c9db5c21SMilanka Ringwald }
6252d70217a2SMatthias Ringwald #endif
62534f551432SMatthias Ringwald #endif
62544f551432SMatthias Ringwald 
625535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6256ac9c45e0SMatthias Ringwald /**
6257ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
6258a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6259ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
6260ff00ed1cSMatthias Ringwald  */
6261ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
6262ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
6263ff00ed1cSMatthias Ringwald }
6264ff00ed1cSMatthias Ringwald 
6265ff00ed1cSMatthias Ringwald /**
6266f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
6267f5875de5SMatthias Ringwald  * @param duration in 1.28s units
6268f5875de5SMatthias Ringwald  * @return 0 if ok
6269f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6270f5875de5SMatthias Ringwald  */
6271f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
627299449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6273f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6274a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6275f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6276f5875de5SMatthias Ringwald     }
6277f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
6278f5875de5SMatthias Ringwald     hci_run();
6279f5875de5SMatthias Ringwald     return 0;
6280f5875de5SMatthias Ringwald }
6281f5875de5SMatthias Ringwald 
6282f5875de5SMatthias Ringwald /**
6283f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
6284f5875de5SMatthias Ringwald  * @returns 0 if ok
6285f5875de5SMatthias Ringwald  */
6286f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
6287a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6288f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
6289f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6290f5875de5SMatthias Ringwald         hci_emit_event(event, sizeof(event), 1);
6291f5875de5SMatthias Ringwald         return 0;
6292f5875de5SMatthias Ringwald     }
6293f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6294f5875de5SMatthias Ringwald     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6295f5875de5SMatthias Ringwald     hci_run();
6296f5875de5SMatthias Ringwald     return 0;
6297f5875de5SMatthias Ringwald }
6298f5875de5SMatthias Ringwald 
6299496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
6300496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
6301496bb884SMatthias Ringwald }
6302496bb884SMatthias Ringwald 
6303b7f1ee76SMatthias Ringwald 
6304b7f1ee76SMatthias Ringwald /**
6305b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
6306b7f1ee76SMatthias Ringwald  * @param addr
6307b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
6308b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
6309b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6310b7f1ee76SMatthias Ringwald  */
6311667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6312b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
63136535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6314b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6315b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
6316b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6317b7f1ee76SMatthias Ringwald     hci_run();
6318b7f1ee76SMatthias Ringwald     return 0;
6319b7f1ee76SMatthias Ringwald }
6320b7f1ee76SMatthias Ringwald 
6321667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
63220a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
63236535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
63240a51f88bSMatthias Ringwald     hci_run();
63250a51f88bSMatthias Ringwald     return 0;
63260a51f88bSMatthias Ringwald }
63270a51f88bSMatthias Ringwald 
63280a51f88bSMatthias Ringwald /**
6329aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6330aad97216SMatthias Ringwald  * @param addr
6331aad97216SMatthias Ringwald  * @param pin_data
6332aad97216SMatthias Ringwald  * @param pin_len
6333aad97216SMatthias Ringwald  * @return 0 if ok
6334aad97216SMatthias Ringwald  */
6335667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6336aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6337aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6338aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
6339aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6340aad97216SMatthias Ringwald }
6341aad97216SMatthias Ringwald 
6342aad97216SMatthias Ringwald /**
63430a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
63440a51f88bSMatthias Ringwald  * @param addr
63450a51f88bSMatthias Ringwald  * @param pin
63460a51f88bSMatthias Ringwald  * @return 0 if ok
63470a51f88bSMatthias Ringwald  */
6348667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6349aad97216SMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
63500a51f88bSMatthias Ringwald }
63510a51f88bSMatthias Ringwald 
63520a51f88bSMatthias Ringwald /**
63530a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
63540a51f88bSMatthias Ringwald  * @param addr
63550a51f88bSMatthias Ringwald  * @param pin
63560a51f88bSMatthias Ringwald  * @return 0 if ok
63570a51f88bSMatthias Ringwald  */
63580a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
6359cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
63600a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
63610a51f88bSMatthias Ringwald }
63620a51f88bSMatthias Ringwald 
63630a51f88bSMatthias Ringwald /**
63640a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
63650a51f88bSMatthias Ringwald  * @param addr
63660a51f88bSMatthias Ringwald  * @param passkey
63670a51f88bSMatthias Ringwald  * @return 0 if ok
63680a51f88bSMatthias Ringwald  */
6369667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6370cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6371d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
63720a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
63730a51f88bSMatthias Ringwald }
63740a51f88bSMatthias Ringwald 
63750a51f88bSMatthias Ringwald /**
63760a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
63770a51f88bSMatthias Ringwald  * @param addr
63780a51f88bSMatthias Ringwald  * @param pin
63790a51f88bSMatthias Ringwald  * @return 0 if ok
63800a51f88bSMatthias Ringwald  */
6381667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
6382cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
63830a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
63840a51f88bSMatthias Ringwald }
63850a51f88bSMatthias Ringwald 
63860a51f88bSMatthias Ringwald /**
63870a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
63880a51f88bSMatthias Ringwald  * @param addr
63890a51f88bSMatthias Ringwald  * @param passkey
63900a51f88bSMatthias Ringwald  * @return 0 if ok
63910a51f88bSMatthias Ringwald  */
6392667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
6393cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
63940a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
63950a51f88bSMatthias Ringwald }
63960a51f88bSMatthias Ringwald 
63970a51f88bSMatthias Ringwald /**
63980a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
63990a51f88bSMatthias Ringwald  * @param addr
64000a51f88bSMatthias Ringwald  * @param pin
64010a51f88bSMatthias Ringwald  * @return 0 if ok
64020a51f88bSMatthias Ringwald  */
6403667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
6404cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
64050a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
64060a51f88bSMatthias Ringwald }
64070a51f88bSMatthias Ringwald 
640844565b0cSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
640944565b0cSMatthias Ringwald 
641044565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
641144565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
641244565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
641344565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
641444565b0cSMatthias Ringwald     hci_run();
641544565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
641644565b0cSMatthias Ringwald }
641744565b0cSMatthias Ringwald 
641844565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
64197ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
642044565b0cSMatthias Ringwald }
642144565b0cSMatthias Ringwald 
642244565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
64237ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
642444565b0cSMatthias Ringwald }
642544565b0cSMatthias Ringwald #endif
642644565b0cSMatthias Ringwald 
64271849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
64281849becdSMatthias Ringwald /**
64291849becdSMatthias Ringwald  * @brief Report Remote OOB Data
64301849becdSMatthias Ringwald  * @param bd_addr
64311849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
64321849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
64331849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
64341849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
64351849becdSMatthias Ringwald  */
64361849becdSMatthias Ringwald uint8_t gap_ssp_remote_oob_data(const bd_addr_t addr, const uint8_t * c_192, const uint8_t * r_192, const uint8_t * c_256, const uint8_t * r_256){
64371849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
64381849becdSMatthias Ringwald     if (connection == NULL) {
64391849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
64401849becdSMatthias Ringwald     }
64411849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
64421849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
6443204e8f1dSMatthias Ringwald 
6444204e8f1dSMatthias Ringwald     // ignore P-256 if not supported by us
6445204e8f1dSMatthias Ringwald     if (hci_stack->secure_connections_active){
64461849becdSMatthias Ringwald         connection->classic_oob_c_256 = c_256;
64471849becdSMatthias Ringwald         connection->classic_oob_r_256 = r_256;
6448204e8f1dSMatthias Ringwald     }
6449204e8f1dSMatthias Ringwald 
64501849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
64511849becdSMatthias Ringwald }
6452cf01e888SMatthias Ringwald /**
6453cf01e888SMatthias Ringwald  * @brief Generate new OOB data
6454cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6455cf01e888SMatthias Ringwald  */
6456cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
6457cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
6458cf01e888SMatthias Ringwald     hci_run();
6459cf01e888SMatthias Ringwald }
6460cf01e888SMatthias Ringwald 
64611849becdSMatthias Ringwald #endif
64621849becdSMatthias Ringwald 
6463f5875de5SMatthias Ringwald /**
6464f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6465f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
6466f6858d14SMatthias Ringwald  */
6467b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6468b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
6469f6858d14SMatthias Ringwald }
6470f6858d14SMatthias Ringwald 
6471f6858d14SMatthias Ringwald /**
6472d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6473d950d659SMatthias Ringwald  */
6474d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
6475d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
6476d950d659SMatthias Ringwald }
6477d950d659SMatthias Ringwald 
6478d950d659SMatthias Ringwald /**
6479d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
6480d950d659SMatthias Ringwald  * @return current voice setting
6481d950d659SMatthias Ringwald  */
64820cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
6483d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
6484d950d659SMatthias Ringwald }
6485d950d659SMatthias Ringwald 
6486400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
6487400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
6488400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
6489400ff5abSMatthias Ringwald     if (!transport_name) return 0;
6490400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6491400ff5abSMatthias Ringwald }
6492400ff5abSMatthias Ringwald 
6493b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
6494b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
6495b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
6496b3aad8daSMatthias Ringwald  */
6497b3aad8daSMatthias Ringwald int hci_get_sco_packet_length(void){
6498a3069afeSMatthias Ringwald     int sco_packet_length = 0;
6499cf119f3bSMatthias Ringwald 
65001e20a53eSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
65016f28d2eeSMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
65021431ce27SMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6503cf119f3bSMatthias Ringwald 
6504400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
6505400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
6506cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
650752e46257SMatthias Ringwald         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
650852e46257SMatthias Ringwald         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6509400ff5abSMatthias Ringwald     } else {
6510400ff5abSMatthias Ringwald         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6511400ff5abSMatthias Ringwald         sco_packet_length = 3 + 60 * multiplier;
6512d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
6513d966a453SMatthias Ringwald         if (sco_packet_length > hci_stack->sco_data_packet_length){
6514d966a453SMatthias Ringwald             sco_packet_length = 3 + 60;
6515d966a453SMatthias Ringwald         }
6516400ff5abSMatthias Ringwald     }
6517a3069afeSMatthias Ringwald #endif
65185b7087c7SMatthias Ringwald 
65195b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
65205b7087c7SMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
65211e20a53eSMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
65225b7087c7SMatthias Ringwald     sco_packet_length = 3 + 60 * multiplier;
65235b7087c7SMatthias Ringwald #endif
6524a3069afeSMatthias Ringwald     return sco_packet_length;
6525b3aad8daSMatthias Ringwald }
6526b3aad8daSMatthias Ringwald 
6527c4c88f1bSJakob Krantz /**
6528c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
6529c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
6530c4c88f1bSJakob Krantz */
6531c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
6532c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
6533c4c88f1bSJakob Krantz }
6534c4c88f1bSJakob Krantz 
6535c4c88f1bSJakob Krantz #endif
6536ec111c8bSMatthias Ringwald 
6537ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
6538ec111c8bSMatthias Ringwald     return hci_stack->state;
6539ec111c8bSMatthias Ringwald }
6540ec111c8bSMatthias Ringwald 
654107e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
65425e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
654307e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
654407e010b6SMilanka Ringwald }
654507e010b6SMilanka Ringwald #endif
6546ec111c8bSMatthias Ringwald 
6547d950d659SMatthias Ringwald /**
6548d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
6549d23838ecSMatthias Ringwald  */
6550c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6551d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
6552d23838ecSMatthias Ringwald }
6553d23838ecSMatthias Ringwald 
655471de195eSMatthias Ringwald void hci_disconnect_all(void){
6555665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
6556665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6557665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6558665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
655904a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
656004a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
656104a6ef8cSmatthias.ringwald     }
6562d31fba26S[email protected]     hci_run();
656304a6ef8cSmatthias.ringwald }
656433373e40SMatthias Ringwald 
656533373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
656633373e40SMatthias Ringwald     return hci_stack->manufacturer;
656733373e40SMatthias Ringwald }
65689c6e867eSMatthias Ringwald 
65693e329ddfSandryblack #ifdef ENABLE_BLE
65709c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
65719c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
65729c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
65739c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
65749c6e867eSMatthias Ringwald }
65759c6e867eSMatthias Ringwald 
65769c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
65779c6e867eSMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
65786a79f6baSMatthias Ringwald #endif
65799c6e867eSMatthias Ringwald 
65809c6e867eSMatthias Ringwald int gap_encryption_key_size(hci_con_handle_t con_handle){
6581c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6582c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
6583c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
65846a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
6585c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6586c5fb5ca4SMatthias Ringwald         if (sm_conn->sm_connection_encrypted) {
65879c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
65889c6e867eSMatthias Ringwald         }
65896a79f6baSMatthias Ringwald #endif
65906a79f6baSMatthias Ringwald     } else {
6591c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
65928daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6593c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
6594c5fb5ca4SMatthias Ringwald         }
6595c5fb5ca4SMatthias Ringwald #endif
65966a79f6baSMatthias Ringwald     }
6597c5fb5ca4SMatthias Ringwald     return 0;
6598c5fb5ca4SMatthias Ringwald }
65999c6e867eSMatthias Ringwald 
66009c6e867eSMatthias Ringwald int gap_authenticated(hci_con_handle_t con_handle){
6601c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6602c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
66035f3981bfSMatthias Ringwald 
6604c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
66056a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
66065f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
66075f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6608c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6609c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated;
66106a79f6baSMatthias Ringwald #endif
661159a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
66125f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
6613f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6614c5fb5ca4SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
661559a1a47aSMatthias Ringwald #endif
66165f3981bfSMatthias Ringwald         default:
66175f3981bfSMatthias Ringwald             return 0;
66185f3981bfSMatthias Ringwald     }
66199c6e867eSMatthias Ringwald }
66209c6e867eSMatthias Ringwald 
6621f1dfbe18SMatthias Ringwald int gap_secure_connection(hci_con_handle_t con_handle){
6622c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6623c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
66248b35e16aSMatthias Ringwald 
6625c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
66266a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
66278b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
66288b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6629c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6630c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc;
66316a79f6baSMatthias Ringwald #endif
663259a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
66338b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
6634f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6635c5fb5ca4SMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
663659a1a47aSMatthias Ringwald #endif
66378b35e16aSMatthias Ringwald         default:
66388b35e16aSMatthias Ringwald             return 0;
66398b35e16aSMatthias Ringwald     }
6640f1dfbe18SMatthias Ringwald }
6641f1dfbe18SMatthias Ringwald 
66421e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
66431e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
66441e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
66451e122704SMatthias Ringwald 
664648f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
66471e122704SMatthias Ringwald 	link_key_t link_key;
66481e122704SMatthias Ringwald 	link_key_type_t link_key_type;
664948f33f37SMatthias Ringwald #endif
66501e122704SMatthias Ringwald 	switch (hci_connection->address_type){
66516a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
66521e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
66531e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
66541e122704SMatthias Ringwald 			return hci_connection->sm_connection.sm_le_db_index >= 0;
66556a79f6baSMatthias Ringwald #endif
66561e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
66571e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
66581e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
66591e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
66601e122704SMatthias Ringwald #endif
66611e122704SMatthias Ringwald 		default:
66621e122704SMatthias Ringwald 			return false;
66631e122704SMatthias Ringwald 	}
66641e122704SMatthias Ringwald }
66651e122704SMatthias Ringwald 
66666a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
66679c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
66689c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
66699c6e867eSMatthias Ringwald     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
66709c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
66719c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
66729c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
66739c6e867eSMatthias Ringwald }
66749c6e867eSMatthias Ringwald #endif
6675f8ee3071SMatthias Ringwald 
6676f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
6677f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
6678f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6679f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6680f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
6681f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
6682f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
6683f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
6684f8ee3071SMatthias Ringwald     hci_run();
6685f8ee3071SMatthias Ringwald     return 0;
6686f8ee3071SMatthias Ringwald }
6687f8ee3071SMatthias Ringwald 
6688f8ee3071SMatthias Ringwald /**
6689f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
6690f8ee3071SMatthias Ringwald  * @param con_handle
6691f8ee3071SMatthias Ringwald  @ @return 0 if ok
6692f8ee3071SMatthias Ringwald  */
6693f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6694f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6695f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6696f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
6697f8ee3071SMatthias Ringwald     hci_run();
6698f8ee3071SMatthias Ringwald     return 0;
6699f8ee3071SMatthias Ringwald }
6700bea424a5SMatthias Ringwald 
6701140c0557SMatthias Ringwald uint8_t gap_sniff_subrating_configure(hci_con_handle_t con_handle, uint16_t max_latency, uint16_t min_remote_timeout, uint16_t min_local_timeout){
6702140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6703140c0557SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6704140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
6705140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6706140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6707140c0557SMatthias Ringwald     hci_run();
6708dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6709140c0557SMatthias Ringwald }
6710140c0557SMatthias Ringwald 
6711278ff8a9SMatthias Ringwald uint8_t gap_qos_set(hci_con_handle_t con_handle, hci_service_type_t service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation){
6712278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6713278ff8a9SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6714278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
6715278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
6716278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
6717278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
6718278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
6719278ff8a9SMatthias Ringwald     hci_run();
6720278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6721278ff8a9SMatthias Ringwald }
6722278ff8a9SMatthias Ringwald 
6723bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6724bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
6725bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
6726bea424a5SMatthias Ringwald     hci_run();
6727bea424a5SMatthias Ringwald }
6728bea424a5SMatthias Ringwald 
6729bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6730bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6731bea424a5SMatthias Ringwald     hci_run();
6732bea424a5SMatthias Ringwald }
6733bea424a5SMatthias Ringwald 
6734f8ee3071SMatthias Ringwald #endif
6735beceeddeSMatthias Ringwald 
6736beceeddeSMatthias Ringwald void hci_halting_defer(void){
6737beceeddeSMatthias Ringwald     if (hci_stack->state != HCI_STATE_HALTING) return;
6738beceeddeSMatthias Ringwald     switch (hci_stack->substate){
6739beceeddeSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6740beceeddeSMatthias Ringwald         case HCI_HALTING_CLOSE:
6741beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6742beceeddeSMatthias Ringwald             break;
6743beceeddeSMatthias Ringwald         default:
6744beceeddeSMatthias Ringwald             break;
6745beceeddeSMatthias Ringwald     }
6746beceeddeSMatthias Ringwald }
6747eddac615SMatthias Ringwald 
674821debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
674921debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
675021debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
675121debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
675221debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
675321debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
675402b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
675521debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
675602b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
675702b02cffSMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
675802b02cffSMatthias Ringwald     }
675902b02cffSMatthias Ringwald }
676002b02cffSMatthias Ringwald 
676102b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
676202b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
676302b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
676402b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
676502b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
676602b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
676702b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
676802b02cffSMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
676921debf25SMatthias Ringwald 	}
677021debf25SMatthias Ringwald }
6771cf38a091SMatthias Ringwald 
6772cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
6773cf38a091SMatthias Ringwald 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6774cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6775cf38a091SMatthias Ringwald 	}
6776cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6777cf38a091SMatthias Ringwald 		// restart le resolving list update
6778cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6779cf38a091SMatthias Ringwald 	}
6780cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
6781cf38a091SMatthias Ringwald }
678221debf25SMatthias Ringwald #endif
678321debf25SMatthias Ringwald 
6784eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
678518976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
678618976c74SMatthias Ringwald     hci_connection_t * conn;
678718976c74SMatthias Ringwald 
678818976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
678918976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
679018976c74SMatthias Ringwald 
67917d33cb26SMilanka Ringwald     // setup Controller info
67927d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
67937d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
67947d33cb26SMilanka Ringwald 
679518976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
679618976c74SMatthias Ringwald     addr[5] = 0x01;
679718976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
679818976c74SMatthias Ringwald     conn->con_handle = addr[5];
679918976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
680018976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
68017d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
680218976c74SMatthias Ringwald 
680318976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
680418976c74SMatthias Ringwald     addr[5] = 0x02;
680518976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
680618976c74SMatthias Ringwald     conn->con_handle = addr[5];
680718976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
680818976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
68097d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
681018976c74SMatthias Ringwald 
681118976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
681218976c74SMatthias Ringwald     addr[5] = 0x03;
681318976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
681418976c74SMatthias Ringwald     conn->con_handle = addr[5];
681518976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
681618976c74SMatthias Ringwald     conn->state = OPEN;
68177d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
681818976c74SMatthias Ringwald 
681918976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
682018976c74SMatthias Ringwald     addr[5] = 0x04;
682118976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
682218976c74SMatthias Ringwald     conn->con_handle = addr[5];
682318976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
682418976c74SMatthias Ringwald     conn->state = OPEN;
68257d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
682618976c74SMatthias Ringwald 
682718976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
682818976c74SMatthias Ringwald     addr[5] = 0x05;
682918976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
683018976c74SMatthias Ringwald     conn->con_handle = addr[5];
683118976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
683218976c74SMatthias Ringwald     conn->state = OPEN;
68337d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
68348046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
683518976c74SMatthias Ringwald }
683618976c74SMatthias Ringwald 
6837eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
6838eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
6839eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6840eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6841eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6842eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
6843eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
6844eddac615SMatthias Ringwald     }
6845eddac615SMatthias Ringwald }
68461470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
68471470db0cSMatthias Ringwald     hci_init_done();
68481470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
68491470db0cSMatthias Ringwald }
6850eddac615SMatthias Ringwald #endif
6851