btif_dm.c revision b0daa5d79d4e2950701fb9a5f76a306e1da42de0
1/******************************************************************************
2 *
3 *  Copyright (C) 2009-2012 Broadcom Corporation
4 *
5 *  Licensed under the Apache License, Version 2.0 (the "License");
6 *  you may not use this file except in compliance with the License.
7 *  You may obtain a copy of the License at:
8 *
9 *  http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 *
17 ******************************************************************************/
18
19/************************************************************************************
20 *
21 *  Filename:      btif_dm.c
22 *
23 *  Description:   Contains Device Management (DM) related functionality
24 *
25 *
26 ***********************************************************************************/
27#include <stdio.h>
28#include <stdlib.h>
29#include <unistd.h>
30
31#include <hardware/bluetooth.h>
32
33#include <utils/Log.h>
34#include <cutils/properties.h>
35#include "gki.h"
36#include "btu.h"
37#include "bd.h"
38#include "bta_api.h"
39#include "btif_api.h"
40#include "btif_util.h"
41#include "btif_dm.h"
42#include "btif_storage.h"
43#include "btif_hh.h"
44#include "btif_config.h"
45
46#include "bta_gatt_api.h"
47/******************************************************************************
48**  Constants & Macros
49******************************************************************************/
50
51#define COD_UNCLASSIFIED ((0x1F) << 8)
52#define COD_HID_KEYBOARD                    0x0540
53#define COD_HID_POINTING                    0x0580
54#define COD_HID_COMBO                       0x05C0
55#define COD_HID_MAJOR                       0x0500
56#define COD_AV_HEADSETS                     0x0404
57#define COD_AV_HANDSFREE                    0x0408
58#define COD_AV_HEADPHONES                   0x0418
59#define COD_AV_PORTABLE_AUDIO               0x041C
60#define COD_AV_HIFI_AUDIO                   0x0428
61
62
63#define BTIF_DM_DEFAULT_INQ_MAX_RESULTS     0
64#define BTIF_DM_DEFAULT_INQ_MAX_DURATION    10
65#define BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING 2
66
67#define PROPERTY_PRODUCT_MODEL "ro.product.model"
68#define DEFAULT_LOCAL_NAME_MAX  31
69#if (DEFAULT_LOCAL_NAME_MAX > BTM_MAX_LOC_BD_NAME_LEN)
70    #error "default btif local name size exceeds stack supported length"
71#endif
72
73#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
74#define BTIF_DM_INTERLEAVE_DURATION_BR_ONE    2
75#define BTIF_DM_INTERLEAVE_DURATION_LE_ONE    2
76#define BTIF_DM_INTERLEAVE_DURATION_BR_TWO    3
77#define BTIF_DM_INTERLEAVE_DURATION_LE_TWO    4
78#endif
79
80typedef struct
81{
82    bt_bond_state_t state;
83    BD_ADDR bd_addr;
84    UINT8   is_temp;
85    UINT8   pin_code_len;
86    UINT8   is_ssp;
87    UINT8   auth_req;
88    UINT8   io_cap;
89    UINT8   autopair_attempts;
90    UINT8   is_local_initiated;
91    UINT8   sdp_attempts;
92#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
93    BOOLEAN          is_le_only;
94    btif_dm_ble_cb_t ble;
95#endif
96} btif_dm_pairing_cb_t;
97
98
99typedef struct
100{
101    UINT8       ir[BT_OCTET16_LEN];
102    UINT8       irk[BT_OCTET16_LEN];
103    UINT8       dhk[BT_OCTET16_LEN];
104}btif_dm_local_key_id_t;
105
106typedef struct
107{
108    BOOLEAN                 is_er_rcvd;
109    UINT8                   er[BT_OCTET16_LEN];
110    BOOLEAN                 is_id_keys_rcvd;
111    btif_dm_local_key_id_t  id_keys;  /* ID kyes */
112
113}btif_dm_local_key_cb_t;
114
115typedef struct
116{
117    BD_ADDR bd_addr;
118    BD_NAME bd_name;
119} btif_dm_remote_name_t;
120
121typedef struct
122{
123    BT_OCTET16 sp_c;
124    BT_OCTET16 sp_r;
125    BD_ADDR  oob_bdaddr;  /* peer bdaddr*/
126} btif_dm_oob_cb_t;
127
128typedef struct
129{
130    bt_bdaddr_t  bdaddr;
131    UINT8        transport; /* 0=Unknown, 1=BR/EDR, 2=LE */
132} btif_dm_create_bond_cb_t;
133
134typedef struct
135{
136    uint8_t  status;
137    uint8_t  ctrl_state;
138    uint64_t tx_time;
139    uint64_t rx_time;
140    uint64_t idle_time;
141    uint64_t energy_used;
142} btif_activity_energy_info_cb_t;
143
144#define BTA_SERVICE_ID_TO_SERVICE_MASK(id)       (1 << (id))
145
146/* This flag will be true if HCI_Inquiry is in progress */
147static BOOLEAN btif_dm_inquiry_in_progress = FALSE;
148
149/************************************************************************************
150**  Static variables
151************************************************************************************/
152static char btif_default_local_name[DEFAULT_LOCAL_NAME_MAX+1] = {'\0'};
153
154/******************************************************************************
155**  Static functions
156******************************************************************************/
157static btif_dm_pairing_cb_t pairing_cb;
158static btif_dm_oob_cb_t     oob_cb;
159static void btif_dm_generic_evt(UINT16 event, char* p_param);
160static void btif_dm_cb_create_bond(bt_bdaddr_t *bd_addr, tBTA_TRANSPORT transport);
161static void btif_dm_cb_hid_remote_name(tBTM_REMOTE_DEV_NAME *p_remote_name);
162static void btif_update_remote_properties(BD_ADDR bd_addr, BD_NAME bd_name,
163                                          DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type);
164#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
165static btif_dm_local_key_cb_t ble_local_key_cb;
166static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif);
167static void btif_dm_ble_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl);
168static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ *p_pin_req);
169#endif
170
171static void bte_scan_filt_param_cfg_evt(UINT8 action_type,
172                                           tBTA_DM_BLE_PF_AVBL_SPACE avbl_space,
173                                           tBTA_DM_BLE_REF_VALUE ref_value, tBTA_STATUS status);
174
175static char* btif_get_default_local_name();
176/******************************************************************************
177**  Externs
178******************************************************************************/
179extern UINT16 bta_service_id_to_uuid_lkup_tbl [BTA_MAX_SERVICE_ID];
180extern bt_status_t btif_hf_execute_service(BOOLEAN b_enable);
181extern bt_status_t btif_av_execute_service(BOOLEAN b_enable);
182extern bt_status_t btif_hh_execute_service(BOOLEAN b_enable);
183extern bt_status_t btif_hf_client_execute_service(BOOLEAN b_enable);
184extern bt_status_t btif_mce_execute_service(BOOLEAN b_enable);
185extern int btif_hh_connect(bt_bdaddr_t *bd_addr);
186extern void bta_gatt_convert_uuid16_to_uuid128(UINT8 uuid_128[LEN_UUID_128], UINT16 uuid_16);
187
188
189/******************************************************************************
190**  Functions
191******************************************************************************/
192
193bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id,
194                                                BOOLEAN b_enable)
195{
196    /* Check the service_ID and invoke the profile's BT state changed API */
197    switch (service_id)
198    {
199         case BTA_HFP_SERVICE_ID:
200         case BTA_HSP_SERVICE_ID:
201         {
202              btif_hf_execute_service(b_enable);
203         }break;
204         case BTA_A2DP_SERVICE_ID:
205         {
206              btif_av_execute_service(b_enable);
207         }break;
208         case BTA_HID_SERVICE_ID:
209         {
210              btif_hh_execute_service(b_enable);
211         }break;
212         case BTA_HFP_HS_SERVICE_ID:
213         {
214             btif_hf_client_execute_service(b_enable);
215         }break;
216         case BTA_MAP_SERVICE_ID:
217         {
218             btif_mce_execute_service(b_enable);
219         }break;
220         default:
221              BTIF_TRACE_ERROR("%s: Unknown service being enabled", __FUNCTION__);
222              return BT_STATUS_FAIL;
223    }
224    return BT_STATUS_SUCCESS;
225}
226
227/*******************************************************************************
228**
229** Function         check_eir_remote_name
230**
231** Description      Check if remote name is in the EIR data
232**
233** Returns          TRUE if remote name found
234**                  Populate p_remote_name, if provided and remote name found
235**
236*******************************************************************************/
237static BOOLEAN check_eir_remote_name(tBTA_DM_SEARCH *p_search_data,
238                            UINT8 *p_remote_name, UINT8 *p_remote_name_len)
239{
240    UINT8 *p_eir_remote_name = NULL;
241    UINT8 remote_name_len = 0;
242
243    /* Check EIR for remote name and services */
244    if (p_search_data->inq_res.p_eir)
245    {
246        p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
247                BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
248        if (!p_eir_remote_name)
249        {
250            p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
251                    BTM_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
252        }
253
254        if (p_eir_remote_name)
255        {
256            if (remote_name_len > BD_NAME_LEN)
257                remote_name_len = BD_NAME_LEN;
258
259            if (p_remote_name && p_remote_name_len)
260            {
261                memcpy(p_remote_name, p_eir_remote_name, remote_name_len);
262                *(p_remote_name + remote_name_len) = 0;
263                *p_remote_name_len = remote_name_len;
264            }
265
266            return TRUE;
267        }
268    }
269
270    return FALSE;
271
272}
273
274/*******************************************************************************
275**
276** Function         check_cached_remote_name
277**
278** Description      Check if remote name is in the NVRAM cache
279**
280** Returns          TRUE if remote name found
281**                  Populate p_remote_name, if provided and remote name found
282**
283*******************************************************************************/
284static BOOLEAN check_cached_remote_name(tBTA_DM_SEARCH *p_search_data,
285                                UINT8 *p_remote_name, UINT8 *p_remote_name_len)
286{
287    bt_bdname_t bdname;
288    bt_bdaddr_t remote_bdaddr;
289    bt_property_t prop_name;
290
291    /* check if we already have it in our btif_storage cache */
292    bdcpy(remote_bdaddr.address, p_search_data->inq_res.bd_addr);
293    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
294                               sizeof(bt_bdname_t), &bdname);
295    if (btif_storage_get_remote_device_property(
296        &remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS)
297    {
298        if (p_remote_name && p_remote_name_len)
299        {
300            strcpy((char *)p_remote_name, (char *)bdname.name);
301            *p_remote_name_len = strlen((char *)p_remote_name);
302        }
303        return TRUE;
304    }
305
306    return FALSE;
307}
308
309BOOLEAN check_cod(const bt_bdaddr_t *remote_bdaddr, uint32_t cod)
310{
311    uint32_t    remote_cod;
312    bt_property_t prop_name;
313
314    /* check if we already have it in our btif_storage cache */
315    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE,
316                               sizeof(uint32_t), &remote_cod);
317    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS)
318    {
319        BTIF_TRACE_ERROR("%s: remote_cod = 0x%06x", __FUNCTION__, remote_cod);
320        if ((remote_cod & 0x7ff) == cod)
321            return TRUE;
322    }
323
324    return FALSE;
325}
326
327BOOLEAN check_cod_hid(const bt_bdaddr_t *remote_bdaddr, uint32_t cod)
328{
329    uint32_t    remote_cod;
330    bt_property_t prop_name;
331
332    /* check if we already have it in our btif_storage cache */
333    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE,
334                               sizeof(uint32_t), &remote_cod);
335    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr,
336                                &prop_name) == BT_STATUS_SUCCESS)
337    {
338        BTIF_TRACE_DEBUG("%s: remote_cod = 0x%06x", __FUNCTION__, remote_cod);
339        if ((remote_cod & 0x700) == cod)
340            return TRUE;
341    }
342    return FALSE;
343}
344
345BOOLEAN check_hid_le(const bt_bdaddr_t *remote_bdaddr)
346{
347    uint32_t    remote_dev_type;
348    bt_property_t prop_name;
349
350    /* check if we already have it in our btif_storage cache */
351    BTIF_STORAGE_FILL_PROPERTY(&prop_name,BT_PROPERTY_TYPE_OF_DEVICE,
352                               sizeof(uint32_t), &remote_dev_type);
353    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr,
354                                &prop_name) == BT_STATUS_SUCCESS)
355    {
356        if (remote_dev_type == BT_DEVICE_DEVTYPE_BLE)
357        {
358            bdstr_t bdstr;
359            bd2str(remote_bdaddr, &bdstr);
360            if(btif_config_exist("Remote", bdstr, "HidAppId"))
361                return TRUE;
362        }
363    }
364    return FALSE;
365}
366
367static void bond_state_changed(bt_status_t status, bt_bdaddr_t *bd_addr, bt_bond_state_t state)
368{
369    /* Send bonding state only once - based on outgoing/incoming we may receive duplicates */
370    if ( (pairing_cb.state == state) && (state == BT_BOND_STATE_BONDING) )
371        return;
372
373    if (pairing_cb.is_temp)
374    {
375       state = BT_BOND_STATE_NONE;
376    }
377    BTIF_TRACE_DEBUG("%s: state=%d prev_state=%d", __FUNCTION__, state, pairing_cb.state);
378
379    HAL_CBACK(bt_hal_cbacks, bond_state_changed_cb, status, bd_addr, state);
380
381    if (state == BT_BOND_STATE_BONDING)
382    {
383        pairing_cb.state = state;
384        bdcpy(pairing_cb.bd_addr, bd_addr->address);
385    }
386    else
387    {
388        memset(&pairing_cb, 0, sizeof(pairing_cb));
389    }
390
391}
392
393/* store remote version in bt config to always have access
394   to it post pairing*/
395static void btif_update_remote_version_property(bt_bdaddr_t *p_bd)
396{
397    bt_property_t property;
398    UINT8 lmp_ver = 0;
399    UINT16 lmp_subver = 0;
400    UINT16 mfct_set = 0;
401    tBTM_STATUS btm_status;
402    bt_remote_version_t info;
403    bt_status_t status;
404    bdstr_t bdstr;
405
406    btm_status = BTM_ReadRemoteVersion(*(BD_ADDR*)p_bd, &lmp_ver,
407                          &mfct_set, &lmp_subver);
408
409    ALOGD("remote version info [%s]: %x, %x, %x", bd2str(p_bd, &bdstr),
410               lmp_ver, mfct_set, lmp_subver);
411
412    if (btm_status == BTM_SUCCESS)
413    {
414        /* always update cache to ensure we have availability whenever BTM API
415           is not populated */
416        info.manufacturer = mfct_set;
417        info.sub_ver = lmp_subver;
418        info.version = lmp_ver;
419        BTIF_STORAGE_FILL_PROPERTY(&property,
420                            BT_PROPERTY_REMOTE_VERSION_INFO, sizeof(bt_remote_version_t),
421                            &info);
422        status = btif_storage_set_remote_device_property(p_bd, &property);
423        ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote version", status);
424    }
425}
426
427
428static void btif_update_remote_properties(BD_ADDR bd_addr, BD_NAME bd_name,
429                                          DEV_CLASS dev_class, tBT_DEVICE_TYPE device_type)
430{
431    int num_properties = 0;
432    bt_property_t properties[3];
433    bt_bdaddr_t bdaddr;
434    bt_status_t status;
435    UINT32 cod;
436    bt_device_type_t dev_type;
437
438    memset(properties, 0, sizeof(properties));
439    bdcpy(bdaddr.address, bd_addr);
440
441    /* remote name */
442    if (strlen((const char *) bd_name))
443    {
444        BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
445                            BT_PROPERTY_BDNAME, strlen((char *)bd_name), bd_name);
446        status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
447        ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name", status);
448        num_properties++;
449    }
450
451    /* class of device */
452    cod = devclass2uint(dev_class);
453    BTIF_TRACE_DEBUG("%s():cod is 0x%06x", __FUNCTION__, cod);
454    if ( cod == 0) {
455       /* Try to retrieve cod from storage */
456        BTIF_TRACE_DEBUG("%s():cod is 0, checking cod from storage", __FUNCTION__);
457        BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
458            BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
459        status = btif_storage_get_remote_device_property(&bdaddr, &properties[num_properties]);
460        BTIF_TRACE_DEBUG("%s():cod retreived from storage is 0x%06x", __FUNCTION__, cod);
461        if ( cod == 0) {
462            BTIF_TRACE_DEBUG("%s():cod is again 0, set as unclassified", __FUNCTION__);
463            cod = COD_UNCLASSIFIED;
464        }
465    }
466
467    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
468                        BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
469    status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
470    ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device class", status);
471    num_properties++;
472
473    /* device type */
474    dev_type = device_type;
475    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
476                        BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type);
477    status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
478    ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device type", status);
479    num_properties++;
480
481    HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
482                     status, &bdaddr, num_properties, properties);
483}
484
485/*******************************************************************************
486**
487** Function         btif_dm_cb_hid_remote_name
488**
489** Description      Remote name callback for HID device. Called in btif context
490**                  Special handling for HID devices
491**
492** Returns          void
493**
494*******************************************************************************/
495static void btif_dm_cb_hid_remote_name(tBTM_REMOTE_DEV_NAME *p_remote_name)
496{
497    BTIF_TRACE_DEBUG("%s: status=%d pairing_cb.state=%d", __FUNCTION__, p_remote_name->status, pairing_cb.state);
498    if (pairing_cb.state == BT_BOND_STATE_BONDING)
499    {
500        bt_bdaddr_t remote_bd;
501
502        bdcpy(remote_bd.address, pairing_cb.bd_addr);
503
504        if (p_remote_name->status == BTM_SUCCESS)
505        {
506            bond_state_changed(BT_STATUS_SUCCESS, &remote_bd, BT_BOND_STATE_BONDED);
507        }
508        else
509            bond_state_changed(BT_STATUS_FAIL, &remote_bd, BT_BOND_STATE_NONE);
510    }
511}
512
513/*******************************************************************************
514**
515** Function         btif_dm_cb_create_bond
516**
517** Description      Create bond initiated from the BTIF thread context
518**                  Special handling for HID devices
519**
520** Returns          void
521**
522*******************************************************************************/
523static void btif_dm_cb_create_bond(bt_bdaddr_t *bd_addr, tBTA_TRANSPORT transport)
524{
525    BOOLEAN is_hid = check_cod(bd_addr, COD_HID_POINTING);
526    bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
527
528#if BLE_INCLUDED == TRUE
529    int device_type;
530    int addr_type;
531    bdstr_t bdstr;
532    bd2str(bd_addr, &bdstr);
533    if(btif_config_get_int("Remote", (char const *)&bdstr,"DevType", &device_type) &&
534       (btif_storage_get_remote_addr_type(bd_addr, &addr_type) == BT_STATUS_SUCCESS) &&
535       (device_type == BT_DEVICE_TYPE_BLE))
536    {
537        BTA_DmAddBleDevice(bd_addr->address, addr_type, BT_DEVICE_TYPE_BLE);
538    }
539#endif
540
541#if BLE_INCLUDED == TRUE
542    if(is_hid && device_type != BT_DEVICE_TYPE_BLE)
543#else
544    if(is_hid)
545#endif
546    {
547        int status;
548        status = btif_hh_connect(bd_addr);
549        if(status != BT_STATUS_SUCCESS)
550            bond_state_changed(status, bd_addr, BT_BOND_STATE_NONE);
551    }
552    else
553    {
554        BTA_DmBondByTransport((UINT8 *)bd_addr->address, transport);
555    }
556    /*  Track  originator of bond creation  */
557    pairing_cb.is_local_initiated = TRUE;
558
559}
560
561/*******************************************************************************
562**
563** Function         btif_dm_cb_remove_bond
564**
565** Description      remove bond initiated from the BTIF thread context
566**                  Special handling for HID devices
567**
568** Returns          void
569**
570*******************************************************************************/
571void btif_dm_cb_remove_bond(bt_bdaddr_t *bd_addr)
572{
573     bdstr_t bdstr;
574     /*special handling for HID devices */
575     /*  VUP needs to be sent if its a HID Device. The HID HOST module will check if there
576     is a valid hid connection with this bd_addr. If yes VUP will be issued.*/
577#if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
578    if (btif_hh_virtual_unplug(bd_addr) != BT_STATUS_SUCCESS)
579#endif
580    {
581         BTA_DmRemoveDevice((UINT8 *)bd_addr->address);
582    }
583}
584
585/*******************************************************************************
586**
587** Function         btif_dm_get_connection_state
588**
589** Description      Returns whether the remote device is currently connected
590**
591** Returns          0 if not connected
592**
593*******************************************************************************/
594uint16_t btif_dm_get_connection_state(const bt_bdaddr_t *bd_addr)
595{
596    return BTA_DmGetConnectionState((UINT8 *)bd_addr->address);
597}
598
599/*******************************************************************************
600**
601** Function         search_devices_copy_cb
602**
603** Description      Deep copy callback for search devices event
604**
605** Returns          void
606**
607*******************************************************************************/
608static void search_devices_copy_cb(UINT16 event, char *p_dest, char *p_src)
609{
610    tBTA_DM_SEARCH *p_dest_data =  (tBTA_DM_SEARCH *) p_dest;
611    tBTA_DM_SEARCH *p_src_data =  (tBTA_DM_SEARCH *) p_src;
612
613    if (!p_src)
614        return;
615
616    BTIF_TRACE_DEBUG("%s: event=%s", __FUNCTION__, dump_dm_search_event(event));
617    memcpy(p_dest_data, p_src_data, sizeof(tBTA_DM_SEARCH));
618    switch (event)
619    {
620        case BTA_DM_INQ_RES_EVT:
621        {
622            if (p_src_data->inq_res.p_eir)
623            {
624                p_dest_data->inq_res.p_eir = (UINT8 *)(p_dest + sizeof(tBTA_DM_SEARCH));
625                memcpy(p_dest_data->inq_res.p_eir, p_src_data->inq_res.p_eir, HCI_EXT_INQ_RESPONSE_LEN);
626            }
627        }
628        break;
629
630        case BTA_DM_DISC_RES_EVT:
631        {
632            if (p_src_data->disc_res.raw_data_size && p_src_data->disc_res.p_raw_data)
633            {
634                p_dest_data->disc_res.p_raw_data = (UINT8 *)(p_dest + sizeof(tBTA_DM_SEARCH));
635                memcpy(p_dest_data->disc_res.p_raw_data,
636                    p_src_data->disc_res.p_raw_data, p_src_data->disc_res.raw_data_size);
637            }
638        }
639        break;
640    }
641}
642
643static void search_services_copy_cb(UINT16 event, char *p_dest, char *p_src)
644{
645    tBTA_DM_SEARCH *p_dest_data =  (tBTA_DM_SEARCH *) p_dest;
646    tBTA_DM_SEARCH *p_src_data =  (tBTA_DM_SEARCH *) p_src;
647
648    if (!p_src)
649        return;
650    memcpy(p_dest_data, p_src_data, sizeof(tBTA_DM_SEARCH));
651    switch (event)
652    {
653         case BTA_DM_DISC_RES_EVT:
654         {
655              if (p_src_data->disc_res.result == BTA_SUCCESS)
656              {
657                  if (p_src_data->disc_res.num_uuids > 0)
658                  {
659                       p_dest_data->disc_res.p_uuid_list =
660                                                        (UINT8*)(p_dest + sizeof(tBTA_DM_SEARCH));
661                       memcpy(p_dest_data->disc_res.p_uuid_list, p_src_data->disc_res.p_uuid_list,
662                              p_src_data->disc_res.num_uuids*MAX_UUID_SIZE);
663                       GKI_freebuf(p_src_data->disc_res.p_uuid_list);
664                  }
665                  if (p_src_data->disc_res.p_raw_data != NULL)
666                  {
667                      GKI_freebuf(p_src_data->disc_res.p_raw_data);
668                  }
669              }
670         } break;
671    }
672}
673/******************************************************************************
674**
675**  BTIF DM callback events
676**
677*****************************************************************************/
678
679/*******************************************************************************
680**
681** Function         btif_dm_pin_req_evt
682**
683** Description      Executes pin request event in btif context
684**
685** Returns          void
686**
687*******************************************************************************/
688static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ *p_pin_req)
689{
690    bt_bdaddr_t bd_addr;
691    bt_bdname_t bd_name;
692    UINT32 cod;
693    bt_pin_code_t pin_code;
694
695    /* Remote properties update */
696    btif_update_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name,
697                                  p_pin_req->dev_class, BT_DEVICE_TYPE_BREDR);
698
699    bdcpy(bd_addr.address, p_pin_req->bd_addr);
700    memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
701
702    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
703
704    cod = devclass2uint(p_pin_req->dev_class);
705
706    if ( cod == 0) {
707        BTIF_TRACE_DEBUG("%s():cod is 0, set as unclassified", __FUNCTION__);
708        cod = COD_UNCLASSIFIED;
709    }
710
711    /* check for auto pair possiblity only if bond was initiated by local device */
712    if (pairing_cb.is_local_initiated)
713    {
714        if (check_cod(&bd_addr, COD_AV_HEADSETS) ||
715            check_cod(&bd_addr, COD_AV_HANDSFREE) ||
716            check_cod(&bd_addr, COD_AV_HEADPHONES) ||
717            check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) ||
718            check_cod(&bd_addr, COD_AV_HIFI_AUDIO) ||
719            check_cod(&bd_addr, COD_HID_POINTING))
720        {
721            BTIF_TRACE_DEBUG("%s()cod matches for auto pair", __FUNCTION__);
722            /*  Check if this device can be auto paired  */
723            if ((btif_storage_is_device_autopair_blacklisted(&bd_addr) == FALSE) &&
724                (pairing_cb.autopair_attempts == 0))
725            {
726                BTIF_TRACE_DEBUG("%s() Attempting auto pair", __FUNCTION__);
727                pin_code.pin[0] = 0x30;
728                pin_code.pin[1] = 0x30;
729                pin_code.pin[2] = 0x30;
730                pin_code.pin[3] = 0x30;
731
732                pairing_cb.autopair_attempts++;
733                BTA_DmPinReply( (UINT8*)bd_addr.address, TRUE, 4, pin_code.pin);
734                return;
735            }
736        }
737        else if (check_cod(&bd_addr, COD_HID_KEYBOARD) ||
738                 check_cod(&bd_addr, COD_HID_COMBO))
739        {
740            if(( btif_storage_is_fixed_pin_zeros_keyboard (&bd_addr) == TRUE) &&
741               (pairing_cb.autopair_attempts == 0))
742            {
743                BTIF_TRACE_DEBUG("%s() Attempting auto pair", __FUNCTION__);
744                pin_code.pin[0] = 0x30;
745                pin_code.pin[1] = 0x30;
746                pin_code.pin[2] = 0x30;
747                pin_code.pin[3] = 0x30;
748
749                pairing_cb.autopair_attempts++;
750                BTA_DmPinReply( (UINT8*)bd_addr.address, TRUE, 4, pin_code.pin);
751                return;
752            }
753        }
754    }
755    HAL_CBACK(bt_hal_cbacks, pin_request_cb,
756                     &bd_addr, &bd_name, cod);
757}
758
759/*******************************************************************************
760**
761** Function         btif_dm_ssp_cfm_req_evt
762**
763** Description      Executes SSP confirm request event in btif context
764**
765** Returns          void
766**
767*******************************************************************************/
768static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ *p_ssp_cfm_req)
769{
770    bt_bdaddr_t bd_addr;
771    bt_bdname_t bd_name;
772    UINT32 cod;
773    BOOLEAN is_incoming = !(pairing_cb.state == BT_BOND_STATE_BONDING);
774
775    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
776
777    /* Remote properties update */
778    btif_update_remote_properties(p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->bd_name,
779                                  p_ssp_cfm_req->dev_class, BT_DEVICE_TYPE_BREDR);
780
781    bdcpy(bd_addr.address, p_ssp_cfm_req->bd_addr);
782    memcpy(bd_name.name, p_ssp_cfm_req->bd_name, BD_NAME_LEN);
783
784    /* Set the pairing_cb based on the local & remote authentication requirements */
785    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
786
787    /* if just_works and bonding bit is not set treat this as temporary */
788    if (p_ssp_cfm_req->just_works && !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) &&
789        !(p_ssp_cfm_req->rmt_auth_req & BTM_AUTH_BONDS) &&
790        !(check_cod((bt_bdaddr_t*)&p_ssp_cfm_req->bd_addr, COD_HID_POINTING)))
791        pairing_cb.is_temp = TRUE;
792    else
793        pairing_cb.is_temp = FALSE;
794
795    pairing_cb.is_ssp = TRUE;
796
797    /* If JustWorks auto-accept */
798    if (p_ssp_cfm_req->just_works)
799    {
800        /* Pairing consent for JustWorks needed if:
801         * 1. Incoming pairing is detected AND
802         * 2. local IO capabilities are DisplayYesNo AND
803         * 3. remote IO capabiltiies are DisplayOnly or NoInputNoOutput;
804         */
805        if ((is_incoming) && ((p_ssp_cfm_req->loc_io_caps == 0x01) &&
806                (p_ssp_cfm_req->rmt_io_caps == 0x00 || p_ssp_cfm_req->rmt_io_caps == 0x03)))
807        {
808            BTIF_TRACE_EVENT("%s: User consent needed for incoming pairing request. loc_io_caps: %d, rmt_io_caps: %d",
809                __FUNCTION__, p_ssp_cfm_req->loc_io_caps, p_ssp_cfm_req->rmt_io_caps);
810        }
811        else
812        {
813            BTIF_TRACE_EVENT("%s: Auto-accept JustWorks pairing", __FUNCTION__);
814            btif_dm_ssp_reply(&bd_addr, BT_SSP_VARIANT_CONSENT, TRUE, 0);
815            return;
816        }
817    }
818
819    cod = devclass2uint(p_ssp_cfm_req->dev_class);
820
821    if ( cod == 0) {
822        ALOGD("cod is 0, set as unclassified");
823        cod = COD_UNCLASSIFIED;
824    }
825
826    pairing_cb.sdp_attempts = 0;
827    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name, cod,
828                     (p_ssp_cfm_req->just_works ? BT_SSP_VARIANT_CONSENT : BT_SSP_VARIANT_PASSKEY_CONFIRMATION),
829                     p_ssp_cfm_req->num_val);
830}
831
832static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif)
833{
834    bt_bdaddr_t bd_addr;
835    bt_bdname_t bd_name;
836    UINT32 cod;
837
838    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
839
840    /* Remote properties update */
841    btif_update_remote_properties(p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name,
842                                  p_ssp_key_notif->dev_class, BT_DEVICE_TYPE_BREDR);
843
844    bdcpy(bd_addr.address, p_ssp_key_notif->bd_addr);
845    memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
846
847    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
848    pairing_cb.is_ssp = TRUE;
849    cod = devclass2uint(p_ssp_key_notif->dev_class);
850
851    if ( cod == 0) {
852        ALOGD("cod is 0, set as unclassified");
853        cod = COD_UNCLASSIFIED;
854    }
855
856    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name,
857                     cod, BT_SSP_VARIANT_PASSKEY_NOTIFICATION,
858                     p_ssp_key_notif->passkey);
859}
860/*******************************************************************************
861**
862** Function         btif_dm_auth_cmpl_evt
863**
864** Description      Executes authentication complete event in btif context
865**
866** Returns          void
867**
868*******************************************************************************/
869static void btif_dm_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl)
870{
871    /* Save link key, if not temporary */
872    bt_bdaddr_t bd_addr;
873    bt_status_t status = BT_STATUS_FAIL;
874    bt_bond_state_t state = BT_BOND_STATE_NONE;
875
876    bdcpy(bd_addr.address, p_auth_cmpl->bd_addr);
877    if ( (p_auth_cmpl->success == TRUE) && (p_auth_cmpl->key_present) )
878    {
879        if ((p_auth_cmpl->key_type < HCI_LKEY_TYPE_DEBUG_COMB)  || (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB) ||
880            (p_auth_cmpl->key_type == HCI_LKEY_TYPE_CHANGED_COMB) || (!pairing_cb.is_temp))
881        {
882            bt_status_t ret;
883            BTIF_TRACE_DEBUG("%s: Storing link key. key_type=0x%x, is_temp=%d",
884                __FUNCTION__, p_auth_cmpl->key_type, pairing_cb.is_temp);
885            ret = btif_storage_add_bonded_device(&bd_addr,
886                                p_auth_cmpl->key, p_auth_cmpl->key_type,
887                                pairing_cb.pin_code_len);
888            ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret);
889        }
890        else
891        {
892            BTIF_TRACE_DEBUG("%s: Temporary key. Not storing. key_type=0x%x, is_temp=%d",
893                __FUNCTION__, p_auth_cmpl->key_type, pairing_cb.is_temp);
894            if(pairing_cb.is_temp)
895            {
896                BTIF_TRACE_DEBUG("%s: sending BT_BOND_STATE_NONE for Temp pairing",
897                        __FUNCTION__);
898                bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_NONE);
899                return;
900            }
901        }
902    }
903    if (p_auth_cmpl->success)
904    {
905        status = BT_STATUS_SUCCESS;
906        state = BT_BOND_STATE_BONDED;
907
908        /* Trigger SDP on the device */
909        pairing_cb.sdp_attempts = 1;;
910
911        if(btif_dm_inquiry_in_progress)
912            btif_dm_cancel_discovery();
913
914        btif_dm_get_remote_services(&bd_addr);
915        /* Do not call bond_state_changed_cb yet. Wait till fetch remote service is complete */
916    }
917    else
918    {
919         /*Map the HCI fail reason  to  bt status  */
920        switch(p_auth_cmpl->fail_reason)
921        {
922            case HCI_ERR_PAGE_TIMEOUT:
923            case HCI_ERR_CONNECTION_TOUT:
924                status =  BT_STATUS_RMT_DEV_DOWN;
925                break;
926
927            case HCI_ERR_PAIRING_NOT_ALLOWED:
928                status = BT_STATUS_AUTH_REJECTED;
929                break;
930
931            case HCI_ERR_LMP_RESPONSE_TIMEOUT:
932                status =  BT_STATUS_AUTH_FAILURE;
933                break;
934
935            /* map the auth failure codes, so we can retry pairing if necessary */
936            case HCI_ERR_AUTH_FAILURE:
937            case HCI_ERR_KEY_MISSING:
938                btif_storage_remove_bonded_device(&bd_addr);
939            case HCI_ERR_HOST_REJECT_SECURITY:
940            case HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE:
941            case HCI_ERR_UNIT_KEY_USED:
942            case HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED:
943            case HCI_ERR_INSUFFCIENT_SECURITY:
944            case HCI_ERR_PEER_USER:
945            case HCI_ERR_UNSPECIFIED:
946                BTIF_TRACE_DEBUG(" %s() Authentication fail reason %d",
947                    __FUNCTION__, p_auth_cmpl->fail_reason);
948                if (pairing_cb.autopair_attempts  == 1)
949                {
950                    BTIF_TRACE_DEBUG("%s(): Adding device to blacklist ", __FUNCTION__);
951
952                    /* Add the device to dynamic black list only if this device belongs to Audio/pointing dev class  */
953                    if (check_cod(&bd_addr, COD_AV_HEADSETS) ||
954                        check_cod(&bd_addr, COD_AV_HANDSFREE) ||
955                        check_cod(&bd_addr, COD_AV_HEADPHONES) ||
956                        check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) ||
957                        check_cod(&bd_addr, COD_AV_HIFI_AUDIO) ||
958                        check_cod(&bd_addr, COD_HID_POINTING))
959                    {
960                        btif_storage_add_device_to_autopair_blacklist (&bd_addr);
961                    }
962                    pairing_cb.autopair_attempts++;
963
964                    /* Create the Bond once again */
965                    BTIF_TRACE_DEBUG("%s() auto pair failed. Reinitiate Bond", __FUNCTION__);
966                    btif_dm_cb_create_bond (&bd_addr, BTA_TRANSPORT_UNKNOWN);
967                    return;
968                }
969                else
970                {
971                    /* if autopair attempts are more than 1, or not attempted */
972                    status =  BT_STATUS_AUTH_FAILURE;
973                }
974                break;
975
976            default:
977                status =  BT_STATUS_FAIL;
978        }
979        /* Special Handling for HID Devices */
980        if (check_cod(&bd_addr, COD_HID_POINTING)) {
981            /* Remove Device as bonded in nvram as authentication failed */
982            BTIF_TRACE_DEBUG("%s(): removing hid pointing device from nvram", __FUNCTION__);
983            btif_storage_remove_bonded_device(&bd_addr);
984        }
985        bond_state_changed(status, &bd_addr, state);
986    }
987}
988
989/******************************************************************************
990**
991** Function         btif_dm_search_devices_evt
992**
993** Description      Executes search devices callback events in btif context
994**
995** Returns          void
996**
997******************************************************************************/
998static void btif_dm_search_devices_evt (UINT16 event, char *p_param)
999{
1000    tBTA_DM_SEARCH *p_search_data;
1001    BTIF_TRACE_EVENT("%s event=%s", __FUNCTION__, dump_dm_search_event(event));
1002
1003    switch (event)
1004    {
1005        case BTA_DM_DISC_RES_EVT:
1006        {
1007            p_search_data = (tBTA_DM_SEARCH *)p_param;
1008            /* Remote name update */
1009            if (strlen((const char *) p_search_data->disc_res.bd_name))
1010            {
1011                bt_property_t properties[1];
1012                bt_bdaddr_t bdaddr;
1013                bt_status_t status;
1014
1015                properties[0].type = BT_PROPERTY_BDNAME;
1016                properties[0].val = p_search_data->disc_res.bd_name;
1017                properties[0].len = strlen((char *)p_search_data->disc_res.bd_name);
1018                bdcpy(bdaddr.address, p_search_data->disc_res.bd_addr);
1019
1020                status = btif_storage_set_remote_device_property(&bdaddr, &properties[0]);
1021                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device property", status);
1022                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1023                                 status, &bdaddr, 1, properties);
1024            }
1025            /* TODO: Services? */
1026        }
1027        break;
1028
1029        case BTA_DM_INQ_RES_EVT:
1030        {
1031            /* inquiry result */
1032            UINT32 cod;
1033            UINT8 *p_eir_remote_name = NULL;
1034            bt_bdname_t bdname;
1035            bt_bdaddr_t bdaddr;
1036            UINT8 remote_name_len;
1037            UINT8 *p_cached_name = NULL;
1038            tBTA_SERVICE_MASK services = 0;
1039            bdstr_t bdstr;
1040
1041            p_search_data = (tBTA_DM_SEARCH *)p_param;
1042            bdcpy(bdaddr.address, p_search_data->inq_res.bd_addr);
1043
1044            BTIF_TRACE_DEBUG("%s() %s device_type = 0x%x\n", __FUNCTION__, bd2str(&bdaddr, &bdstr),
1045#if (BLE_INCLUDED == TRUE)
1046                    p_search_data->inq_res.device_type);
1047#else
1048                    BT_DEVICE_TYPE_BREDR);
1049#endif
1050            bdname.name[0] = 0;
1051
1052            cod = devclass2uint (p_search_data->inq_res.dev_class);
1053
1054            if ( cod == 0) {
1055                ALOGD("cod is 0, set as unclassified");
1056                cod = COD_UNCLASSIFIED;
1057            }
1058
1059            if (!check_eir_remote_name(p_search_data, bdname.name, &remote_name_len))
1060                check_cached_remote_name(p_search_data, bdname.name, &remote_name_len);
1061
1062            /* Check EIR for remote name and services */
1063            if (p_search_data->inq_res.p_eir)
1064            {
1065                BTA_GetEirService(p_search_data->inq_res.p_eir, &services);
1066                BTIF_TRACE_DEBUG("%s()EIR BTA services = %08X", __FUNCTION__, (UINT32)services);
1067                /* TODO:  Get the service list and check to see which uuids we got and send it back to the client. */
1068            }
1069
1070
1071            {
1072                bt_property_t properties[5];
1073                bt_device_type_t dev_type;
1074                UINT8 addr_type;
1075                uint32_t num_properties = 0;
1076                bt_status_t status;
1077
1078                memset(properties, 0, sizeof(properties));
1079                /* BD_ADDR */
1080                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1081                                    BT_PROPERTY_BDADDR, sizeof(bdaddr), &bdaddr);
1082                num_properties++;
1083                /* BD_NAME */
1084                /* Don't send BDNAME if it is empty */
1085                if (bdname.name[0])
1086                {
1087                    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1088                                               BT_PROPERTY_BDNAME,
1089                                               strlen((char *)bdname.name), &bdname);
1090                    num_properties++;
1091                }
1092
1093                /* DEV_CLASS */
1094                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1095                                    BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
1096                num_properties++;
1097                /* DEV_TYPE */
1098#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1099                /* FixMe: Assumption is that bluetooth.h and BTE enums match */
1100                dev_type = p_search_data->inq_res.device_type;
1101                addr_type = p_search_data->inq_res.ble_addr_type;
1102#else
1103                dev_type = BT_DEVICE_TYPE_BREDR;
1104#endif
1105                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1106                                    BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type);
1107                num_properties++;
1108                /* RSSI */
1109                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1110                                    BT_PROPERTY_REMOTE_RSSI, sizeof(int8_t),
1111                                    &(p_search_data->inq_res.rssi));
1112                num_properties++;
1113
1114                status = btif_storage_add_remote_device(&bdaddr, num_properties, properties);
1115                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device (inquiry)", status);
1116#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1117                status = btif_storage_set_remote_addr_type(&bdaddr, addr_type);
1118                if (( dev_type == BT_DEVICE_TYPE_DUMO)&&
1119                   (p_search_data->inq_res.flag & BTA_BLE_DMT_CONTROLLER_SPT) &&
1120                   (p_search_data->inq_res.flag & BTA_BLE_DMT_HOST_SPT))
1121                 {
1122                    btif_storage_set_dmt_support_type (&bdaddr, TRUE);
1123                 }
1124                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote addr type (inquiry)", status);
1125#endif
1126                /* Callback to notify upper layer of device */
1127                HAL_CBACK(bt_hal_cbacks, device_found_cb,
1128                                 num_properties, properties);
1129            }
1130        }
1131        break;
1132
1133        case BTA_DM_INQ_CMPL_EVT:
1134        {
1135#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1136            tBTA_DM_BLE_PF_FILT_PARAMS adv_filt_param;
1137            memset(&adv_filt_param, 0, sizeof(tBTA_DM_BLE_PF_FILT_PARAMS));
1138            BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_DELETE, 0, &adv_filt_param, NULL,
1139                                     bte_scan_filt_param_cfg_evt, 0);
1140#endif
1141        }
1142        break;
1143        case BTA_DM_DISC_CMPL_EVT:
1144        {
1145            HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STOPPED);
1146        }
1147        break;
1148        case BTA_DM_SEARCH_CANCEL_CMPL_EVT:
1149        {
1150           /* if inquiry is not in progress and we get a cancel event, then
1151            * it means we are done with inquiry, but remote_name fetches are in
1152            * progress
1153            *
1154            * if inquiry  is in progress, then we don't want to act on this cancel_cmpl_evt
1155            * but instead wait for the cancel_cmpl_evt via the Busy Level
1156            *
1157            */
1158           if (btif_dm_inquiry_in_progress == FALSE)
1159           {
1160               HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STOPPED);
1161           }
1162        }
1163        break;
1164    }
1165}
1166
1167/*******************************************************************************
1168**
1169** Function         btif_dm_search_services_evt
1170**
1171** Description      Executes search services event in btif context
1172**
1173** Returns          void
1174**
1175*******************************************************************************/
1176static void btif_dm_search_services_evt(UINT16 event, char *p_param)
1177{
1178    tBTA_DM_SEARCH *p_data = (tBTA_DM_SEARCH*)p_param;
1179
1180    BTIF_TRACE_EVENT("%s:  event = %d", __FUNCTION__, event);
1181    switch (event)
1182    {
1183        case BTA_DM_DISC_RES_EVT:
1184        {
1185            bt_uuid_t uuid_arr[BT_MAX_NUM_UUIDS]; /* Max 32 services */
1186            bt_property_t prop;
1187            uint32_t i = 0,  j = 0;
1188            bt_bdaddr_t bd_addr;
1189            bt_status_t ret;
1190
1191            bdcpy(bd_addr.address, p_data->disc_res.bd_addr);
1192
1193            BTIF_TRACE_DEBUG("%s:(result=0x%x, services 0x%x)", __FUNCTION__,
1194                    p_data->disc_res.result, p_data->disc_res.services);
1195            if  ((p_data->disc_res.result != BTA_SUCCESS) &&
1196                 (pairing_cb.state == BT_BOND_STATE_BONDING ) &&
1197                 (pairing_cb.sdp_attempts < BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING))
1198            {
1199                BTIF_TRACE_WARNING("%s:SDP failed after bonding re-attempting", __FUNCTION__);
1200                pairing_cb.sdp_attempts++;
1201                btif_dm_get_remote_services(&bd_addr);
1202                return;
1203            }
1204            prop.type = BT_PROPERTY_UUIDS;
1205            prop.len = 0;
1206            if ((p_data->disc_res.result == BTA_SUCCESS) && (p_data->disc_res.num_uuids > 0))
1207            {
1208                 prop.val = p_data->disc_res.p_uuid_list;
1209                 prop.len = p_data->disc_res.num_uuids * MAX_UUID_SIZE;
1210                 for (i=0; i < p_data->disc_res.num_uuids; i++)
1211                 {
1212                      char temp[256];
1213                      uuid_to_string((bt_uuid_t*)(p_data->disc_res.p_uuid_list + (i*MAX_UUID_SIZE)), temp);
1214                      BTIF_TRACE_ERROR("Index: %d uuid:%s", i, temp);
1215                 }
1216            }
1217
1218            /* onUuidChanged requires getBondedDevices to be populated.
1219            ** bond_state_changed needs to be sent prior to remote_device_property
1220            */
1221            if ((pairing_cb.state == BT_BOND_STATE_BONDING) &&
1222                (bdcmp(p_data->disc_res.bd_addr, pairing_cb.bd_addr) == 0)&&
1223                pairing_cb.sdp_attempts > 0)
1224            {
1225                 BTIF_TRACE_DEBUG("%s Remote Service SDP done. Call bond_state_changed_cb BONDED",
1226                                   __FUNCTION__);
1227                 pairing_cb.sdp_attempts  = 0;
1228                 bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDED);
1229            }
1230
1231            if(p_data->disc_res.num_uuids != 0)
1232            {
1233                /* Also write this to the NVRAM */
1234                ret = btif_storage_set_remote_device_property(&bd_addr, &prop);
1235                ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1236                /* Send the event to the BTIF */
1237                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1238                                 BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1239            }
1240        }
1241        break;
1242
1243        case BTA_DM_DISC_CMPL_EVT:
1244            /* fixme */
1245        break;
1246
1247#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1248        case BTA_DM_DISC_BLE_RES_EVT:
1249             BTIF_TRACE_DEBUG("%s:, services 0x%x)", __FUNCTION__,
1250                                p_data->disc_ble_res.service.uu.uuid16);
1251             bt_uuid_t  uuid;
1252             int i = 0;
1253             int j = 15;
1254             if (p_data->disc_ble_res.service.uu.uuid16 == UUID_SERVCLASS_LE_HID)
1255             {
1256                BTIF_TRACE_DEBUG("%s: Found HOGP UUID",__FUNCTION__);
1257                bt_property_t prop;
1258                bt_bdaddr_t bd_addr;
1259                char temp[256];
1260                bt_status_t ret;
1261
1262                bta_gatt_convert_uuid16_to_uuid128(uuid.uu,p_data->disc_ble_res.service.uu.uuid16);
1263
1264                while(i < j )
1265                {
1266                    unsigned char c = uuid.uu[j];
1267                    uuid.uu[j] = uuid.uu[i];
1268                    uuid.uu[i] = c;
1269                    i++;
1270                    j--;
1271                }
1272
1273                uuid_to_string(&uuid, temp);
1274                BTIF_TRACE_ERROR(" uuid:%s", temp);
1275
1276                bdcpy(bd_addr.address, p_data->disc_ble_res.bd_addr);
1277                prop.type = BT_PROPERTY_UUIDS;
1278                prop.val = uuid.uu;
1279                prop.len = MAX_UUID_SIZE;
1280
1281                /* Also write this to the NVRAM */
1282                ret = btif_storage_set_remote_device_property(&bd_addr, &prop);
1283                ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1284
1285                /* Send the event to the BTIF */
1286                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1287                                 BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1288
1289            }
1290        break;
1291#endif /* BLE_INCLUDED */
1292
1293        default:
1294        {
1295            ASSERTC(0, "unhandled search services event", event);
1296        }
1297        break;
1298    }
1299}
1300
1301/*******************************************************************************
1302**
1303** Function         btif_dm_remote_service_record_evt
1304**
1305** Description      Executes search service record event in btif context
1306**
1307** Returns          void
1308**
1309*******************************************************************************/
1310static void btif_dm_remote_service_record_evt(UINT16 event, char *p_param)
1311{
1312    tBTA_DM_SEARCH *p_data = (tBTA_DM_SEARCH*)p_param;
1313
1314    BTIF_TRACE_EVENT("%s:  event = %d", __FUNCTION__, event);
1315    switch (event)
1316    {
1317        case BTA_DM_DISC_RES_EVT:
1318        {
1319            bt_service_record_t rec;
1320            bt_property_t prop;
1321            uint32_t i = 0;
1322            bt_bdaddr_t bd_addr;
1323
1324            memset(&rec, 0, sizeof(bt_service_record_t));
1325            bdcpy(bd_addr.address, p_data->disc_res.bd_addr);
1326
1327            BTIF_TRACE_DEBUG("%s:(result=0x%x, services 0x%x)", __FUNCTION__,
1328                    p_data->disc_res.result, p_data->disc_res.services);
1329            prop.type = BT_PROPERTY_SERVICE_RECORD;
1330            prop.val = (void*)&rec;
1331            prop.len = sizeof(rec);
1332
1333            /* disc_res.result is overloaded with SCN. Cannot check result */
1334            p_data->disc_res.services &= ~BTA_USER_SERVICE_MASK;
1335            /* TODO: Get the UUID as well */
1336            rec.channel = p_data->disc_res.result - 3;
1337            /* TODO: Need to get the service name using p_raw_data */
1338            rec.name[0] = 0;
1339
1340            HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1341                             BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1342        }
1343        break;
1344
1345        default:
1346        {
1347           ASSERTC(0, "unhandled remote service record event", event);
1348        }
1349        break;
1350    }
1351}
1352
1353/*******************************************************************************
1354**
1355** Function         btif_dm_upstreams_cback
1356**
1357** Description      Executes UPSTREAMS events in btif context
1358**
1359** Returns          void
1360**
1361*******************************************************************************/
1362static void btif_dm_upstreams_evt(UINT16 event, char* p_param)
1363{
1364    tBTA_DM_SEC_EVT dm_event = (tBTA_DM_SEC_EVT)event;
1365    tBTA_DM_SEC *p_data = (tBTA_DM_SEC*)p_param;
1366    tBTA_SERVICE_MASK service_mask;
1367    uint32_t i;
1368    bt_bdaddr_t bd_addr;
1369
1370    BTIF_TRACE_EVENT("btif_dm_upstreams_cback  ev: %s", dump_dm_event(event));
1371
1372    switch (event)
1373    {
1374        case BTA_DM_ENABLE_EVT:
1375        {
1376             BD_NAME bdname;
1377             bt_status_t status;
1378             bt_property_t prop;
1379             prop.type = BT_PROPERTY_BDNAME;
1380             prop.len = BD_NAME_LEN;
1381             prop.val = (void*)bdname;
1382
1383             status = btif_storage_get_adapter_property(&prop);
1384             if (status == BT_STATUS_SUCCESS)
1385             {
1386                 /* A name exists in the storage. Make this the device name */
1387                 BTA_DmSetDeviceName((char*)prop.val);
1388             }
1389             else
1390             {
1391                 /* Storage does not have a name yet.
1392                  * Use the default name and write it to the chip
1393                  */
1394                 BTA_DmSetDeviceName(btif_get_default_local_name());
1395             }
1396
1397             /* for each of the enabled services in the mask, trigger the profile
1398              * enable */
1399             service_mask = btif_get_enabled_services_mask();
1400             for (i=0; i <= BTA_MAX_SERVICE_ID; i++)
1401             {
1402                 if (service_mask &
1403                     (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i)))
1404                 {
1405                     btif_in_execute_service_request(i, TRUE);
1406                 }
1407             }
1408             /* clear control blocks */
1409             memset(&pairing_cb, 0, sizeof(btif_dm_pairing_cb_t));
1410
1411             /* This function will also trigger the adapter_properties_cb
1412             ** and bonded_devices_info_cb
1413             */
1414             btif_storage_load_bonded_devices();
1415
1416             btif_storage_load_autopair_device_list();
1417
1418             btif_enable_bluetooth_evt(p_data->enable.status, p_data->enable.bd_addr);
1419
1420             #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1421             /* Enable local privacy */
1422             /*TODO  Should this call be exposed to JAVA...? */
1423             BTA_DmBleConfigLocalPrivacy(TRUE);
1424             #endif
1425        }
1426        break;
1427
1428        case BTA_DM_DISABLE_EVT:
1429            /* for each of the enabled services in the mask, trigger the profile
1430             * disable */
1431            service_mask = btif_get_enabled_services_mask();
1432            for (i=0; i <= BTA_MAX_SERVICE_ID; i++)
1433            {
1434                if (service_mask &
1435                    (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i)))
1436                {
1437                    btif_in_execute_service_request(i, FALSE);
1438                }
1439            }
1440            btif_disable_bluetooth_evt();
1441            break;
1442
1443        case BTA_DM_PIN_REQ_EVT:
1444            btif_dm_pin_req_evt(&p_data->pin_req);
1445            break;
1446
1447        case BTA_DM_AUTH_CMPL_EVT:
1448            btif_dm_auth_cmpl_evt(&p_data->auth_cmpl);
1449            break;
1450
1451        case BTA_DM_BOND_CANCEL_CMPL_EVT:
1452            if (pairing_cb.state == BT_BOND_STATE_BONDING)
1453            {
1454                bdcpy(bd_addr.address, pairing_cb.bd_addr);
1455                bond_state_changed(p_data->bond_cancel_cmpl.result, &bd_addr, BT_BOND_STATE_NONE);
1456            }
1457            break;
1458
1459        case BTA_DM_SP_CFM_REQ_EVT:
1460            btif_dm_ssp_cfm_req_evt(&p_data->cfm_req);
1461            break;
1462        case BTA_DM_SP_KEY_NOTIF_EVT:
1463            btif_dm_ssp_key_notif_evt(&p_data->key_notif);
1464            break;
1465
1466        case BTA_DM_DEV_UNPAIRED_EVT:
1467            bdcpy(bd_addr.address, p_data->link_down.bd_addr);
1468
1469            /*special handling for HID devices */
1470            #if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
1471            btif_hh_remove_device(bd_addr);
1472            #endif
1473            #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1474            btif_storage_remove_ble_bonding_keys(&bd_addr);
1475            #endif
1476            btif_storage_remove_bonded_device(&bd_addr);
1477            bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_NONE);
1478            break;
1479
1480        case BTA_DM_BUSY_LEVEL_EVT:
1481        {
1482
1483            if (p_data->busy_level.level_flags & BTM_BL_INQUIRY_PAGING_MASK)
1484            {
1485                if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_STARTED)
1486                {
1487                       HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb,
1488                                                BT_DISCOVERY_STARTED);
1489                       btif_dm_inquiry_in_progress = TRUE;
1490                }
1491                else if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_CANCELLED)
1492                {
1493                       HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb,
1494                                                BT_DISCOVERY_STOPPED);
1495                       btif_dm_inquiry_in_progress = FALSE;
1496                }
1497                else if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_COMPLETE)
1498                {
1499                       btif_dm_inquiry_in_progress = FALSE;
1500                }
1501            }
1502        }break;
1503
1504        case BTA_DM_LINK_UP_EVT:
1505            bdcpy(bd_addr.address, p_data->link_up.bd_addr);
1506            BTIF_TRACE_DEBUG("BTA_DM_LINK_UP_EVT. Sending BT_ACL_STATE_CONNECTED");
1507
1508            btif_update_remote_version_property(&bd_addr);
1509
1510            HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, BT_STATUS_SUCCESS,
1511                      &bd_addr, BT_ACL_STATE_CONNECTED);
1512            break;
1513
1514        case BTA_DM_LINK_DOWN_EVT:
1515            bdcpy(bd_addr.address, p_data->link_down.bd_addr);
1516            BTIF_TRACE_DEBUG("BTA_DM_LINK_DOWN_EVT. Sending BT_ACL_STATE_DISCONNECTED");
1517            HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, BT_STATUS_SUCCESS,
1518                      &bd_addr, BT_ACL_STATE_DISCONNECTED);
1519            break;
1520
1521        case BTA_DM_HW_ERROR_EVT:
1522            BTIF_TRACE_ERROR("Received H/W Error. ");
1523            /* Flush storage data */
1524            btif_config_flush();
1525            usleep(100000); /* 100milliseconds */
1526            /* Killing the process to force a restart as part of fault tolerance */
1527            kill(getpid(), SIGKILL);
1528            break;
1529
1530#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1531        case BTA_DM_BLE_KEY_EVT:
1532            BTIF_TRACE_DEBUG("BTA_DM_BLE_KEY_EVT key_type=0x%02x ", p_data->ble_key.key_type);
1533
1534            /* If this pairing is by-product of local initiated GATT client Read or Write,
1535            BTA would not have sent BTA_DM_BLE_SEC_REQ_EVT event and Bond state would not
1536            have setup properly. Setup pairing_cb and notify App about Bonding state now*/
1537            if (pairing_cb.state != BT_BOND_STATE_BONDING)
1538            {
1539                BTIF_TRACE_DEBUG("Bond state not sent to App so far.Notify the app now");
1540                bond_state_changed(BT_STATUS_SUCCESS, (bt_bdaddr_t*)p_data->ble_key.bd_addr,
1541                                   BT_BOND_STATE_BONDING);
1542            }
1543            else if (memcmp (pairing_cb.bd_addr, p_data->ble_key.bd_addr, BD_ADDR_LEN)!=0)
1544            {
1545                BTIF_TRACE_ERROR("BD mismatch discard BLE key_type=%d ",p_data->ble_key.key_type);
1546                break;
1547            }
1548
1549            switch (p_data->ble_key.key_type)
1550            {
1551                case BTA_LE_KEY_PENC:
1552                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PENC");
1553                    pairing_cb.ble.is_penc_key_rcvd = TRUE;
1554                    memcpy(pairing_cb.ble.penc_key.ltk,p_data->ble_key.key_value.penc_key.ltk, 16);
1555                    memcpy(pairing_cb.ble.penc_key.rand, p_data->ble_key.key_value.penc_key.rand,8);
1556                    pairing_cb.ble.penc_key.ediv = p_data->ble_key.key_value.penc_key.ediv;
1557                    pairing_cb.ble.penc_key.sec_level = p_data->ble_key.key_value.penc_key.sec_level;
1558
1559                    for (i=0; i<16; i++)
1560                    {
1561                        BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.ltk[%d]=0x%02x",i,pairing_cb.ble.penc_key.ltk[i]);
1562                    }
1563                    for (i=0; i<8; i++)
1564                    {
1565                        BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.rand[%d]=0x%02x",i,pairing_cb.ble.penc_key.rand[i]);
1566                    }
1567                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.ediv=0x%04x",pairing_cb.ble.penc_key.ediv);
1568                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.sec_level=0x%02x",pairing_cb.ble.penc_key.sec_level);
1569                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.key_size=0x%02x",pairing_cb.ble.penc_key.key_size);
1570                    break;
1571
1572                case BTA_LE_KEY_PID:
1573                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PID");
1574                    pairing_cb.ble.is_pid_key_rcvd = TRUE;
1575                    memcpy(pairing_cb.ble.pid_key, p_data->ble_key.key_value.pid_key.irk, 16);
1576                    for (i=0; i<16; i++)
1577                    {
1578                        BTIF_TRACE_DEBUG("pairing_cb.ble.pid_key[%d]=0x%02x",i,pairing_cb.ble.pid_key[i]);
1579                    }
1580                    break;
1581
1582                case BTA_LE_KEY_PCSRK:
1583                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PCSRK");
1584                    pairing_cb.ble.is_pcsrk_key_rcvd = TRUE;
1585                    pairing_cb.ble.pcsrk_key.counter = p_data->ble_key.key_value.pcsrk_key.counter;
1586                    pairing_cb.ble.pcsrk_key.sec_level = p_data->ble_key.key_value.pcsrk_key.sec_level;
1587                    memcpy(pairing_cb.ble.pcsrk_key.csrk,p_data->ble_key.key_value.pcsrk_key.csrk,16);
1588
1589                    for (i=0; i<16; i++)
1590                    {
1591                        BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.csrk[%d]=0x%02x",i,pairing_cb.ble.pcsrk_key.csrk[i]);
1592                    }
1593                    BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.counter=0x%08x",pairing_cb.ble.pcsrk_key.counter);
1594                    BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.sec_level=0x%02x",pairing_cb.ble.pcsrk_key.sec_level);
1595                    break;
1596
1597                case BTA_LE_KEY_LENC:
1598                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_LENC");
1599                    pairing_cb.ble.is_lenc_key_rcvd = TRUE;
1600                    pairing_cb.ble.lenc_key.div = p_data->ble_key.key_value.lenc_key.div;
1601                    pairing_cb.ble.lenc_key.key_size = p_data->ble_key.key_value.lenc_key.key_size;
1602                    pairing_cb.ble.lenc_key.sec_level = p_data->ble_key.key_value.lenc_key.sec_level;
1603
1604                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.div=0x%04x",pairing_cb.ble.lenc_key.div);
1605                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.key_size=0x%02x",pairing_cb.ble.lenc_key.key_size);
1606                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.sec_level=0x%02x",pairing_cb.ble.lenc_key.sec_level);
1607                    break;
1608
1609
1610
1611                case BTA_LE_KEY_LCSRK:
1612                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_LCSRK");
1613                    pairing_cb.ble.is_lcsrk_key_rcvd = TRUE;
1614                    pairing_cb.ble.lcsrk_key.counter = p_data->ble_key.key_value.lcsrk_key.counter;
1615                    pairing_cb.ble.lcsrk_key.div = p_data->ble_key.key_value.lcsrk_key.div;
1616                    pairing_cb.ble.lcsrk_key.sec_level = p_data->ble_key.key_value.lcsrk_key.sec_level;
1617
1618                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.div=0x%04x",pairing_cb.ble.lcsrk_key.div);
1619                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.counter=0x%08x",pairing_cb.ble.lcsrk_key.counter);
1620                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.sec_level=0x%02x",pairing_cb.ble.lcsrk_key.sec_level);
1621
1622                    break;
1623
1624                default:
1625                    BTIF_TRACE_ERROR("unknown BLE key type (0x%02x)", p_data->ble_key.key_type);
1626                    break;
1627            }
1628
1629            break;
1630        case BTA_DM_BLE_SEC_REQ_EVT:
1631            BTIF_TRACE_DEBUG("BTA_DM_BLE_SEC_REQ_EVT. ");
1632            btif_dm_ble_sec_req_evt(&p_data->ble_req);
1633            break;
1634        case BTA_DM_BLE_PASSKEY_NOTIF_EVT:
1635            BTIF_TRACE_DEBUG("BTA_DM_BLE_PASSKEY_NOTIF_EVT. ");
1636            btif_dm_ble_key_notif_evt(&p_data->key_notif);
1637            break;
1638        case BTA_DM_BLE_PASSKEY_REQ_EVT:
1639            BTIF_TRACE_DEBUG("BTA_DM_BLE_PASSKEY_REQ_EVT. ");
1640            btif_dm_ble_passkey_req_evt(&p_data->pin_req);
1641            break;
1642        case BTA_DM_BLE_OOB_REQ_EVT:
1643            BTIF_TRACE_DEBUG("BTA_DM_BLE_OOB_REQ_EVT. ");
1644            break;
1645        case BTA_DM_BLE_LOCAL_IR_EVT:
1646            BTIF_TRACE_DEBUG("BTA_DM_BLE_LOCAL_IR_EVT. ");
1647            ble_local_key_cb.is_id_keys_rcvd = TRUE;
1648            memcpy(&ble_local_key_cb.id_keys.irk[0], &p_data->ble_id_keys.irk[0], sizeof(BT_OCTET16));
1649            memcpy(&ble_local_key_cb.id_keys.ir[0], &p_data->ble_id_keys.ir[0], sizeof(BT_OCTET16));
1650            memcpy(&ble_local_key_cb.id_keys.dhk[0], &p_data->ble_id_keys.dhk[0], sizeof(BT_OCTET16));
1651            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.irk[0],
1652                                            BTIF_DM_LE_LOCAL_KEY_IR,
1653                                            BT_OCTET16_LEN);
1654            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.ir[0],
1655                                            BTIF_DM_LE_LOCAL_KEY_IRK,
1656                                            BT_OCTET16_LEN);
1657            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.dhk[0],
1658                                            BTIF_DM_LE_LOCAL_KEY_DHK,
1659                                            BT_OCTET16_LEN);
1660            break;
1661        case BTA_DM_BLE_LOCAL_ER_EVT:
1662            BTIF_TRACE_DEBUG("BTA_DM_BLE_LOCAL_ER_EVT. ");
1663            ble_local_key_cb.is_er_rcvd = TRUE;
1664            memcpy(&ble_local_key_cb.er[0], &p_data->ble_er[0], sizeof(BT_OCTET16));
1665            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.er[0],
1666                                            BTIF_DM_LE_LOCAL_KEY_ER,
1667                                            BT_OCTET16_LEN);
1668            break;
1669
1670        case BTA_DM_BLE_AUTH_CMPL_EVT:
1671            BTIF_TRACE_DEBUG("BTA_DM_BLE_KEY_EVT. ");
1672            btif_dm_ble_auth_cmpl_evt(&p_data->auth_cmpl);
1673            break;
1674
1675        case BTA_DM_LE_FEATURES_READ:
1676        {
1677            tBTM_BLE_VSC_CB cmn_vsc_cb;
1678            bt_local_le_features_t local_le_features;
1679            char buf[512];
1680            bt_property_t prop;
1681            prop.type = BT_PROPERTY_LOCAL_LE_FEATURES;
1682            prop.val = (void*)buf;
1683            prop.len = sizeof(buf);
1684
1685           /* LE features are not stored in storage. Should be retrived from stack */
1686            BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
1687            local_le_features.local_privacy_enabled = BTM_BleLocalPrivacyEnabled();
1688
1689            prop.len = sizeof (bt_local_le_features_t);
1690            if (cmn_vsc_cb.filter_support == 1)
1691                local_le_features.max_adv_filter_supported = cmn_vsc_cb.max_filter;
1692             else
1693                local_le_features.max_adv_filter_supported = 0;
1694            local_le_features.max_adv_instance = cmn_vsc_cb.adv_inst_max;
1695            local_le_features.max_irk_list_size = cmn_vsc_cb.max_irk_list_sz;
1696            local_le_features.rpa_offload_supported = cmn_vsc_cb.rpa_offloading;
1697            local_le_features.scan_result_storage_size_hibyte =
1698                (cmn_vsc_cb.tot_scan_results_strg >> 8) & (0xFF);
1699            local_le_features.scan_result_storage_size_lobyte =
1700                (cmn_vsc_cb.tot_scan_results_strg) & (0xFF);
1701            local_le_features.activity_energy_info_supported = cmn_vsc_cb.energy_support;
1702            memcpy(prop.val, &local_le_features, prop.len);
1703            HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, BT_STATUS_SUCCESS, 1, &prop);
1704            break;
1705         }
1706
1707        case BTA_DM_ENER_INFO_READ:
1708        {
1709            btif_activity_energy_info_cb_t *p_ener_data = (btif_activity_energy_info_cb_t*) p_param;
1710            bt_activity_energy_info energy_info;
1711            energy_info.status = p_ener_data->status;
1712            energy_info.ctrl_state = p_ener_data->ctrl_state;
1713            energy_info.rx_time = p_ener_data->rx_time;
1714            energy_info.tx_time = p_ener_data->tx_time;
1715            energy_info.idle_time = p_ener_data->idle_time;
1716            energy_info.energy_used = p_ener_data->energy_used;
1717            HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info);
1718            break;
1719        }
1720#endif
1721
1722        case BTA_DM_AUTHORIZE_EVT:
1723        case BTA_DM_SIG_STRENGTH_EVT:
1724        case BTA_DM_SP_RMT_OOB_EVT:
1725        case BTA_DM_SP_KEYPRESS_EVT:
1726        case BTA_DM_ROLE_CHG_EVT:
1727
1728        default:
1729            BTIF_TRACE_WARNING( "btif_dm_cback : unhandled event (%d)", event );
1730            break;
1731    }
1732} /* btui_security_cback() */
1733
1734
1735/*******************************************************************************
1736**
1737** Function         btif_dm_generic_evt
1738**
1739** Description      Executes non-BTA upstream events in BTIF context
1740**
1741** Returns          void
1742**
1743*******************************************************************************/
1744static void btif_dm_generic_evt(UINT16 event, char* p_param)
1745{
1746    BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
1747    switch(event)
1748    {
1749        case BTIF_DM_CB_DISCOVERY_STARTED:
1750        {
1751            HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STARTED);
1752        }
1753        break;
1754
1755        case BTIF_DM_CB_CREATE_BOND:
1756        {
1757            btif_dm_create_bond_cb_t *create_bond_cb = (btif_dm_create_bond_cb_t*)p_param;
1758            btif_dm_cb_create_bond(&create_bond_cb->bdaddr, create_bond_cb->transport);
1759        }
1760        break;
1761
1762        case BTIF_DM_CB_REMOVE_BOND:
1763        {
1764            btif_dm_cb_remove_bond((bt_bdaddr_t *)p_param);
1765        }
1766        break;
1767
1768        case BTIF_DM_CB_HID_REMOTE_NAME:
1769        {
1770            btif_dm_cb_hid_remote_name((tBTM_REMOTE_DEV_NAME *)p_param);
1771        }
1772        break;
1773
1774        case BTIF_DM_CB_BOND_STATE_BONDING:
1775            {
1776                bond_state_changed(BT_STATUS_SUCCESS, (bt_bdaddr_t *)p_param, BT_BOND_STATE_BONDING);
1777            }
1778            break;
1779        case BTIF_DM_CB_LE_TX_TEST:
1780        case BTIF_DM_CB_LE_RX_TEST:
1781            {
1782                uint8_t status;
1783                STREAM_TO_UINT8(status, p_param);
1784                HAL_CBACK(bt_hal_cbacks, le_test_mode_cb,
1785                      (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0);
1786            }
1787            break;
1788        case BTIF_DM_CB_LE_TEST_END:
1789            {
1790                uint8_t status;
1791                uint16_t count = 0;
1792                STREAM_TO_UINT8(status, p_param);
1793                if (status == 0)
1794                    STREAM_TO_UINT16(count, p_param);
1795                HAL_CBACK(bt_hal_cbacks, le_test_mode_cb,
1796                      (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, count);
1797            }
1798            break;
1799        default:
1800        {
1801            BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __FUNCTION__, event);
1802        }
1803        break;
1804    }
1805}
1806
1807/*******************************************************************************
1808**
1809** Function         bte_dm_evt
1810**
1811** Description      Switches context from BTE to BTIF for all DM events
1812**
1813** Returns          void
1814**
1815*******************************************************************************/
1816
1817void bte_dm_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC *p_data)
1818{
1819    bt_status_t status;
1820
1821    /* switch context to btif task context (copy full union size for convenience) */
1822    status = btif_transfer_context(btif_dm_upstreams_evt, (uint16_t)event, (void*)p_data, sizeof(tBTA_DM_SEC), NULL);
1823
1824    /* catch any failed context transfers */
1825    ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
1826}
1827
1828/*******************************************************************************
1829**
1830** Function         bte_search_devices_evt
1831**
1832** Description      Switches context from BTE to BTIF for DM search events
1833**
1834** Returns          void
1835**
1836*******************************************************************************/
1837static void bte_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
1838{
1839    UINT16 param_len = 0;
1840
1841    if (p_data)
1842        param_len += sizeof(tBTA_DM_SEARCH);
1843    /* Allocate buffer to hold the pointers (deep copy). The pointers will point to the end of the tBTA_DM_SEARCH */
1844    switch (event)
1845    {
1846        case BTA_DM_INQ_RES_EVT:
1847        {
1848            if (p_data->inq_res.p_eir)
1849                param_len += HCI_EXT_INQ_RESPONSE_LEN;
1850        }
1851        break;
1852
1853        case BTA_DM_DISC_RES_EVT:
1854        {
1855            if (p_data->disc_res.raw_data_size && p_data->disc_res.p_raw_data)
1856                param_len += p_data->disc_res.raw_data_size;
1857        }
1858        break;
1859    }
1860    BTIF_TRACE_DEBUG("%s event=%s param_len=%d", __FUNCTION__, dump_dm_search_event(event), param_len);
1861
1862    /* if remote name is available in EIR, set teh flag so that stack doesnt trigger RNR */
1863    if (event == BTA_DM_INQ_RES_EVT)
1864        p_data->inq_res.remt_name_not_required = check_eir_remote_name(p_data, NULL, NULL);
1865
1866    btif_transfer_context (btif_dm_search_devices_evt , (UINT16) event, (void *)p_data, param_len,
1867        (param_len > sizeof(tBTA_DM_SEARCH)) ? search_devices_copy_cb : NULL);
1868}
1869
1870/*******************************************************************************
1871**
1872** Function         bte_dm_search_services_evt
1873**
1874** Description      Switches context from BTE to BTIF for DM search services
1875**                  event
1876**
1877** Returns          void
1878**
1879*******************************************************************************/
1880static void bte_dm_search_services_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
1881{
1882    UINT16 param_len = 0;
1883   if (p_data)
1884       param_len += sizeof(tBTA_DM_SEARCH);
1885   switch (event)
1886   {
1887         case BTA_DM_DISC_RES_EVT:
1888         {
1889             if ((p_data->disc_res.result == BTA_SUCCESS) && (p_data->disc_res.num_uuids > 0)) {
1890                  param_len += (p_data->disc_res.num_uuids * MAX_UUID_SIZE);
1891             }
1892         } break;
1893   }
1894   /* TODO: The only other member that needs a deep copy is the p_raw_data. But not sure
1895    * if raw_data is needed. */
1896   btif_transfer_context(btif_dm_search_services_evt, event, (char*)p_data, param_len,
1897         (param_len > sizeof(tBTA_DM_SEARCH)) ? search_services_copy_cb : NULL);
1898}
1899
1900/*******************************************************************************
1901**
1902** Function         bte_dm_remote_service_record_evt
1903**
1904** Description      Switches context from BTE to BTIF for DM search service
1905**                  record event
1906**
1907** Returns          void
1908**
1909*******************************************************************************/
1910static void bte_dm_remote_service_record_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
1911{
1912   /* TODO: The only member that needs a deep copy is the p_raw_data. But not sure yet if this is needed. */
1913   btif_transfer_context(btif_dm_remote_service_record_evt, event, (char*)p_data, sizeof(tBTA_DM_SEARCH), NULL);
1914}
1915
1916#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1917/*******************************************************************************
1918**
1919** Function         bta_energy_info_cb
1920**
1921** Description      Switches context from BTE to BTIF for DM energy info event
1922**
1923** Returns          void
1924**
1925*******************************************************************************/
1926static void bta_energy_info_cb(tBTA_DM_BLE_TX_TIME_MS tx_time, tBTA_DM_BLE_RX_TIME_MS rx_time,
1927                                    tBTA_DM_BLE_IDLE_TIME_MS idle_time,
1928                                    tBTA_DM_BLE_ENERGY_USED energy_used,
1929                                    tBTA_DM_CONTRL_STATE ctrl_state, tBTA_STATUS status)
1930{
1931    BTIF_TRACE_DEBUG("energy_info_cb-Status:%d,state=%d,tx_t=%ld, rx_t=%ld, idle_time=%ld,used=%ld",
1932        status, ctrl_state, tx_time, rx_time, idle_time, energy_used);
1933
1934    btif_activity_energy_info_cb_t btif_cb;
1935    btif_cb.status = status;
1936    btif_cb.ctrl_state = ctrl_state;
1937    btif_cb.tx_time = (uint64_t) tx_time;
1938    btif_cb.rx_time = (uint64_t) rx_time;
1939    btif_cb.idle_time =(uint64_t) idle_time;
1940    btif_cb.energy_used =(uint64_t) energy_used;
1941    btif_transfer_context(btif_dm_upstreams_evt, BTA_DM_ENER_INFO_READ,
1942                          (char*) &btif_cb, sizeof(btif_activity_energy_info_cb_t), NULL);
1943}
1944#endif
1945
1946/*******************************************************************************
1947**
1948** Function         bte_scan_filt_param_cfg_evt
1949**
1950** Description      Scan filter param config event
1951**
1952** Returns          void
1953**
1954*******************************************************************************/
1955static void bte_scan_filt_param_cfg_evt(UINT8 action_type,
1956                                        tBTA_DM_BLE_PF_AVBL_SPACE avbl_space,
1957                                        tBTA_DM_BLE_REF_VALUE ref_value, tBTA_STATUS status)
1958{
1959    /* This event occurs on calling BTA_DmBleCfgFilterCondition internally,
1960    ** and that is why there is no HAL callback
1961    */
1962    if(BTA_SUCCESS != status)
1963    {
1964        BTIF_TRACE_ERROR("%s, %d", __FUNCTION__, status);
1965    }
1966    else
1967    {
1968        BTIF_TRACE_DEBUG("%s", __FUNCTION__);
1969    }
1970}
1971
1972/*****************************************************************************
1973**
1974**   btif api functions (no context switch)
1975**
1976*****************************************************************************/
1977
1978/*******************************************************************************
1979**
1980** Function         btif_dm_start_discovery
1981**
1982** Description      Start device discovery/inquiry
1983**
1984** Returns          bt_status_t
1985**
1986*******************************************************************************/
1987bt_status_t btif_dm_start_discovery(void)
1988{
1989    tBTA_DM_INQ inq_params;
1990    tBTA_SERVICE_MASK services = 0;
1991    tBTA_DM_BLE_PF_FILT_PARAMS adv_filt_param;
1992
1993    BTIF_TRACE_EVENT("%s", __FUNCTION__);
1994
1995#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1996    memset(&adv_filt_param, 0, sizeof(tBTA_DM_BLE_PF_FILT_PARAMS));
1997    /* Cleanup anything remaining on index 0 */
1998    BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_DELETE, 0, &adv_filt_param, NULL,
1999                             bte_scan_filt_param_cfg_evt, 0);
2000
2001    /* Add an allow-all filter on index 0*/
2002    adv_filt_param.dely_mode = IMMEDIATE_DELY_MODE;
2003    adv_filt_param.feat_seln = ALLOW_ALL_FILTER;
2004    adv_filt_param.filt_logic_type = BTA_DM_BLE_PF_FILT_LOGIC_OR;
2005    adv_filt_param.list_logic_type = BTA_DM_BLE_PF_LIST_LOGIC_OR;
2006    adv_filt_param.rssi_low_thres = LOWEST_RSSI_VALUE;
2007    adv_filt_param.rssi_high_thres = LOWEST_RSSI_VALUE;
2008    BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_ADD, 0, &adv_filt_param, NULL,
2009                             bte_scan_filt_param_cfg_evt, 0);
2010
2011    /* TODO: Do we need to handle multiple inquiries at the same time? */
2012
2013    /* Set inquiry params and call API */
2014    inq_params.mode = BTA_DM_GENERAL_INQUIRY|BTA_BLE_GENERAL_INQUIRY;
2015#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
2016    inq_params.intl_duration[0]= BTIF_DM_INTERLEAVE_DURATION_BR_ONE;
2017    inq_params.intl_duration[1]= BTIF_DM_INTERLEAVE_DURATION_LE_ONE;
2018    inq_params.intl_duration[2]= BTIF_DM_INTERLEAVE_DURATION_BR_TWO;
2019    inq_params.intl_duration[3]= BTIF_DM_INTERLEAVE_DURATION_LE_TWO;
2020#endif
2021#else
2022    inq_params.mode = BTA_DM_GENERAL_INQUIRY;
2023#endif
2024    inq_params.duration = BTIF_DM_DEFAULT_INQ_MAX_DURATION;
2025
2026    inq_params.max_resps = BTIF_DM_DEFAULT_INQ_MAX_RESULTS;
2027    inq_params.report_dup = TRUE;
2028
2029    inq_params.filter_type = BTA_DM_INQ_CLR;
2030    /* TODO: Filter device by BDA needs to be implemented here */
2031
2032    /* Will be enabled to TRUE once inquiry busy level has been received */
2033    btif_dm_inquiry_in_progress = FALSE;
2034    /* find nearby devices */
2035    BTA_DmSearch(&inq_params, services, bte_search_devices_evt);
2036
2037    return BT_STATUS_SUCCESS;
2038}
2039
2040/*******************************************************************************
2041**
2042** Function         btif_dm_cancel_discovery
2043**
2044** Description      Cancels search
2045**
2046** Returns          bt_status_t
2047**
2048*******************************************************************************/
2049bt_status_t btif_dm_cancel_discovery(void)
2050{
2051    BTIF_TRACE_EVENT("%s", __FUNCTION__);
2052    BTA_DmSearchCancel();
2053    return BT_STATUS_SUCCESS;
2054}
2055
2056/*******************************************************************************
2057**
2058** Function         btif_dm_create_bond
2059**
2060** Description      Initiate bonding with the specified device
2061**
2062** Returns          bt_status_t
2063**
2064*******************************************************************************/
2065bt_status_t btif_dm_create_bond(const bt_bdaddr_t *bd_addr, int transport)
2066{
2067    btif_dm_create_bond_cb_t create_bond_cb;
2068    create_bond_cb.transport = transport;
2069    bdcpy(create_bond_cb.bdaddr.address, bd_addr->address);
2070
2071    bdstr_t bdstr;
2072    BTIF_TRACE_EVENT("%s: bd_addr=%s, transport=%d", __FUNCTION__,
2073            bd2str((bt_bdaddr_t *) bd_addr, &bdstr), transport);
2074    if (pairing_cb.state != BT_BOND_STATE_NONE)
2075        return BT_STATUS_BUSY;
2076
2077    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_CREATE_BOND,
2078                          (char *)&create_bond_cb, sizeof(btif_dm_create_bond_cb_t), NULL);
2079
2080    return BT_STATUS_SUCCESS;
2081}
2082
2083/*******************************************************************************
2084**
2085** Function         btif_dm_cancel_bond
2086**
2087** Description      Initiate bonding with the specified device
2088**
2089** Returns          bt_status_t
2090**
2091*******************************************************************************/
2092
2093bt_status_t btif_dm_cancel_bond(const bt_bdaddr_t *bd_addr)
2094{
2095    bdstr_t bdstr;
2096
2097    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
2098
2099    /* TODO:
2100    **  1. Restore scan modes
2101    **  2. special handling for HID devices
2102    */
2103    if (pairing_cb.state == BT_BOND_STATE_BONDING)
2104    {
2105
2106#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2107
2108        if (pairing_cb.is_ssp)
2109        {
2110            if (pairing_cb.is_le_only)
2111            {
2112                BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_PAIR_NOT_SPT);
2113            }
2114            else
2115            {
2116                BTA_DmConfirm( (UINT8 *)bd_addr->address, FALSE);
2117                BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2118                btif_storage_remove_bonded_device((bt_bdaddr_t *)bd_addr);
2119            }
2120        }
2121        else
2122        {
2123            if (pairing_cb.is_le_only)
2124            {
2125                BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2126            }
2127            else
2128            {
2129                BTA_DmPinReply( (UINT8 *)bd_addr->address, FALSE, 0, NULL);
2130            }
2131        /* Cancel bonding, in case it is in ACL connection setup state */
2132        BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2133        }
2134
2135#else
2136        if (pairing_cb.is_ssp)
2137        {
2138            BTA_DmConfirm( (UINT8 *)bd_addr->address, FALSE);
2139        }
2140        else
2141        {
2142            BTA_DmPinReply( (UINT8 *)bd_addr->address, FALSE, 0, NULL);
2143        }
2144        /* Cancel bonding, in case it is in ACL connection setup state */
2145        BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2146        btif_storage_remove_bonded_device((bt_bdaddr_t *)bd_addr);
2147#endif
2148    }
2149
2150    return BT_STATUS_SUCCESS;
2151}
2152
2153/*******************************************************************************
2154**
2155** Function         btif_dm_hh_open_failed
2156**
2157** Description      informs the upper layers if the HH have failed during bonding
2158**
2159** Returns          none
2160**
2161*******************************************************************************/
2162
2163void btif_dm_hh_open_failed(bt_bdaddr_t *bdaddr)
2164{
2165    if (pairing_cb.state == BT_BOND_STATE_BONDING &&
2166            bdcmp(bdaddr->address, pairing_cb.bd_addr) == 0)
2167    {
2168        bond_state_changed(BT_STATUS_FAIL, bdaddr, BT_BOND_STATE_NONE);
2169    }
2170}
2171
2172/*******************************************************************************
2173**
2174** Function         btif_dm_remove_bond
2175**
2176** Description      Removes bonding with the specified device
2177**
2178** Returns          bt_status_t
2179**
2180*******************************************************************************/
2181
2182bt_status_t btif_dm_remove_bond(const bt_bdaddr_t *bd_addr)
2183{
2184    bdstr_t bdstr;
2185
2186    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
2187    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_REMOVE_BOND,
2188                          (char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
2189
2190    return BT_STATUS_SUCCESS;
2191}
2192
2193/*******************************************************************************
2194**
2195** Function         btif_dm_pin_reply
2196**
2197** Description      BT legacy pairing - PIN code reply
2198**
2199** Returns          bt_status_t
2200**
2201*******************************************************************************/
2202
2203bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
2204                               uint8_t pin_len, bt_pin_code_t *pin_code)
2205{
2206    BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
2207    if (pin_code == NULL)
2208        return BT_STATUS_FAIL;
2209#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2210
2211    if (pairing_cb.is_le_only)
2212    {
2213        int i;
2214        UINT32 passkey = 0;
2215        int multi[] = {100000, 10000, 1000, 100, 10,1};
2216        BD_ADDR remote_bd_addr;
2217        bdcpy(remote_bd_addr, bd_addr->address);
2218        for (i = 0; i < 6; i++)
2219        {
2220            passkey += (multi[i] * (pin_code->pin[i] - '0'));
2221        }
2222        BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
2223        BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
2224
2225    }
2226    else
2227    {
2228        BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
2229        if (accept)
2230            pairing_cb.pin_code_len = pin_len;
2231    }
2232#else
2233    BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
2234
2235    if (accept)
2236        pairing_cb.pin_code_len = pin_len;
2237#endif
2238    return BT_STATUS_SUCCESS;
2239}
2240
2241/*******************************************************************************
2242**
2243** Function         btif_dm_ssp_reply
2244**
2245** Description      BT SSP Reply - Just Works, Numeric Comparison & Passkey Entry
2246**
2247** Returns          bt_status_t
2248**
2249*******************************************************************************/
2250bt_status_t btif_dm_ssp_reply(const bt_bdaddr_t *bd_addr,
2251                                 bt_ssp_variant_t variant, uint8_t accept,
2252                                 uint32_t passkey)
2253{
2254    UNUSED(passkey);
2255
2256    if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY)
2257    {
2258        /* This is not implemented in the stack.
2259         * For devices with display, this is not needed
2260        */
2261        BTIF_TRACE_WARNING("%s: Not implemented", __FUNCTION__);
2262        return BT_STATUS_FAIL;
2263    }
2264    /* BT_SSP_VARIANT_CONSENT & BT_SSP_VARIANT_PASSKEY_CONFIRMATION supported */
2265    BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
2266#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2267    if (pairing_cb.is_le_only)
2268    {
2269        if (accept)
2270            BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_GRANTED);
2271        else
2272            BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_PAIR_NOT_SPT);
2273    }
2274    else
2275        BTA_DmConfirm( (UINT8 *)bd_addr->address, accept);
2276
2277#else
2278    BTA_DmConfirm( (UINT8 *)bd_addr->address, accept);
2279#endif
2280    return BT_STATUS_SUCCESS;
2281}
2282
2283/*******************************************************************************
2284**
2285** Function         btif_dm_get_adapter_property
2286**
2287** Description     Queries the BTA for the adapter property
2288**
2289** Returns          bt_status_t
2290**
2291*******************************************************************************/
2292bt_status_t btif_dm_get_adapter_property(bt_property_t *prop)
2293{
2294    bt_status_t status;
2295
2296    BTIF_TRACE_EVENT("%s: type=0x%x", __FUNCTION__, prop->type);
2297    switch (prop->type)
2298    {
2299        case BT_PROPERTY_BDNAME:
2300        {
2301            bt_bdname_t *bd_name = (bt_bdname_t*)prop->val;
2302            strcpy((char *)bd_name->name, btif_get_default_local_name());
2303            prop->len = strlen((char *)bd_name->name);
2304        }
2305        break;
2306
2307        case BT_PROPERTY_ADAPTER_SCAN_MODE:
2308        {
2309            /* if the storage does not have it. Most likely app never set it. Default is NONE */
2310            bt_scan_mode_t *mode = (bt_scan_mode_t*)prop->val;
2311            *mode = BT_SCAN_MODE_NONE;
2312            prop->len = sizeof(bt_scan_mode_t);
2313        }
2314        break;
2315
2316        case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
2317        {
2318            uint32_t *tmt = (uint32_t*)prop->val;
2319            *tmt = 120; /* default to 120s, if not found in NV */
2320            prop->len = sizeof(uint32_t);
2321        }
2322        break;
2323
2324        default:
2325            prop->len = 0;
2326            return BT_STATUS_FAIL;
2327    }
2328    return BT_STATUS_SUCCESS;
2329}
2330
2331/*******************************************************************************
2332**
2333** Function         btif_dm_get_remote_services
2334**
2335** Description      Start SDP to get remote services
2336**
2337** Returns          bt_status_t
2338**
2339*******************************************************************************/
2340bt_status_t btif_dm_get_remote_services(bt_bdaddr_t *remote_addr)
2341{
2342    bdstr_t bdstr;
2343
2344    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
2345
2346    BTA_DmDiscover(remote_addr->address, BTA_ALL_SERVICE_MASK,
2347                   bte_dm_search_services_evt, TRUE);
2348
2349    return BT_STATUS_SUCCESS;
2350}
2351
2352/*******************************************************************************
2353**
2354** Function         btif_dm_get_remote_service_record
2355**
2356** Description      Start SDP to get remote service record
2357**
2358**
2359** Returns          bt_status_t
2360*******************************************************************************/
2361bt_status_t btif_dm_get_remote_service_record(bt_bdaddr_t *remote_addr,
2362                                                    bt_uuid_t *uuid)
2363{
2364    tSDP_UUID sdp_uuid;
2365    bdstr_t bdstr;
2366
2367    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
2368
2369    sdp_uuid.len = MAX_UUID_SIZE;
2370    memcpy(sdp_uuid.uu.uuid128, uuid->uu, MAX_UUID_SIZE);
2371
2372    BTA_DmDiscoverUUID(remote_addr->address, &sdp_uuid,
2373                       bte_dm_remote_service_record_evt, TRUE);
2374
2375    return BT_STATUS_SUCCESS;
2376}
2377
2378void btif_dm_execute_service_request(UINT16 event, char *p_param)
2379{
2380    BOOLEAN b_enable = FALSE;
2381    bt_status_t status;
2382    if (event == BTIF_DM_ENABLE_SERVICE)
2383    {
2384        b_enable = TRUE;
2385    }
2386    status = btif_in_execute_service_request(*((tBTA_SERVICE_ID*)p_param), b_enable);
2387    if (status == BT_STATUS_SUCCESS)
2388    {
2389        bt_property_t property;
2390        bt_uuid_t local_uuids[BT_MAX_NUM_UUIDS];
2391
2392        /* Now send the UUID_PROPERTY_CHANGED event to the upper layer */
2393        BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS,
2394                                    sizeof(local_uuids), local_uuids);
2395        btif_storage_get_adapter_property(&property);
2396        HAL_CBACK(bt_hal_cbacks, adapter_properties_cb,
2397                          BT_STATUS_SUCCESS, 1, &property);
2398    }
2399    return;
2400}
2401
2402void btif_dm_proc_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap, tBTA_OOB_DATA *p_oob_data,
2403                      tBTA_AUTH_REQ *p_auth_req, BOOLEAN is_orig)
2404{
2405    UINT8   yes_no_bit = BTA_AUTH_SP_YES & *p_auth_req;
2406    /* if local initiated:
2407    **      1. set DD + MITM
2408    ** if remote initiated:
2409    **      1. Copy over the auth_req from peer's io_rsp
2410    **      2. Set the MITM if peer has it set or if peer has DisplayYesNo (iPhone)
2411    ** as a fallback set MITM+GB if peer had MITM set
2412    */
2413    UNUSED (bd_addr);
2414    UNUSED (p_io_cap);
2415    UNUSED (p_oob_data);
2416
2417
2418    BTIF_TRACE_DEBUG("+%s: p_auth_req=%d", __FUNCTION__, *p_auth_req);
2419    if(pairing_cb.is_local_initiated)
2420    {
2421        /* if initing/responding to a dedicated bonding, use dedicate bonding bit */
2422        *p_auth_req = BTA_AUTH_DD_BOND | BTA_AUTH_SP_YES;
2423    }
2424    else if (!is_orig)
2425    {
2426        /* peer initiated paring. They probably know what they want.
2427        ** Copy the mitm from peer device.
2428        */
2429        BTIF_TRACE_DEBUG("%s: setting p_auth_req to peer's: %d",
2430                __FUNCTION__, pairing_cb.auth_req);
2431        *p_auth_req = (pairing_cb.auth_req & BTA_AUTH_BONDS);
2432
2433        /* copy over the MITM bit as well. In addition if the peer has DisplayYesNo, force MITM */
2434        if ((yes_no_bit) || (pairing_cb.io_cap & BTM_IO_CAP_IO) )
2435            *p_auth_req |= BTA_AUTH_SP_YES;
2436    }
2437    else if (yes_no_bit)
2438    {
2439        /* set the general bonding bit for stored device */
2440        *p_auth_req = BTA_AUTH_GEN_BOND | yes_no_bit;
2441    }
2442    BTIF_TRACE_DEBUG("-%s: p_auth_req=%d", __FUNCTION__, *p_auth_req);
2443}
2444
2445void btif_dm_proc_io_rsp(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
2446                      tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req)
2447{
2448    UNUSED (bd_addr);
2449    UNUSED (oob_data);
2450
2451    if(auth_req & BTA_AUTH_BONDS)
2452    {
2453        BTIF_TRACE_DEBUG("%s auth_req:%d", __FUNCTION__, auth_req);
2454        pairing_cb.auth_req = auth_req;
2455        pairing_cb.io_cap = io_cap;
2456    }
2457}
2458
2459#if (BTM_OOB_INCLUDED == TRUE)
2460void btif_dm_set_oob_for_io_req(tBTA_OOB_DATA  *p_oob_data)
2461{
2462    if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2463        oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 )
2464    {
2465        *p_oob_data = FALSE;
2466    }
2467    else
2468    {
2469        *p_oob_data = TRUE;
2470    }
2471    BTIF_TRACE_DEBUG("btif_dm_set_oob_for_io_req *p_oob_data=%d", *p_oob_data);
2472}
2473#endif /* BTM_OOB_INCLUDED */
2474
2475#ifdef BTIF_DM_OOB_TEST
2476void btif_dm_load_local_oob(void)
2477{
2478    char prop_oob[PROPERTY_VALUE_MAX];
2479    property_get("service.brcm.bt.oob", prop_oob, "3");
2480    BTIF_TRACE_DEBUG("btif_dm_load_local_oob prop_oob = %s",prop_oob);
2481    if (prop_oob[0] != '3')
2482    {
2483#if (BTM_OOB_INCLUDED == TRUE)
2484        if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2485            oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 )
2486        {
2487            BTIF_TRACE_DEBUG("btif_dm_load_local_oob: read OOB, call BTA_DmLocalOob()");
2488            BTA_DmLocalOob();
2489        }
2490#else
2491        BTIF_TRACE_ERROR("BTM_OOB_INCLUDED is FALSE!!(btif_dm_load_local_oob)");
2492#endif
2493    }
2494}
2495
2496void btif_dm_proc_loc_oob(BOOLEAN valid, BT_OCTET16 c, BT_OCTET16 r)
2497{
2498    FILE *fp;
2499    char *path_a = "/data/misc/bluedroid/LOCAL/a.key";
2500    char *path_b = "/data/misc/bluedroid/LOCAL/b.key";
2501    char *path = NULL;
2502    char prop_oob[PROPERTY_VALUE_MAX];
2503    BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: valid=%d", valid);
2504    if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2505        oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 &&
2506        valid)
2507    {
2508        BTIF_TRACE_DEBUG("save local OOB data in memory");
2509        memcpy(oob_cb.sp_c, c, BT_OCTET16_LEN);
2510        memcpy(oob_cb.sp_r, r, BT_OCTET16_LEN);
2511        property_get("service.brcm.bt.oob", prop_oob, "3");
2512        BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob prop_oob = %s",prop_oob);
2513        if (prop_oob[0] == '1')
2514            path = path_a;
2515        else if (prop_oob[0] == '2')
2516            path = path_b;
2517        if (path)
2518        {
2519            fp = fopen(path, "wb+");
2520            if (fp == NULL)
2521            {
2522                BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: failed to save local OOB data to %s", path);
2523            }
2524            else
2525            {
2526                BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: save local OOB data into file %s",path);
2527                fwrite (c , 1 , BT_OCTET16_LEN , fp );
2528                fwrite (r , 1 , BT_OCTET16_LEN , fp );
2529                fclose(fp);
2530            }
2531        }
2532    }
2533}
2534BOOLEAN btif_dm_proc_rmt_oob(BD_ADDR bd_addr,  BT_OCTET16 p_c, BT_OCTET16 p_r)
2535{
2536    char t[128];
2537    FILE *fp;
2538    char *path_a = "/data/misc/bluedroid/LOCAL/a.key";
2539    char *path_b = "/data/misc/bluedroid/LOCAL/b.key";
2540    char *path = NULL;
2541    char prop_oob[PROPERTY_VALUE_MAX];
2542    BOOLEAN result = FALSE;
2543    bt_bdaddr_t bt_bd_addr;
2544    bdcpy(oob_cb.oob_bdaddr, bd_addr);
2545    property_get("service.brcm.bt.oob", prop_oob, "3");
2546    BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob prop_oob = %s",prop_oob);
2547    if (prop_oob[0] == '1')
2548        path = path_b;
2549    else if (prop_oob[0] == '2')
2550        path = path_a;
2551    if (path)
2552    {
2553        fp = fopen(path, "rb");
2554        if (fp == NULL)
2555        {
2556            BTIF_TRACE_DEBUG("btapp_dm_rmt_oob_reply: failed to read OOB keys from %s",path);
2557            return FALSE;
2558        }
2559        else
2560        {
2561            BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob: read OOB data from %s",path);
2562            fread (p_c , 1 , BT_OCTET16_LEN , fp );
2563            fread (p_r , 1 , BT_OCTET16_LEN , fp );
2564            fclose(fp);
2565        }
2566        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: TRUE");
2567        sprintf(t, "%02x:%02x:%02x:%02x:%02x:%02x",
2568                oob_cb.oob_bdaddr[0], oob_cb.oob_bdaddr[1], oob_cb.oob_bdaddr[2],
2569                oob_cb.oob_bdaddr[3], oob_cb.oob_bdaddr[4], oob_cb.oob_bdaddr[5]);
2570        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: peer_bdaddr = %s", t);
2571        sprintf(t, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
2572                p_c[0], p_c[1], p_c[2],  p_c[3],  p_c[4],  p_c[5],  p_c[6],  p_c[7],
2573                p_c[8], p_c[9], p_c[10], p_c[11], p_c[12], p_c[13], p_c[14], p_c[15]);
2574        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: c = %s",t);
2575        sprintf(t, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
2576                p_r[0], p_r[1], p_r[2],  p_r[3],  p_r[4],  p_r[5],  p_r[6],  p_r[7],
2577                p_r[8], p_r[9], p_r[10], p_r[11], p_r[12], p_r[13], p_r[14], p_r[15]);
2578        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: r = %s",t);
2579        bdcpy(bt_bd_addr.address, bd_addr);
2580        btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_BOND_STATE_BONDING,
2581                              (char *)&bt_bd_addr, sizeof(bt_bdaddr_t), NULL);
2582        result = TRUE;
2583    }
2584    BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob result=%d",result);
2585    return result;
2586}
2587#endif /*  BTIF_DM_OOB_TEST */
2588#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2589
2590static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif)
2591{
2592    bt_bdaddr_t bd_addr;
2593    bt_bdname_t bd_name;
2594    UINT32 cod;
2595
2596    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
2597
2598    /* Remote name update */
2599    btif_update_remote_properties(p_ssp_key_notif->bd_addr , p_ssp_key_notif->bd_name,
2600                                          NULL, BT_DEVICE_TYPE_BLE);
2601    bdcpy(bd_addr.address, p_ssp_key_notif->bd_addr);
2602    memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
2603
2604    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2605    pairing_cb.is_ssp = FALSE;
2606    cod = COD_UNCLASSIFIED;
2607
2608    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name,
2609              cod, BT_SSP_VARIANT_PASSKEY_NOTIFICATION,
2610              p_ssp_key_notif->passkey);
2611}
2612
2613/*******************************************************************************
2614**
2615** Function         btif_dm_ble_auth_cmpl_evt
2616**
2617** Description      Executes authentication complete event in btif context
2618**
2619** Returns          void
2620**
2621*******************************************************************************/
2622static void btif_dm_ble_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl)
2623{
2624    /* Save link key, if not temporary */
2625    bt_bdaddr_t bd_addr;
2626    bt_status_t status = BT_STATUS_FAIL;
2627    bt_bond_state_t state = BT_BOND_STATE_NONE;
2628
2629    bdcpy(bd_addr.address, p_auth_cmpl->bd_addr);
2630    if ( (p_auth_cmpl->success == TRUE) && (p_auth_cmpl->key_present) )
2631    {
2632        /* store keys */
2633    }
2634    if (p_auth_cmpl->success)
2635    {
2636        status = BT_STATUS_SUCCESS;
2637        state = BT_BOND_STATE_BONDED;
2638
2639        btif_dm_save_ble_bonding_keys();
2640        BTA_GATTC_Refresh(bd_addr.address);
2641        btif_dm_get_remote_services(&bd_addr);
2642    }
2643    else
2644    {
2645        /*Map the HCI fail reason  to  bt status  */
2646        switch (p_auth_cmpl->fail_reason)
2647        {
2648            case BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL:
2649            case BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL:
2650                btif_dm_remove_ble_bonding_keys();
2651                status = BT_STATUS_AUTH_FAILURE;
2652                break;
2653            case BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT:
2654                status = BT_STATUS_AUTH_REJECTED;
2655                break;
2656            default:
2657                btif_dm_remove_ble_bonding_keys();
2658                status =  BT_STATUS_FAIL;
2659                break;
2660        }
2661    }
2662    bond_state_changed(status, &bd_addr, state);
2663}
2664
2665
2666
2667void    btif_dm_load_ble_local_keys(void)
2668{
2669    bt_status_t bt_status;
2670
2671    memset(&ble_local_key_cb, 0, sizeof(btif_dm_local_key_cb_t));
2672
2673    if (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_ER,(char*)&ble_local_key_cb.er[0],
2674                                       BT_OCTET16_LEN)== BT_STATUS_SUCCESS)
2675    {
2676        ble_local_key_cb.is_er_rcvd = TRUE;
2677        BTIF_TRACE_DEBUG("%s BLE ER key loaded",__FUNCTION__ );
2678    }
2679
2680    if ((btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IR,(char*)&ble_local_key_cb.id_keys.ir[0],
2681                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS )&&
2682        (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IRK, (char*)&ble_local_key_cb.id_keys.irk[0],
2683                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS)&&
2684        (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_DHK,(char*)&ble_local_key_cb.id_keys.dhk[0],
2685                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS))
2686    {
2687        ble_local_key_cb.is_id_keys_rcvd = TRUE;
2688        BTIF_TRACE_DEBUG("%s BLE ID keys loaded",__FUNCTION__ );
2689    }
2690
2691}
2692void    btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er,
2693                                   tBTA_BLE_LOCAL_ID_KEYS *p_id_keys)
2694{
2695    if (ble_local_key_cb.is_er_rcvd )
2696    {
2697        memcpy(&er[0], &ble_local_key_cb.er[0], sizeof(BT_OCTET16));
2698        *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ER;
2699    }
2700
2701    if (ble_local_key_cb.is_id_keys_rcvd)
2702    {
2703        memcpy(&p_id_keys->ir[0], &ble_local_key_cb.id_keys.ir[0], sizeof(BT_OCTET16));
2704        memcpy(&p_id_keys->irk[0],  &ble_local_key_cb.id_keys.irk[0], sizeof(BT_OCTET16));
2705        memcpy(&p_id_keys->dhk[0],  &ble_local_key_cb.id_keys.dhk[0], sizeof(BT_OCTET16));
2706        *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ID;
2707    }
2708    BTIF_TRACE_DEBUG("%s  *p_key_mask=0x%02x",__FUNCTION__,   *p_key_mask);
2709}
2710
2711void btif_dm_save_ble_bonding_keys(void)
2712{
2713
2714    bt_bdaddr_t bd_addr;
2715
2716    BTIF_TRACE_DEBUG("%s",__FUNCTION__ );
2717
2718    bdcpy(bd_addr.address, pairing_cb.bd_addr);
2719
2720    if (pairing_cb.ble.is_penc_key_rcvd)
2721    {
2722        btif_storage_add_ble_bonding_key(&bd_addr,
2723                                         (char *) &pairing_cb.ble.penc_key,
2724                                         BTIF_DM_LE_KEY_PENC,
2725                                         sizeof(btif_dm_ble_penc_keys_t));
2726    }
2727
2728    if (pairing_cb.ble.is_pid_key_rcvd)
2729    {
2730        btif_storage_add_ble_bonding_key(&bd_addr,
2731                                         (char *) &pairing_cb.ble.pid_key[0],
2732                                         BTIF_DM_LE_KEY_PID,
2733                                         BT_OCTET16_LEN);
2734    }
2735
2736
2737    if (pairing_cb.ble.is_pcsrk_key_rcvd)
2738    {
2739        btif_storage_add_ble_bonding_key(&bd_addr,
2740                                         (char *) &pairing_cb.ble.pcsrk_key,
2741                                         BTIF_DM_LE_KEY_PCSRK,
2742                                         sizeof(btif_dm_ble_pcsrk_keys_t));
2743    }
2744
2745
2746    if (pairing_cb.ble.is_lenc_key_rcvd)
2747    {
2748        btif_storage_add_ble_bonding_key(&bd_addr,
2749                                         (char *) &pairing_cb.ble.lenc_key,
2750                                         BTIF_DM_LE_KEY_LENC,
2751                                         sizeof(btif_dm_ble_lenc_keys_t));
2752    }
2753
2754    if (pairing_cb.ble.is_lcsrk_key_rcvd)
2755    {
2756        btif_storage_add_ble_bonding_key(&bd_addr,
2757                                         (char *) &pairing_cb.ble.lcsrk_key,
2758                                         BTIF_DM_LE_KEY_LCSRK,
2759                                         sizeof(btif_dm_ble_lcsrk_keys_t));
2760    }
2761
2762}
2763
2764
2765void btif_dm_remove_ble_bonding_keys(void)
2766{
2767    bt_bdaddr_t bd_addr;
2768
2769    BTIF_TRACE_DEBUG("%s",__FUNCTION__ );
2770
2771    bdcpy(bd_addr.address, pairing_cb.bd_addr);
2772    btif_storage_remove_ble_bonding_keys(&bd_addr);
2773}
2774
2775
2776/*******************************************************************************
2777**
2778** Function         btif_dm_ble_sec_req_evt
2779**
2780** Description      Eprocess security request event in btif context
2781**
2782** Returns          void
2783**
2784*******************************************************************************/
2785void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ *p_ble_req)
2786{
2787    bt_bdaddr_t bd_addr;
2788    bt_bdname_t bd_name;
2789    UINT32 cod;
2790    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
2791
2792    if (pairing_cb.state == BT_BOND_STATE_BONDING)
2793    {
2794        BTIF_TRACE_DEBUG("%s Discard security request", __FUNCTION__);
2795        return;
2796    }
2797
2798    /* Remote name update */
2799    btif_update_remote_properties(p_ble_req->bd_addr,p_ble_req->bd_name,NULL,BT_DEVICE_TYPE_BLE);
2800
2801    bdcpy(bd_addr.address, p_ble_req->bd_addr);
2802    memcpy(bd_name.name, p_ble_req->bd_name, BD_NAME_LEN);
2803
2804    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2805
2806    pairing_cb.is_temp = FALSE;
2807    pairing_cb.is_le_only = TRUE;
2808    pairing_cb.is_ssp = TRUE;
2809
2810    cod = COD_UNCLASSIFIED;
2811
2812    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name, cod,
2813              BT_SSP_VARIANT_CONSENT, 0);
2814}
2815
2816
2817
2818/*******************************************************************************
2819**
2820** Function         btif_dm_ble_passkey_req_evt
2821**
2822** Description      Executes pin request event in btif context
2823**
2824** Returns          void
2825**
2826*******************************************************************************/
2827static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ *p_pin_req)
2828{
2829    bt_bdaddr_t bd_addr;
2830    bt_bdname_t bd_name;
2831    UINT32 cod;
2832
2833    /* Remote name update */
2834    btif_update_remote_properties(p_pin_req->bd_addr,p_pin_req->bd_name,NULL,BT_DEVICE_TYPE_BLE);
2835
2836    bdcpy(bd_addr.address, p_pin_req->bd_addr);
2837    memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
2838
2839    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2840    pairing_cb.is_le_only = TRUE;
2841
2842    cod = COD_UNCLASSIFIED;
2843
2844    HAL_CBACK(bt_hal_cbacks, pin_request_cb,
2845              &bd_addr, &bd_name, cod);
2846}
2847
2848
2849void btif_dm_update_ble_remote_properties( BD_ADDR bd_addr, BD_NAME bd_name,
2850                                           tBT_DEVICE_TYPE dev_type)
2851{
2852   btif_update_remote_properties(bd_addr,bd_name,NULL,dev_type);
2853}
2854
2855static void btif_dm_ble_tx_test_cback(void *p)
2856{
2857    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_TX_TEST,
2858                          (char *)p, 1, NULL);
2859}
2860
2861static void btif_dm_ble_rx_test_cback(void *p)
2862{
2863    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_RX_TEST,
2864                          (char *)p, 1, NULL);
2865}
2866
2867static void btif_dm_ble_test_end_cback(void *p)
2868{
2869    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_TEST_END,
2870                          (char *)p, 3, NULL);
2871}
2872/*******************************************************************************
2873**
2874** Function         btif_le_test_mode
2875**
2876** Description     Sends a HCI BLE Test command to the Controller
2877**
2878** Returns          BT_STATUS_SUCCESS on success
2879**
2880*******************************************************************************/
2881bt_status_t btif_le_test_mode(uint16_t opcode, uint8_t *buf, uint8_t len)
2882{
2883     switch (opcode) {
2884         case HCI_BLE_TRANSMITTER_TEST:
2885             if (len != 3) return BT_STATUS_PARM_INVALID;
2886             BTM_BleTransmitterTest(buf[0],buf[1],buf[2], btif_dm_ble_tx_test_cback);
2887             break;
2888         case HCI_BLE_RECEIVER_TEST:
2889             if (len != 1) return BT_STATUS_PARM_INVALID;
2890             BTM_BleReceiverTest(buf[0], btif_dm_ble_rx_test_cback);
2891             break;
2892         case HCI_BLE_TEST_END:
2893             BTM_BleTestEnd((tBTM_CMPL_CB*) btif_dm_ble_test_end_cback);
2894             break;
2895         default:
2896             BTIF_TRACE_ERROR("%s: Unknown LE Test Mode Command 0x%x", __FUNCTION__, opcode);
2897             return BT_STATUS_UNSUPPORTED;
2898     }
2899     return BT_STATUS_SUCCESS;
2900}
2901
2902#endif
2903
2904void btif_dm_on_disable()
2905{
2906    /* cancel any pending pairing requests */
2907    if (pairing_cb.state == BT_BOND_STATE_BONDING)
2908    {
2909        bt_bdaddr_t bd_addr;
2910
2911        BTIF_TRACE_DEBUG("%s: Cancel pending pairing request", __FUNCTION__);
2912        bdcpy(bd_addr.address, pairing_cb.bd_addr);
2913        btif_dm_cancel_bond(&bd_addr);
2914    }
2915}
2916
2917/*******************************************************************************
2918**
2919** Function         btif_dm_read_energy_info
2920**
2921** Description     Reads the energy info from controller
2922**
2923** Returns         void
2924**
2925*******************************************************************************/
2926void btif_dm_read_energy_info()
2927{
2928#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2929    BTA_DmBleGetEnergyInfo(bta_energy_info_cb);
2930#endif
2931}
2932
2933static char* btif_get_default_local_name() {
2934    if (btif_default_local_name[0] == '\0')
2935    {
2936        int max_len = sizeof(btif_default_local_name) - 1;
2937        if (BTM_DEF_LOCAL_NAME[0] != '\0')
2938        {
2939            strncpy(btif_default_local_name, BTM_DEF_LOCAL_NAME, max_len);
2940        }
2941        else
2942        {
2943            char prop_model[PROPERTY_VALUE_MAX];
2944            property_get(PROPERTY_PRODUCT_MODEL, prop_model, "");
2945            strncpy(btif_default_local_name, prop_model, max_len);
2946        }
2947        btif_default_local_name[max_len] = '\0';
2948    }
2949    return btif_default_local_name;
2950}
2951