• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2014 The Android Open Source Project
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 /*******************************************************************************
21  *
22  *  Filename:      btif_core.c
23  *
24  *  Description:   Contains core functionality related to interfacing between
25  *                 Bluetooth HAL and BTE core stack.
26  *
27  ******************************************************************************/
28 
29 #define LOG_TAG "bt_btif_core"
30 
31 #include <base/at_exit.h>
32 #include <base/bind.h>
33 #include <base/run_loop.h>
34 #include <base/threading/platform_thread.h>
35 #include <base/threading/thread.h>
36 #include <ctype.h>
37 #include <dirent.h>
38 #include <fcntl.h>
39 #include <hardware/bluetooth.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44 #include <unistd.h>
45 
46 #include "bt_common.h"
47 #include "bt_utils.h"
48 #include "bta_api.h"
49 #include "bte.h"
50 #include "btif_api.h"
51 #include "btif_av.h"
52 #include "btif_config.h"
53 #include "btif_pan.h"
54 #include "btif_profile_queue.h"
55 #include "btif_sock.h"
56 #include "btif_storage.h"
57 #include "btif_uid.h"
58 #include "btif_util.h"
59 #include "btu.h"
60 #include "common/message_loop_thread.h"
61 #include "device/include/controller.h"
62 #include "osi/include/fixed_queue.h"
63 #include "osi/include/future.h"
64 #include "osi/include/log.h"
65 #include "osi/include/osi.h"
66 #include "osi/include/properties.h"
67 #include "stack_manager.h"
68 
69 using base::PlatformThread;
70 using bluetooth::Uuid;
71 using bluetooth::common::MessageLoopThread;
72 
73 /*******************************************************************************
74  *  Constants & Macros
75  ******************************************************************************/
76 
77 #ifndef BTE_DID_CONF_FILE
78 // TODO(armansito): Find a better way than searching by a hardcoded path.
79 #if defined(OS_GENERIC)
80 #define BTE_DID_CONF_FILE "bt_did.conf"
81 #else  // !defined(OS_GENERIC)
82 #define BTE_DID_CONF_FILE "/etc/bluetooth/bt_did.conf"
83 #endif  // defined(OS_GENERIC)
84 #endif  // BTE_DID_CONF_FILE
85 
86 /*******************************************************************************
87  *  Local type definitions
88  ******************************************************************************/
89 
90 /* These type definitions are used when passing data from the HAL to BTIF
91  * context in the downstream path for the adapter and remote_device property
92  * APIs
93  */
94 
95 typedef struct {
96   RawAddress bd_addr;
97   bt_property_type_t type;
98 } btif_storage_read_t;
99 
100 typedef struct {
101   RawAddress bd_addr;
102   bt_property_t prop;
103 } btif_storage_write_t;
104 
105 typedef union {
106   btif_storage_read_t read_req;
107   btif_storage_write_t write_req;
108 } btif_storage_req_t;
109 
110 typedef enum {
111   BTIF_CORE_STATE_DISABLED = 0,
112   BTIF_CORE_STATE_ENABLING,
113   BTIF_CORE_STATE_ENABLED,
114   BTIF_CORE_STATE_DISABLING
115 } btif_core_state_t;
116 
117 /*******************************************************************************
118  *  Static variables
119  ******************************************************************************/
120 
121 static tBTA_SERVICE_MASK btif_enabled_services = 0;
122 
123 /*
124  * This variable should be set to 1, if the Bluedroid+BTIF libraries are to
125  * function in DUT mode.
126  *
127  * To set this, the btif_init_bluetooth needs to be called with argument as 1
128  */
129 static uint8_t btif_dut_mode = 0;
130 
131 static MessageLoopThread jni_thread("bt_jni_thread");
132 static base::AtExitManager* exit_manager;
133 static uid_set_t* uid_set;
134 
135 /*******************************************************************************
136  *  Static functions
137  ******************************************************************************/
138 static void btif_jni_associate();
139 static void btif_jni_disassociate();
140 
141 /* sends message to btif task */
142 static void btif_sendmsg(void* p_msg);
143 
144 /*******************************************************************************
145  *  Externs
146  ******************************************************************************/
147 extern fixed_queue_t* btu_hci_msg_queue;
148 
149 void btif_dm_execute_service_request(uint16_t event, char* p_param);
150 #ifdef BTIF_DM_OOB_TEST
151 void btif_dm_load_local_oob(void);
152 #endif
153 
154 /*******************************************************************************
155  *
156  * Function         btif_context_switched
157  *
158  * Description      Callback used to execute transferred context callback
159  *
160  *                  p_msg : message to be executed in btif context
161  *
162  * Returns          void
163  *
164  ******************************************************************************/
165 
btif_context_switched(void * p_msg)166 static void btif_context_switched(void* p_msg) {
167   BTIF_TRACE_VERBOSE("btif_context_switched");
168 
169   tBTIF_CONTEXT_SWITCH_CBACK* p = (tBTIF_CONTEXT_SWITCH_CBACK*)p_msg;
170 
171   /* each callback knows how to parse the data */
172   if (p->p_cb) p->p_cb(p->event, p->p_param);
173 }
174 
175 /*******************************************************************************
176  *
177  * Function         btif_transfer_context
178  *
179  * Description      This function switches context to btif task
180  *
181  *                  p_cback   : callback used to process message in btif context
182  *                  event     : event id of message
183  *                  p_params  : parameter area passed to callback (copied)
184  *                  param_len : length of parameter area
185  *                  p_copy_cback : If set this function will be invoked for deep
186  *                                 copy
187  *
188  * Returns          void
189  *
190  ******************************************************************************/
191 
btif_transfer_context(tBTIF_CBACK * p_cback,uint16_t event,char * p_params,int param_len,tBTIF_COPY_CBACK * p_copy_cback)192 bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event,
193                                   char* p_params, int param_len,
194                                   tBTIF_COPY_CBACK* p_copy_cback) {
195   tBTIF_CONTEXT_SWITCH_CBACK* p_msg = (tBTIF_CONTEXT_SWITCH_CBACK*)osi_malloc(
196       sizeof(tBTIF_CONTEXT_SWITCH_CBACK) + param_len);
197 
198   BTIF_TRACE_VERBOSE("btif_transfer_context event %d, len %d", event,
199                      param_len);
200 
201   /* allocate and send message that will be executed in btif context */
202   p_msg->hdr.event = BT_EVT_CONTEXT_SWITCH_EVT; /* internal event */
203   p_msg->p_cb = p_cback;
204 
205   p_msg->event = event; /* callback event */
206 
207   /* check if caller has provided a copy callback to do the deep copy */
208   if (p_copy_cback) {
209     p_copy_cback(event, p_msg->p_param, p_params);
210   } else if (p_params) {
211     memcpy(p_msg->p_param, p_params, param_len); /* callback parameter data */
212   }
213 
214   btif_sendmsg(p_msg);
215 
216   return BT_STATUS_SUCCESS;
217 }
218 
219 /**
220  * This function posts a task into the btif message loop, that executes it in
221  * the JNI message loop.
222  **/
do_in_jni_thread(const base::Location & from_here,base::OnceClosure task)223 bt_status_t do_in_jni_thread(const base::Location& from_here,
224                              base::OnceClosure task) {
225   if (!jni_thread.DoInThread(from_here, std::move(task))) {
226     LOG(ERROR) << __func__ << ": Post task to task runner failed!";
227     return BT_STATUS_FAIL;
228   }
229   return BT_STATUS_SUCCESS;
230 }
231 
do_in_jni_thread(base::OnceClosure task)232 bt_status_t do_in_jni_thread(base::OnceClosure task) {
233   return do_in_jni_thread(FROM_HERE, std::move(task));
234 }
235 
is_on_jni_thread()236 bool is_on_jni_thread() {
237   return jni_thread.GetThreadId() == PlatformThread::CurrentId();
238 }
239 
get_jni_message_loop()240 base::MessageLoop* get_jni_message_loop() { return jni_thread.message_loop(); }
241 
242 /*******************************************************************************
243  *
244  * Function         btif_is_dut_mode
245  *
246  * Description      checks if BTIF is currently in DUT mode
247  *
248  * Returns          true if test mode, otherwise false
249  *
250  ******************************************************************************/
251 
btif_is_dut_mode()252 bool btif_is_dut_mode() { return btif_dut_mode == 1; }
253 
254 /*******************************************************************************
255  *
256  * Function         btif_is_enabled
257  *
258  * Description      checks if main adapter is fully enabled
259  *
260  * Returns          1 if fully enabled, otherwize 0
261  *
262  ******************************************************************************/
263 
btif_is_enabled(void)264 int btif_is_enabled(void) {
265   return ((!btif_is_dut_mode()) &&
266           (stack_manager_get_interface()->get_stack_is_running()));
267 }
268 
btif_init_ok(UNUSED_ATTR uint16_t event,UNUSED_ATTR char * p_param)269 void btif_init_ok(UNUSED_ATTR uint16_t event, UNUSED_ATTR char* p_param) {
270   BTIF_TRACE_DEBUG("btif_task: received trigger stack init event");
271   btif_dm_load_ble_local_keys();
272   BTA_EnableBluetooth(bte_dm_evt);
273 }
274 
275 /*******************************************************************************
276  *
277  * Function         btif_task
278  *
279  * Description      BTIF task handler managing all messages being passed
280  *                  Bluetooth HAL and BTA.
281  *
282  * Returns          void
283  *
284  ******************************************************************************/
bt_jni_msg_ready(void * context)285 static void bt_jni_msg_ready(void* context) {
286   BT_HDR* p_msg = (BT_HDR*)context;
287 
288   BTIF_TRACE_VERBOSE("btif task fetched event %x", p_msg->event);
289 
290   switch (p_msg->event) {
291     case BT_EVT_CONTEXT_SWITCH_EVT:
292       btif_context_switched(p_msg);
293       break;
294     default:
295       BTIF_TRACE_ERROR("unhandled btif event (%d)", p_msg->event & BT_EVT_MASK);
296       break;
297   }
298   osi_free(p_msg);
299 }
300 
301 /*******************************************************************************
302  *
303  * Function         btif_sendmsg
304  *
305  * Description      Sends msg to BTIF task
306  *
307  * Returns          void
308  *
309  ******************************************************************************/
310 
btif_sendmsg(void * p_msg)311 void btif_sendmsg(void* p_msg) {
312   do_in_jni_thread(base::Bind(&bt_jni_msg_ready, p_msg));
313 }
314 
315 /*******************************************************************************
316  *
317  * Function         btif_init_bluetooth
318  *
319  * Description      Creates BTIF task and prepares BT scheduler for startup
320  *
321  * Returns          bt_status_t
322  *
323  ******************************************************************************/
btif_init_bluetooth()324 bt_status_t btif_init_bluetooth() {
325   LOG_INFO(LOG_TAG, "%s entered", __func__);
326   exit_manager = new base::AtExitManager();
327   bte_main_boot_entry();
328   jni_thread.StartUp();
329   jni_thread.DoInThread(FROM_HERE, base::Bind(btif_jni_associate));
330   LOG_INFO(LOG_TAG, "%s finished", __func__);
331   return BT_STATUS_SUCCESS;
332 }
333 
334 /*******************************************************************************
335  *
336  * Function         btif_enable_bluetooth_evt
337  *
338  * Description      Event indicating bluetooth enable is completed
339  *                  Notifies HAL user with updated adapter state
340  *
341  * Returns          void
342  *
343  ******************************************************************************/
344 
btif_enable_bluetooth_evt(tBTA_STATUS status)345 void btif_enable_bluetooth_evt(tBTA_STATUS status) {
346   LOG_INFO(LOG_TAG, "%s entered: status %d", __func__, status);
347 
348   /* Fetch the local BD ADDR */
349   RawAddress local_bd_addr = *controller_get_interface()->get_address();
350 
351   std::string bdstr = local_bd_addr.ToString();
352 
353   char val[PROPERTY_VALUE_MAX] = "";
354   int val_size = 0;
355   if ((btif_config_get_str("Adapter", "Address", val, &val_size) == 0) ||
356       strcmp(bdstr.c_str(), val) == 0) {
357     // This address is not present in the config file, save it there.
358     BTIF_TRACE_WARNING("%s: Saving the Adapter Address", __func__);
359     btif_config_set_str("Adapter", "Address", bdstr.c_str());
360     btif_config_save();
361 
362     // fire HAL callback for property change
363     bt_property_t prop;
364     prop.type = BT_PROPERTY_BDADDR;
365     prop.val = (void*)&local_bd_addr;
366     prop.len = sizeof(RawAddress);
367     HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, BT_STATUS_SUCCESS, 1,
368               &prop);
369   }
370 
371   bte_main_postload_cfg();
372 
373   /* callback to HAL */
374   if (status == BTA_SUCCESS) {
375     uid_set = uid_set_create();
376 
377     btif_dm_init(uid_set);
378 
379     /* init rfcomm & l2cap api */
380     btif_sock_init(uid_set);
381 
382     /* init pan */
383     btif_pan_init();
384 
385     /* load did configuration */
386     bte_load_did_conf(BTE_DID_CONF_FILE);
387 
388 #ifdef BTIF_DM_OOB_TEST
389     btif_dm_load_local_oob();
390 #endif
391 
392     future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
393   } else {
394     /* cleanup rfcomm & l2cap api */
395     btif_sock_cleanup();
396 
397     btif_pan_cleanup();
398 
399     future_ready(stack_manager_get_hack_future(), FUTURE_FAIL);
400   }
401 
402   LOG_INFO(LOG_TAG, "%s finished", __func__);
403 }
404 
405 /*******************************************************************************
406  *
407  * Function         btif_disable_bluetooth
408  *
409  * Description      Inititates shutdown of Bluetooth system.
410  *                  Any active links will be dropped and device entering
411  *                  non connectable/discoverable mode
412  *
413  * Returns          void
414  *
415  ******************************************************************************/
btif_disable_bluetooth()416 bt_status_t btif_disable_bluetooth() {
417   LOG_INFO(LOG_TAG, "%s entered", __func__);
418 
419   do_in_main_thread(FROM_HERE, base::Bind(&btm_ble_multi_adv_cleanup));
420   // TODO(jpawlowski): this should do whole BTA_VendorCleanup(), but it would
421   // kill the stack now.
422 
423   btif_dm_on_disable();
424   /* cleanup rfcomm & l2cap api */
425   btif_sock_cleanup();
426   btif_pan_cleanup();
427   BTA_DisableBluetooth();
428 
429   LOG_INFO(LOG_TAG, "%s finished", __func__);
430 
431   return BT_STATUS_SUCCESS;
432 }
433 
434 /*******************************************************************************
435  *
436  * Function         btif_disable_bluetooth_evt
437  *
438  * Description      Event notifying BT disable is now complete.
439  *                  Terminates main stack tasks and notifies HAL
440  *                  user with updated BT state.
441  *
442  * Returns          void
443  *
444  ******************************************************************************/
445 
btif_disable_bluetooth_evt()446 void btif_disable_bluetooth_evt() {
447   LOG_INFO(LOG_TAG, "%s entered", __func__);
448 
449   bte_main_disable();
450 
451   /* callback to HAL */
452   future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
453 
454   LOG_INFO(LOG_TAG, "%s finished", __func__);
455 }
456 
457 /*******************************************************************************
458  *
459  * Function         btif_cleanup_bluetooth
460  *
461  * Description      Cleanup BTIF state.
462  *
463  * Returns          void
464  *
465  ******************************************************************************/
466 
btif_cleanup_bluetooth()467 bt_status_t btif_cleanup_bluetooth() {
468   LOG_INFO(LOG_TAG, "%s entered", __func__);
469   do_in_main_thread(FROM_HERE, base::Bind(&BTA_VendorCleanup));
470   btif_dm_cleanup();
471   jni_thread.DoInThread(FROM_HERE, base::BindOnce(btif_jni_disassociate));
472   btif_queue_release();
473   jni_thread.ShutDown();
474   bte_main_cleanup();
475   delete exit_manager;
476   exit_manager = nullptr;
477   btif_dut_mode = 0;
478   LOG_INFO(LOG_TAG, "%s finished", __func__);
479   return BT_STATUS_SUCCESS;
480 }
481 
482 /*******************************************************************************
483  *
484  * Function         btif_dut_mode_cback
485  *
486  * Description     Callback invoked on completion of vendor specific test mode
487  *                 command
488  *
489  * Returns          None
490  *
491  ******************************************************************************/
btif_dut_mode_cback(UNUSED_ATTR tBTM_VSC_CMPL * p)492 static void btif_dut_mode_cback(UNUSED_ATTR tBTM_VSC_CMPL* p) {
493   /* For now nothing to be done. */
494 }
495 
496 /*******************************************************************************
497  *
498  * Function         btif_dut_mode_configure
499  *
500  * Description      Configure Test Mode - 'enable' to 1 puts the device in test
501  *                       mode and 0 exits test mode
502  *
503  * Returns          BT_STATUS_SUCCESS on success
504  *
505  ******************************************************************************/
btif_dut_mode_configure(uint8_t enable)506 bt_status_t btif_dut_mode_configure(uint8_t enable) {
507   BTIF_TRACE_DEBUG("%s", __func__);
508 
509   if (!stack_manager_get_interface()->get_stack_is_running()) {
510     BTIF_TRACE_ERROR("btif_dut_mode_configure : Bluetooth not enabled");
511     return BT_STATUS_NOT_READY;
512   }
513 
514   btif_dut_mode = enable;
515   if (enable == 1) {
516     BTA_EnableTestMode();
517   } else {
518     BTA_DisableTestMode();
519   }
520   return BT_STATUS_SUCCESS;
521 }
522 
523 /*******************************************************************************
524  *
525  * Function         btif_dut_mode_send
526  *
527  * Description     Sends a HCI Vendor specific command to the controller
528  *
529  * Returns          BT_STATUS_SUCCESS on success
530  *
531  ******************************************************************************/
btif_dut_mode_send(uint16_t opcode,uint8_t * buf,uint8_t len)532 bt_status_t btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
533   /* TODO: Check that opcode is a vendor command group */
534   BTIF_TRACE_DEBUG("%s", __func__);
535   if (!btif_is_dut_mode()) {
536     BTIF_TRACE_ERROR("Bluedroid HAL needs to be init with test_mode set to 1.");
537     return BT_STATUS_FAIL;
538   }
539   BTM_VendorSpecificCommand(opcode, len, buf, btif_dut_mode_cback);
540   return BT_STATUS_SUCCESS;
541 }
542 
543 /*****************************************************************************
544  *
545  *   btif api adapter property functions
546  *
547  ****************************************************************************/
548 
btif_in_get_adapter_properties(void)549 static bt_status_t btif_in_get_adapter_properties(void) {
550   const static uint32_t NUM_ADAPTER_PROPERTIES = 8;
551   bt_property_t properties[NUM_ADAPTER_PROPERTIES];
552   uint32_t num_props = 0;
553 
554   RawAddress addr;
555   bt_bdname_t name;
556   bt_scan_mode_t mode;
557   uint32_t disc_timeout;
558   RawAddress bonded_devices[BTM_SEC_MAX_DEVICE_RECORDS];
559   Uuid local_uuids[BT_MAX_NUM_UUIDS];
560   bt_status_t status;
561   bt_io_cap_t local_bt_io_cap;
562   bt_io_cap_t local_bt_io_cap_ble;
563 
564   /* RawAddress */
565   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDADDR,
566                              sizeof(addr), &addr);
567   status = btif_storage_get_adapter_property(&properties[num_props]);
568   // Add BT_PROPERTY_BDADDR property into list only when successful.
569   // Otherwise, skip this property entry.
570   if (status == BT_STATUS_SUCCESS) {
571     num_props++;
572   }
573 
574   /* BD_NAME */
575   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDNAME,
576                              sizeof(name), &name);
577   btif_storage_get_adapter_property(&properties[num_props]);
578   num_props++;
579 
580   /* SCAN_MODE */
581   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
582                              BT_PROPERTY_ADAPTER_SCAN_MODE, sizeof(mode),
583                              &mode);
584   btif_storage_get_adapter_property(&properties[num_props]);
585   num_props++;
586 
587   /* DISC_TIMEOUT */
588   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
589                              BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT,
590                              sizeof(disc_timeout), &disc_timeout);
591   btif_storage_get_adapter_property(&properties[num_props]);
592   num_props++;
593 
594   /* BONDED_DEVICES */
595   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
596                              BT_PROPERTY_ADAPTER_BONDED_DEVICES,
597                              sizeof(bonded_devices), bonded_devices);
598   btif_storage_get_adapter_property(&properties[num_props]);
599   num_props++;
600 
601   /* LOCAL UUIDs */
602   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_UUIDS,
603                              sizeof(local_uuids), local_uuids);
604   btif_storage_get_adapter_property(&properties[num_props]);
605   num_props++;
606 
607   /* LOCAL IO Capabilities */
608   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_LOCAL_IO_CAPS,
609                              sizeof(bt_io_cap_t), &local_bt_io_cap);
610   btif_storage_get_adapter_property(&properties[num_props]);
611   num_props++;
612 
613   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
614                              BT_PROPERTY_LOCAL_IO_CAPS_BLE, sizeof(bt_io_cap_t),
615                              &local_bt_io_cap_ble);
616   btif_storage_get_adapter_property(&properties[num_props]);
617   num_props++;
618 
619   HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, BT_STATUS_SUCCESS, num_props,
620             properties);
621 
622   return BT_STATUS_SUCCESS;
623 }
624 
btif_in_get_remote_device_properties(RawAddress * bd_addr)625 static bt_status_t btif_in_get_remote_device_properties(RawAddress* bd_addr) {
626   bt_property_t remote_properties[8];
627   uint32_t num_props = 0;
628 
629   bt_bdname_t name, alias;
630   uint32_t cod, devtype;
631   Uuid remote_uuids[BT_MAX_NUM_UUIDS];
632 
633   memset(remote_properties, 0, sizeof(remote_properties));
634   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_BDNAME,
635                              sizeof(name), &name);
636   btif_storage_get_remote_device_property(bd_addr,
637                                           &remote_properties[num_props]);
638   num_props++;
639 
640   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
641                              BT_PROPERTY_REMOTE_FRIENDLY_NAME, sizeof(alias),
642                              &alias);
643   btif_storage_get_remote_device_property(bd_addr,
644                                           &remote_properties[num_props]);
645   num_props++;
646 
647   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
648                              BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
649   btif_storage_get_remote_device_property(bd_addr,
650                                           &remote_properties[num_props]);
651   num_props++;
652 
653   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
654                              BT_PROPERTY_TYPE_OF_DEVICE, sizeof(devtype),
655                              &devtype);
656   btif_storage_get_remote_device_property(bd_addr,
657                                           &remote_properties[num_props]);
658   num_props++;
659 
660   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_UUIDS,
661                              sizeof(remote_uuids), remote_uuids);
662   btif_storage_get_remote_device_property(bd_addr,
663                                           &remote_properties[num_props]);
664   num_props++;
665 
666   HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, BT_STATUS_SUCCESS,
667             bd_addr, num_props, remote_properties);
668 
669   return BT_STATUS_SUCCESS;
670 }
671 
672 /*******************************************************************************
673  *
674  * Function         execute_storage_request
675  *
676  * Description      Executes adapter storage request in BTIF context
677  *
678  * Returns          bt_status_t
679  *
680  ******************************************************************************/
681 
execute_storage_request(uint16_t event,char * p_param)682 static void execute_storage_request(uint16_t event, char* p_param) {
683   bt_status_t status = BT_STATUS_SUCCESS;
684 
685   BTIF_TRACE_EVENT("execute storage request event : %d", event);
686 
687   switch (event) {
688     case BTIF_CORE_STORAGE_ADAPTER_WRITE: {
689       btif_storage_req_t* p_req = (btif_storage_req_t*)p_param;
690       bt_property_t* p_prop = &(p_req->write_req.prop);
691       BTIF_TRACE_EVENT("type: %d, len %d, 0x%x", p_prop->type, p_prop->len,
692                        p_prop->val);
693 
694       status = btif_storage_set_adapter_property(p_prop);
695       HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, 1, p_prop);
696     } break;
697 
698     case BTIF_CORE_STORAGE_ADAPTER_READ: {
699       btif_storage_req_t* p_req = (btif_storage_req_t*)p_param;
700       char buf[512];
701       bt_property_t prop;
702       prop.type = p_req->read_req.type;
703       prop.val = (void*)buf;
704       prop.len = sizeof(buf);
705       if (prop.type == BT_PROPERTY_LOCAL_LE_FEATURES) {
706         tBTM_BLE_VSC_CB cmn_vsc_cb;
707         bt_local_le_features_t local_le_features;
708 
709         /* LE features are not stored in storage. Should be retrived from stack
710          */
711         BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
712         local_le_features.local_privacy_enabled = BTM_BleLocalPrivacyEnabled();
713 
714         prop.len = sizeof(bt_local_le_features_t);
715         if (cmn_vsc_cb.filter_support == 1)
716           local_le_features.max_adv_filter_supported = cmn_vsc_cb.max_filter;
717         else
718           local_le_features.max_adv_filter_supported = 0;
719         local_le_features.max_adv_instance = cmn_vsc_cb.adv_inst_max;
720         local_le_features.max_irk_list_size = cmn_vsc_cb.max_irk_list_sz;
721         local_le_features.rpa_offload_supported = cmn_vsc_cb.rpa_offloading;
722         local_le_features.scan_result_storage_size =
723             cmn_vsc_cb.tot_scan_results_strg;
724         local_le_features.activity_energy_info_supported =
725             cmn_vsc_cb.energy_support;
726         local_le_features.version_supported = cmn_vsc_cb.version_supported;
727         local_le_features.total_trackable_advertisers =
728             cmn_vsc_cb.total_trackable_advertisers;
729 
730         local_le_features.extended_scan_support =
731             cmn_vsc_cb.extended_scan_support > 0;
732         local_le_features.debug_logging_supported =
733             cmn_vsc_cb.debug_logging_supported > 0;
734         memcpy(prop.val, &local_le_features, prop.len);
735       } else {
736         status = btif_storage_get_adapter_property(&prop);
737       }
738       HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, 1, &prop);
739     } break;
740 
741     case BTIF_CORE_STORAGE_ADAPTER_READ_ALL: {
742       status = btif_in_get_adapter_properties();
743     } break;
744 
745     case BTIF_CORE_STORAGE_NOTIFY_STATUS: {
746       HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, 0, NULL);
747     } break;
748 
749     default:
750       BTIF_TRACE_ERROR("%s invalid event id (%d)", __func__, event);
751       break;
752   }
753 }
754 
execute_storage_remote_request(uint16_t event,char * p_param)755 static void execute_storage_remote_request(uint16_t event, char* p_param) {
756   bt_status_t status = BT_STATUS_FAIL;
757   bt_property_t prop;
758 
759   BTIF_TRACE_EVENT("execute storage remote request event : %d", event);
760 
761   switch (event) {
762     case BTIF_CORE_STORAGE_REMOTE_READ: {
763       char buf[1024];
764       btif_storage_req_t* p_req = (btif_storage_req_t*)p_param;
765       prop.type = p_req->read_req.type;
766       prop.val = (void*)buf;
767       prop.len = sizeof(buf);
768 
769       status = btif_storage_get_remote_device_property(
770           &(p_req->read_req.bd_addr), &prop);
771       HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, status,
772                 &(p_req->read_req.bd_addr), 1, &prop);
773     } break;
774     case BTIF_CORE_STORAGE_REMOTE_WRITE: {
775       btif_storage_req_t* p_req = (btif_storage_req_t*)p_param;
776       status = btif_storage_set_remote_device_property(
777           &(p_req->write_req.bd_addr), &(p_req->write_req.prop));
778     } break;
779     case BTIF_CORE_STORAGE_REMOTE_READ_ALL: {
780       btif_storage_req_t* p_req = (btif_storage_req_t*)p_param;
781       btif_in_get_remote_device_properties(&p_req->read_req.bd_addr);
782     } break;
783   }
784 }
785 
btif_adapter_properties_evt(bt_status_t status,uint32_t num_props,bt_property_t * p_props)786 void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props,
787                                  bt_property_t* p_props) {
788   HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, num_props, p_props);
789 }
btif_remote_properties_evt(bt_status_t status,RawAddress * remote_addr,uint32_t num_props,bt_property_t * p_props)790 void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr,
791                                 uint32_t num_props, bt_property_t* p_props) {
792   HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, status, remote_addr,
793             num_props, p_props);
794 }
795 
796 /*******************************************************************************
797  *
798  * Function         btif_in_storage_request_copy_cb
799  *
800  * Description     Switch context callback function to perform the deep copy for
801  *                 both the adapter and remote_device property API
802  *
803  * Returns          None
804  *
805  ******************************************************************************/
btif_in_storage_request_copy_cb(uint16_t event,char * p_new_buf,char * p_old_buf)806 static void btif_in_storage_request_copy_cb(uint16_t event, char* p_new_buf,
807                                             char* p_old_buf) {
808   btif_storage_req_t* new_req = (btif_storage_req_t*)p_new_buf;
809   btif_storage_req_t* old_req = (btif_storage_req_t*)p_old_buf;
810 
811   BTIF_TRACE_EVENT("%s", __func__);
812   switch (event) {
813     case BTIF_CORE_STORAGE_REMOTE_WRITE:
814     case BTIF_CORE_STORAGE_ADAPTER_WRITE: {
815       new_req->write_req.bd_addr = old_req->write_req.bd_addr;
816       /* Copy the member variables one at a time */
817       new_req->write_req.prop.type = old_req->write_req.prop.type;
818       new_req->write_req.prop.len = old_req->write_req.prop.len;
819 
820       new_req->write_req.prop.val =
821           (uint8_t*)(p_new_buf + sizeof(btif_storage_req_t));
822       memcpy(new_req->write_req.prop.val, old_req->write_req.prop.val,
823              old_req->write_req.prop.len);
824     } break;
825   }
826 }
827 
828 /*******************************************************************************
829  *
830  * Function         btif_get_adapter_properties
831  *
832  * Description      Fetch all available properties (local & remote)
833  *
834  * Returns          bt_status_t
835  *
836  ******************************************************************************/
837 
btif_get_adapter_properties(void)838 bt_status_t btif_get_adapter_properties(void) {
839   BTIF_TRACE_EVENT("%s", __func__);
840 
841   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
842 
843   return btif_transfer_context(execute_storage_request,
844                                BTIF_CORE_STORAGE_ADAPTER_READ_ALL, NULL, 0,
845                                NULL);
846 }
847 
848 /*******************************************************************************
849  *
850  * Function         btif_get_adapter_property
851  *
852  * Description      Fetches property value from local cache
853  *
854  * Returns          bt_status_t
855  *
856  ******************************************************************************/
857 
btif_get_adapter_property(bt_property_type_t type)858 bt_status_t btif_get_adapter_property(bt_property_type_t type) {
859   btif_storage_req_t req;
860 
861   BTIF_TRACE_EVENT("%s %d", __func__, type);
862 
863   /* Allow get_adapter_property only for BDADDR and BDNAME if BT is disabled */
864   if (!btif_is_enabled() && (type != BT_PROPERTY_BDADDR) &&
865       (type != BT_PROPERTY_BDNAME) && (type != BT_PROPERTY_CLASS_OF_DEVICE))
866     return BT_STATUS_NOT_READY;
867 
868   req.read_req.bd_addr = RawAddress::kEmpty;
869   req.read_req.type = type;
870 
871   return btif_transfer_context(execute_storage_request,
872                                BTIF_CORE_STORAGE_ADAPTER_READ, (char*)&req,
873                                sizeof(btif_storage_req_t), NULL);
874 }
875 
876 /*******************************************************************************
877  *
878  * Function         btif_set_adapter_property
879  *
880  * Description      Updates core stack with property value and stores it in
881  *                  local cache
882  *
883  * Returns          bt_status_t
884  *
885  ******************************************************************************/
886 
btif_set_adapter_property(const bt_property_t * property)887 bt_status_t btif_set_adapter_property(const bt_property_t* property) {
888   btif_storage_req_t req;
889   bt_status_t status = BT_STATUS_SUCCESS;
890   int storage_req_id = BTIF_CORE_STORAGE_NOTIFY_STATUS; /* default */
891   char bd_name[BTM_MAX_LOC_BD_NAME_LEN + 1];
892   uint16_t name_len = 0;
893 
894   BTIF_TRACE_EVENT("btif_set_adapter_property type: %d, len %d, 0x%x",
895                    property->type, property->len, property->val);
896 
897   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
898 
899   switch (property->type) {
900     case BT_PROPERTY_BDNAME: {
901       name_len = property->len > BTM_MAX_LOC_BD_NAME_LEN
902                      ? BTM_MAX_LOC_BD_NAME_LEN
903                      : property->len;
904       memcpy(bd_name, property->val, name_len);
905       bd_name[name_len] = '\0';
906 
907       BTIF_TRACE_EVENT("set property name : %s", (char*)bd_name);
908 
909       BTA_DmSetDeviceName((char*)bd_name);
910 
911       storage_req_id = BTIF_CORE_STORAGE_ADAPTER_WRITE;
912     } break;
913 
914     case BT_PROPERTY_ADAPTER_SCAN_MODE: {
915       bt_scan_mode_t mode = *(bt_scan_mode_t*)property->val;
916       tBTA_DM_DISC disc_mode;
917       tBTA_DM_CONN conn_mode;
918 
919       switch (mode) {
920         case BT_SCAN_MODE_NONE:
921           disc_mode = BTA_DM_NON_DISC;
922           conn_mode = BTA_DM_NON_CONN;
923           break;
924 
925         case BT_SCAN_MODE_CONNECTABLE:
926           disc_mode = BTA_DM_NON_DISC;
927           conn_mode = BTA_DM_CONN;
928           break;
929 
930         case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE:
931           disc_mode = BTA_DM_GENERAL_DISC;
932           conn_mode = BTA_DM_CONN;
933           break;
934 
935         default:
936           BTIF_TRACE_ERROR("invalid scan mode (0x%x)", mode);
937           return BT_STATUS_PARM_INVALID;
938       }
939 
940       BTIF_TRACE_EVENT("set property scan mode : %x", mode);
941 
942       BTA_DmSetVisibility(disc_mode, conn_mode, BTA_DM_IGNORE, BTA_DM_IGNORE);
943 
944       storage_req_id = BTIF_CORE_STORAGE_ADAPTER_WRITE;
945     } break;
946     case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT: {
947       /* Nothing to do beside store the value in NV.  Java
948          will change the SCAN_MODE property after setting timeout,
949          if required */
950       storage_req_id = BTIF_CORE_STORAGE_ADAPTER_WRITE;
951     } break;
952     case BT_PROPERTY_CLASS_OF_DEVICE: {
953       DEV_CLASS dev_class;
954       memcpy(dev_class, property->val, DEV_CLASS_LEN);
955 
956       BTIF_TRACE_EVENT("set property dev_class : 0x%02x%02x%02x", dev_class[0],
957                        dev_class[1], dev_class[2]);
958 
959       BTM_SetDeviceClass(dev_class);
960     } break;
961     case BT_PROPERTY_BDADDR:
962     case BT_PROPERTY_UUIDS:
963     case BT_PROPERTY_ADAPTER_BONDED_DEVICES:
964     case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
965       /* no write support through HAL, these properties are only populated from
966        * BTA events */
967       status = BT_STATUS_FAIL;
968       break;
969     case BT_PROPERTY_LOCAL_IO_CAPS:
970     case BT_PROPERTY_LOCAL_IO_CAPS_BLE: {
971       // Changing IO Capability of stack at run-time is not currently supported.
972       // This call changes the stored value which will affect the stack next
973       // time it starts up.
974       storage_req_id = BTIF_CORE_STORAGE_ADAPTER_WRITE;
975     } break;
976     default:
977       BTIF_TRACE_ERROR("btif_get_adapter_property : invalid type %d",
978                        property->type);
979       status = BT_STATUS_FAIL;
980       break;
981   }
982 
983   if (storage_req_id != BTIF_CORE_STORAGE_NO_ACTION) {
984     /* pass on to storage for updating local database */
985 
986     req.write_req.bd_addr = RawAddress::kEmpty;
987     memcpy(&(req.write_req.prop), property, sizeof(bt_property_t));
988 
989     return btif_transfer_context(execute_storage_request, storage_req_id,
990                                  (char*)&req,
991                                  sizeof(btif_storage_req_t) + property->len,
992                                  btif_in_storage_request_copy_cb);
993   }
994 
995   return status;
996 }
997 
998 /*******************************************************************************
999  *
1000  * Function         btif_get_remote_device_property
1001  *
1002  * Description      Fetches the remote device property from the NVRAM
1003  *
1004  * Returns          bt_status_t
1005  *
1006  ******************************************************************************/
btif_get_remote_device_property(RawAddress * remote_addr,bt_property_type_t type)1007 bt_status_t btif_get_remote_device_property(RawAddress* remote_addr,
1008                                             bt_property_type_t type) {
1009   btif_storage_req_t req;
1010 
1011   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
1012 
1013   req.read_req.bd_addr = *remote_addr;
1014   req.read_req.type = type;
1015   return btif_transfer_context(execute_storage_remote_request,
1016                                BTIF_CORE_STORAGE_REMOTE_READ, (char*)&req,
1017                                sizeof(btif_storage_req_t), NULL);
1018 }
1019 
1020 /*******************************************************************************
1021  *
1022  * Function         btif_get_remote_device_properties
1023  *
1024  * Description      Fetches all the remote device properties from NVRAM
1025  *
1026  * Returns          bt_status_t
1027  *
1028  ******************************************************************************/
btif_get_remote_device_properties(RawAddress * remote_addr)1029 bt_status_t btif_get_remote_device_properties(RawAddress* remote_addr) {
1030   btif_storage_req_t req;
1031 
1032   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
1033 
1034   req.read_req.bd_addr = *remote_addr;
1035   return btif_transfer_context(execute_storage_remote_request,
1036                                BTIF_CORE_STORAGE_REMOTE_READ_ALL, (char*)&req,
1037                                sizeof(btif_storage_req_t), NULL);
1038 }
1039 
1040 /*******************************************************************************
1041  *
1042  * Function         btif_set_remote_device_property
1043  *
1044  * Description      Writes the remote device property to NVRAM.
1045  *                  Currently, BT_PROPERTY_REMOTE_FRIENDLY_NAME is the only
1046  *                  remote device property that can be set
1047  *
1048  * Returns          bt_status_t
1049  *
1050  ******************************************************************************/
btif_set_remote_device_property(RawAddress * remote_addr,const bt_property_t * property)1051 bt_status_t btif_set_remote_device_property(RawAddress* remote_addr,
1052                                             const bt_property_t* property) {
1053   btif_storage_req_t req;
1054 
1055   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
1056 
1057   req.write_req.bd_addr = *remote_addr;
1058   memcpy(&(req.write_req.prop), property, sizeof(bt_property_t));
1059 
1060   return btif_transfer_context(execute_storage_remote_request,
1061                                BTIF_CORE_STORAGE_REMOTE_WRITE, (char*)&req,
1062                                sizeof(btif_storage_req_t) + property->len,
1063                                btif_in_storage_request_copy_cb);
1064 }
1065 
1066 /*******************************************************************************
1067  *
1068  * Function         btif_get_remote_service_record
1069  *
1070  * Description      Looks up the service matching uuid on the remote device
1071  *                  and fetches the SCN and service_name if the UUID is found
1072  *
1073  * Returns          bt_status_t
1074  *
1075  ******************************************************************************/
btif_get_remote_service_record(const RawAddress & remote_addr,const Uuid & uuid)1076 bt_status_t btif_get_remote_service_record(const RawAddress& remote_addr,
1077                                            const Uuid& uuid) {
1078   if (!btif_is_enabled()) return BT_STATUS_NOT_READY;
1079 
1080   return btif_dm_get_remote_service_record(remote_addr, uuid);
1081 }
1082 
1083 /*******************************************************************************
1084  *
1085  * Function         btif_get_enabled_services_mask
1086  *
1087  * Description      Fetches currently enabled services
1088  *
1089  * Returns          tBTA_SERVICE_MASK
1090  *
1091  ******************************************************************************/
1092 
btif_get_enabled_services_mask(void)1093 tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) {
1094   return btif_enabled_services;
1095 }
1096 
1097 /*******************************************************************************
1098  *
1099  * Function         btif_enable_service
1100  *
1101  * Description      Enables the service 'service_ID' to the service_mask.
1102  *                  Upon BT enable, BTIF core shall invoke the BTA APIs to
1103  *                  enable the profiles
1104  *
1105  * Returns          bt_status_t
1106  *
1107  ******************************************************************************/
btif_enable_service(tBTA_SERVICE_ID service_id)1108 bt_status_t btif_enable_service(tBTA_SERVICE_ID service_id) {
1109   tBTA_SERVICE_ID* p_id = &service_id;
1110 
1111   /* If BT is enabled, we need to switch to BTIF context and trigger the
1112    * enable for that profile
1113    *
1114    * Otherwise, we just set the flag. On BT_Enable, the DM will trigger
1115    * enable for the profiles that have been enabled */
1116 
1117   btif_enabled_services |= (1 << service_id);
1118 
1119   BTIF_TRACE_DEBUG("%s: current services:0x%x", __func__,
1120                    btif_enabled_services);
1121 
1122   if (btif_is_enabled()) {
1123     btif_transfer_context(btif_dm_execute_service_request,
1124                           BTIF_DM_ENABLE_SERVICE, (char*)p_id,
1125                           sizeof(tBTA_SERVICE_ID), NULL);
1126   }
1127 
1128   return BT_STATUS_SUCCESS;
1129 }
1130 /*******************************************************************************
1131  *
1132  * Function         btif_disable_service
1133  *
1134  * Description      Disables the service 'service_ID' to the service_mask.
1135  *                  Upon BT disable, BTIF core shall invoke the BTA APIs to
1136  *                  disable the profiles
1137  *
1138  * Returns          bt_status_t
1139  *
1140  ******************************************************************************/
btif_disable_service(tBTA_SERVICE_ID service_id)1141 bt_status_t btif_disable_service(tBTA_SERVICE_ID service_id) {
1142   tBTA_SERVICE_ID* p_id = &service_id;
1143 
1144   /* If BT is enabled, we need to switch to BTIF context and trigger the
1145    * disable for that profile so that the appropriate uuid_property_changed will
1146    * be triggerred. Otherwise, we just need to clear the service_id in the mask
1147    */
1148 
1149   btif_enabled_services &= (tBTA_SERVICE_MASK)(~(1 << service_id));
1150 
1151   BTIF_TRACE_DEBUG("%s: Current Services:0x%x", __func__,
1152                    btif_enabled_services);
1153 
1154   if (btif_is_enabled()) {
1155     btif_transfer_context(btif_dm_execute_service_request,
1156                           BTIF_DM_DISABLE_SERVICE, (char*)p_id,
1157                           sizeof(tBTA_SERVICE_ID), NULL);
1158   }
1159 
1160   return BT_STATUS_SUCCESS;
1161 }
1162 
btif_jni_associate()1163 static void btif_jni_associate() {
1164   BTIF_TRACE_DEBUG("%s Associating thread to JVM", __func__);
1165   HAL_CBACK(bt_hal_cbacks, thread_evt_cb, ASSOCIATE_JVM);
1166 }
1167 
btif_jni_disassociate()1168 static void btif_jni_disassociate() {
1169   BTIF_TRACE_DEBUG("%s Disassociating thread from JVM", __func__);
1170   HAL_CBACK(bt_hal_cbacks, thread_evt_cb, DISASSOCIATE_JVM);
1171   bt_hal_cbacks = NULL;
1172 }
1173