OSDN Git Service

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