OSDN Git Service

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