• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //  Copyright 2015 Google, Inc.
3 //
4 //  Licensed under the Apache License, Version 2.0 (the "License");
5 //  you may not use this file except in compliance with the License.
6 //  You may obtain a copy of the License at:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
10 //  Unless required by applicable law or agreed to in writing, software
11 //  distributed under the License is distributed on an "AS IS" BASIS,
12 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 //  See the License for the specific language governing permissions and
14 //  limitations under the License.
15 //
16 
17 #include "service/hal/bluetooth_interface.h"
18 
19 #include <mutex>
20 #include <shared_mutex>
21 
22 #include <base/logging.h>
23 #include <base/observer_list.h>
24 
25 #include "abstract_observer_list.h"
26 #include "service/logging_helpers.h"
27 
28 #include "btcore/include/hal_util.h"
29 
30 using std::lock_guard;
31 using std::unique_lock;
32 using std::shared_lock;
33 using std::mutex;
34 #if defined(OS_GENERIC) && defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 3500)
35 using shared_mutex_impl = std::shared_mutex;
36 #else
37 using shared_mutex_impl = std::shared_timed_mutex;
38 #endif
39 
40 namespace bluetooth {
41 namespace hal {
42 
43 namespace {
44 
45 // The global BluetoothInterface instance.
46 BluetoothInterface* g_bluetooth_interface = nullptr;
47 
48 // Mutex used by callbacks to access |g_interface|. If we initialize or clean it
49 // use unique_lock. If only accessing |g_interface| use shared lock.
50 // TODO(jpawlowski): this should be just shared_mutex, as we currently don't use
51 // timed methods. Change to shared_mutex when we upgrade to C++14
52 shared_mutex_impl g_instance_lock;
53 
54 // Helper for obtaining the observer list. This is forward declared here and
55 // defined below since it depends on BluetoothInterfaceImpl.
56 btbase::AbstractObserverList<BluetoothInterface::Observer>* GetObservers();
57 
58 #define FOR_EACH_BLUETOOTH_OBSERVER(func)  \
59   for (auto& observer : *GetObservers()) { \
60     observer.func;                         \
61   }
62 
63 #define VERIFY_INTERFACE_OR_RETURN()                                   \
64   do {                                                                 \
65     if (!g_bluetooth_interface) {                                      \
66       LOG(WARNING) << "Callback received while |g_interface| is NULL"; \
67       return;                                                          \
68     }                                                                  \
69   } while (0)
70 
AdapterStateChangedCallback(bt_state_t state)71 void AdapterStateChangedCallback(bt_state_t state) {
72   shared_lock<shared_mutex_impl> lock(g_instance_lock);
73   VERIFY_INTERFACE_OR_RETURN();
74   VLOG(1) << "Adapter state changed: " << BtStateText(state);
75   FOR_EACH_BLUETOOTH_OBSERVER(AdapterStateChangedCallback(state));
76 }
77 
AdapterPropertiesCallback(bt_status_t status,int num_properties,bt_property_t * properties)78 void AdapterPropertiesCallback(bt_status_t status, int num_properties,
79                                bt_property_t* properties) {
80   shared_lock<shared_mutex_impl> lock(g_instance_lock);
81   VERIFY_INTERFACE_OR_RETURN();
82   VLOG(1) << "Adapter properties changed - status: " << BtStatusText(status)
83           << ", num_properties: " << num_properties;
84   FOR_EACH_BLUETOOTH_OBSERVER(
85       AdapterPropertiesCallback(status, num_properties, properties));
86 }
87 
RemoteDevicePropertiesCallback(bt_status_t status,RawAddress * remote_bd_addr,int num_properties,bt_property_t * properties)88 void RemoteDevicePropertiesCallback(bt_status_t status,
89                                     RawAddress* remote_bd_addr,
90                                     int num_properties,
91                                     bt_property_t* properties) {
92   shared_lock<shared_mutex_impl> lock(g_instance_lock);
93   VERIFY_INTERFACE_OR_RETURN();
94   VLOG(1) << " Remote device properties changed - status: "
95           << BtStatusText(status)
96           << " - BD_ADDR: " << BtAddrString(remote_bd_addr)
97           << ", num_properties: " << num_properties;
98   FOR_EACH_BLUETOOTH_OBSERVER(RemoteDevicePropertiesCallback(
99       status, remote_bd_addr, num_properties, properties));
100 }
101 
DeviceFoundCallback(int num_properties,bt_property_t * properties)102 void DeviceFoundCallback(int num_properties, bt_property_t* properties) {
103   shared_lock<shared_mutex_impl> lock(g_instance_lock);
104   VERIFY_INTERFACE_OR_RETURN();
105   VLOG(1) << " Device found.";
106   FOR_EACH_BLUETOOTH_OBSERVER(DeviceFoundCallback(num_properties, properties));
107 }
108 
DiscoveryStateChangedCallback(bt_discovery_state_t state)109 void DiscoveryStateChangedCallback(bt_discovery_state_t state) {
110   shared_lock<shared_mutex_impl> lock(g_instance_lock);
111   VERIFY_INTERFACE_OR_RETURN();
112   VLOG(1) << "Discovery state changed - state: " << BtDiscoveryStateText(state);
113   FOR_EACH_BLUETOOTH_OBSERVER(DiscoveryStateChangedCallback(state));
114 }
115 
PinRequestCallback(RawAddress * remote_bd_addr,bt_bdname_t * bd_name,uint32_t cod,bool min_16_digit)116 void PinRequestCallback(RawAddress* remote_bd_addr, bt_bdname_t* bd_name,
117                         uint32_t cod, bool min_16_digit) {
118   shared_lock<shared_mutex_impl> lock(g_instance_lock);
119   VERIFY_INTERFACE_OR_RETURN();
120   VLOG(2) << __func__ << " - remote_bd_addr: " << remote_bd_addr
121           << " - bd_name: " << bd_name << " - cod: " << cod
122           << " - min_16_digit: " << min_16_digit;
123   FOR_EACH_BLUETOOTH_OBSERVER(
124       PinRequestCallback(remote_bd_addr, bd_name, cod, min_16_digit));
125 }
126 
SSPRequestCallback(RawAddress * remote_bd_addr,bt_bdname_t * bd_name,uint32_t cod,bt_ssp_variant_t pairing_variant,uint32_t pass_key)127 void SSPRequestCallback(RawAddress* remote_bd_addr, bt_bdname_t* bd_name,
128                         uint32_t cod, bt_ssp_variant_t pairing_variant,
129                         uint32_t pass_key) {
130   shared_lock<shared_mutex_impl> lock(g_instance_lock);
131   VERIFY_INTERFACE_OR_RETURN();
132   VLOG(2) << __func__ << " - remote_bd_addr: " << remote_bd_addr
133           << " - bd_name: " << bd_name << " - cod: " << cod
134           << " - pairing_variant: " << pairing_variant;
135   FOR_EACH_BLUETOOTH_OBSERVER(SSPRequestCallback(remote_bd_addr, bd_name, cod,
136                                                  pairing_variant, pass_key));
137 }
138 
BondStateChangedCallback(bt_status_t status,RawAddress * remote_bd_addr,bt_bond_state_t state)139 void BondStateChangedCallback(bt_status_t status, RawAddress* remote_bd_addr,
140                               bt_bond_state_t state) {
141   shared_lock<shared_mutex_impl> lock(g_instance_lock);
142   VERIFY_INTERFACE_OR_RETURN();
143   VLOG(2) << __func__ << " - remote_bd_addr: " << BtAddrString(remote_bd_addr)
144           << " - status: " << status << " - state: " << state;
145   FOR_EACH_BLUETOOTH_OBSERVER(
146       BondStateChangedCallback(status, remote_bd_addr, state));
147 }
148 
AclStateChangedCallback(bt_status_t status,RawAddress * remote_bd_addr,bt_acl_state_t state,bt_hci_error_code_t hci_reason)149 void AclStateChangedCallback(bt_status_t status, RawAddress* remote_bd_addr,
150                              bt_acl_state_t state, bt_hci_error_code_t hci_reason) {
151   shared_lock<shared_mutex_impl> lock(g_instance_lock);
152   VERIFY_INTERFACE_OR_RETURN();
153   CHECK(remote_bd_addr);
154   VLOG(1) << "Remote device ACL state changed - status: "
155           << BtStatusText(status)
156           << " - BD_ADDR: " << BtAddrString(remote_bd_addr) << " - state: "
157           << ((state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED")
158           << " - HCI_REASON: " << std::to_string(hci_reason);
159   FOR_EACH_BLUETOOTH_OBSERVER(
160       AclStateChangedCallback(status, *remote_bd_addr, state, hci_reason));
161 }
162 
ThreadEventCallback(bt_cb_thread_evt evt)163 void ThreadEventCallback(bt_cb_thread_evt evt) {
164   VLOG(1) << "ThreadEventCallback" << BtEventText(evt);
165 
166   // TODO(armansito): This callback is completely useless to us but btif borks
167   // out if this is not set. Consider making this optional.
168 }
169 
SetWakeAlarmCallout(uint64_t,bool,alarm_cb,void *)170 bool SetWakeAlarmCallout(uint64_t /* delay_millis */, bool /* should_wake */,
171                          alarm_cb /* cb */, void* /* data */) {
172   // TODO(armansito): According to sharvil@, this interface doesn't even need to
173   // exist and can be done entirely from within osi by interfacing directly with
174   // the kernel. Remove these stubs once that's fixed. (See http://b/23390297)
175   return false;
176 }
177 
AcquireWakeLockCallout(const char *)178 int AcquireWakeLockCallout(const char* /* lock_name */) {
179   // TODO(armansito): According to sharvil@, this interface doesn't even need to
180   // exist and can be done entirely from within osi by interfacing directly with
181   // the kernel. Remove these stubs once that's fixed. (See http://b/23390297)
182   // Lie here and return success so that enabling and disabling the controller
183   // works before this is properly implemented.
184   return BT_STATUS_SUCCESS;
185 }
186 
ReleaseWakeLockCallout(const char *)187 int ReleaseWakeLockCallout(const char* /* lock_name */) {
188   // TODO(armansito): According to sharvil@, this interface doesn't even need to
189   // exist and can be done entirely from within osi by interfacing directly with
190   // the kernel. Remove these stubs once that's fixed. (See http://b/23390297)
191   // Lie here and return success so that enabling and disabling the controller
192   // works before this is properly implemented.
193   return BT_STATUS_SUCCESS;
194 }
195 
LinkQualityReportCallback(uint64_t timestamp,int report_id,int rssi,int snr,int retransmission_count,int packets_not_receive_count,int negative_acknowledgement_count)196 void LinkQualityReportCallback(uint64_t timestamp, int report_id, int rssi,
197     int snr, int retransmission_count, int packets_not_receive_count,
198     int negative_acknowledgement_count) {
199   shared_lock<shared_mutex_impl> lock(g_instance_lock);
200   VERIFY_INTERFACE_OR_RETURN();
201   LOG(WARNING) << __func__ << " - timestamp: " << timestamp
202                << " - report_id: " << report_id << " - rssi: " << rssi
203                << " - snr: " << snr
204                << " - retransmission_count: " << retransmission_count
205                << " - packets_not_receive_count: " << packets_not_receive_count
206                << " - negative_acknowledgement_count: "
207                << negative_acknowledgement_count;
208   FOR_EACH_BLUETOOTH_OBSERVER(LinkQualityReportCallback(
209       timestamp, report_id, rssi, snr, retransmission_count,
210       packets_not_receive_count, negative_acknowledgement_count));
211 }
212 
213 // The HAL Bluetooth DM callbacks.
214 bt_callbacks_t bt_callbacks = {
215     sizeof(bt_callbacks_t),
216     AdapterStateChangedCallback,
217     AdapterPropertiesCallback,
218     RemoteDevicePropertiesCallback,
219     DeviceFoundCallback,
220     DiscoveryStateChangedCallback,
221     PinRequestCallback,
222     SSPRequestCallback,
223     BondStateChangedCallback,
224     AclStateChangedCallback,
225     ThreadEventCallback,
226     nullptr, /* dut_mode_recv_cb */
227     nullptr, /* le_test_mode_cb */
228     nullptr, /* energy_info_cb */
229     LinkQualityReportCallback,
230     nullptr /* generate_local_oob_data_cb */
231 };
232 
233 bt_os_callouts_t bt_os_callouts = {sizeof(bt_os_callouts_t),
234                                    SetWakeAlarmCallout, AcquireWakeLockCallout,
235                                    ReleaseWakeLockCallout};
236 
237 }  // namespace
238 
239 // BluetoothInterface implementation for production.
240 class BluetoothInterfaceImpl : public BluetoothInterface {
241  public:
BluetoothInterfaceImpl()242   BluetoothInterfaceImpl() : hal_iface_(nullptr) {}
243 
~BluetoothInterfaceImpl()244   ~BluetoothInterfaceImpl() override {
245     if (hal_iface_) hal_iface_->cleanup();
246   }
247 
248   // BluetoothInterface overrides.
AddObserver(Observer * observer)249   void AddObserver(Observer* observer) override {
250     shared_lock<shared_mutex_impl> lock(g_instance_lock);
251     observers_.AddObserver(observer);
252   }
253 
RemoveObserver(Observer * observer)254   void RemoveObserver(Observer* observer) override {
255     shared_lock<shared_mutex_impl> lock(g_instance_lock);
256     observers_.RemoveObserver(observer);
257   }
258 
GetHALInterface() const259   const bt_interface_t* GetHALInterface() const override { return hal_iface_; }
260 
GetHALCallbacks() const261   bt_callbacks_t* GetHALCallbacks() const override { return &bt_callbacks; }
262 
263   // Initialize the interface. This loads the shared Bluetooth library and sets
264   // up the callbacks.
Initialize()265   bool Initialize() {
266     // Load the Bluetooth shared library module.
267     const bt_interface_t* interface;
268     int status = hal_util_load_bt_library(&interface);
269     if (status) {
270       LOG(ERROR) << "Failed to open the Bluetooth module";
271       return false;
272     }
273 
274     hal_iface_ = interface;
275 
276     // Initialize the Bluetooth interface. Set up the adapter (Bluetooth DM) API
277     // callbacks.
278     status = hal_iface_->init(&bt_callbacks, false, false, 0, nullptr, false);
279     if (status != BT_STATUS_SUCCESS) {
280       LOG(ERROR) << "Failed to initialize Bluetooth stack";
281       return false;
282     }
283 
284     status = hal_iface_->set_os_callouts(&bt_os_callouts);
285     if (status != BT_STATUS_SUCCESS) {
286       LOG(ERROR) << "Failed to set up Bluetooth OS callouts";
287       return false;
288     }
289 
290     return true;
291   }
292 
observers()293   btbase::AbstractObserverList<Observer>* observers() { return &observers_; }
294 
295  private:
296   // List of observers that are interested in notifications from us. We're not
297   // using a base::ObserverListThreadSafe, which it posts observer events
298   // automatically on the origin threads, as we want to avoid that overhead and
299   // simply forward the events to the upper layer.
300   btbase::AbstractObserverList<Observer> observers_;
301 
302   // The HAL handle obtained from the shared library. We hold a weak reference
303   // to this since the actual data resides in the shared Bluetooth library.
304   const bt_interface_t* hal_iface_;
305 
306   DISALLOW_COPY_AND_ASSIGN(BluetoothInterfaceImpl);
307 };
308 
309 namespace {
310 
311 // Helper for obtaining the observer list from the global instance. This
312 // function is NOT thread safe.
GetObservers()313 btbase::AbstractObserverList<BluetoothInterface::Observer>* GetObservers() {
314   CHECK(g_bluetooth_interface);
315   return static_cast<BluetoothInterfaceImpl*>(g_bluetooth_interface)
316       ->observers();
317 }
318 
319 }  // namespace
320 
321 // Default observer implementations. These are provided so that the methods
322 // themselves are optional.
AdapterStateChangedCallback(bt_state_t)323 void BluetoothInterface::Observer::AdapterStateChangedCallback(
324     bt_state_t /* state*/) {
325   // Do nothing.
326 }
327 
AdapterPropertiesCallback(bt_status_t,int,bt_property_t *)328 void BluetoothInterface::Observer::AdapterPropertiesCallback(
329     bt_status_t /* status */, int /* num_properties */,
330     bt_property_t* /* properties */) {
331   // Do nothing.
332 }
333 
RemoteDevicePropertiesCallback(bt_status_t,RawAddress *,int,bt_property_t *)334 void BluetoothInterface::Observer::RemoteDevicePropertiesCallback(
335     bt_status_t /* status */, RawAddress* /* remote_bd_addr */,
336     int /* num_properties */, bt_property_t* /* properties */) {
337   // Do nothing.
338 }
339 
DeviceFoundCallback(int,bt_property_t *)340 void BluetoothInterface::Observer::DeviceFoundCallback(
341     int /* num_properties */, bt_property_t* /* properties */) {
342   // Do nothing.
343 }
344 
DiscoveryStateChangedCallback(bt_discovery_state_t)345 void BluetoothInterface::Observer::DiscoveryStateChangedCallback(
346     bt_discovery_state_t /* state */) {
347   // Do nothing.
348 }
349 
PinRequestCallback(RawAddress * remote_bd_addr,bt_bdname_t * bd_name,uint32_t cod,bool min_16_digit)350 void BluetoothInterface::Observer::PinRequestCallback(
351     RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod,
352     bool min_16_digit) {
353   // Do nothing.
354 }
355 
SSPRequestCallback(RawAddress * remote_bd_addr,bt_bdname_t * bd_name,uint32_t cod,bt_ssp_variant_t pairing_variant,uint32_t pass_key)356 void BluetoothInterface::Observer::SSPRequestCallback(
357     RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod,
358     bt_ssp_variant_t pairing_variant, uint32_t pass_key) {
359   // Do nothing.
360 }
361 
BondStateChangedCallback(bt_status_t status,RawAddress * remote_bd_addr,bt_bond_state_t state)362 void BluetoothInterface::Observer::BondStateChangedCallback(
363     bt_status_t status, RawAddress* remote_bd_addr, bt_bond_state_t state) {
364   // Do nothing.
365 }
366 
AclStateChangedCallback(bt_status_t,const RawAddress &,bt_acl_state_t,bt_hci_error_code_t)367 void BluetoothInterface::Observer::AclStateChangedCallback(
368     bt_status_t /* status */, const RawAddress& /* remote_bdaddr */,
369     bt_acl_state_t /* state */, bt_hci_error_code_t /* hci_reason */) {
370   // Do nothing.
371 }
372 
LinkQualityReportCallback(uint64_t,int,int,int,int,int,int)373 void BluetoothInterface::Observer::LinkQualityReportCallback(
374     uint64_t /* timestamp */, int /* report_id */, int /* rssi */,
375     int /* snr */, int /* retransmission_count */,
376     int /* packets_not_receive_count */,
377     int /* negative_acknowledgement_count */) {
378   // Do nothing.
379 }
380 
381 // static
Initialize()382 bool BluetoothInterface::Initialize() {
383   unique_lock<shared_mutex_impl> lock(g_instance_lock);
384   CHECK(!g_bluetooth_interface);
385 
386   std::unique_ptr<BluetoothInterfaceImpl> impl(new BluetoothInterfaceImpl());
387   if (!impl->Initialize()) {
388     LOG(ERROR) << "Failed to initialize BluetoothInterface";
389     return false;
390   }
391 
392   g_bluetooth_interface = impl.release();
393 
394   return true;
395 }
396 
397 // static
CleanUp()398 void BluetoothInterface::CleanUp() {
399   unique_lock<shared_mutex_impl> lock(g_instance_lock);
400   CHECK(g_bluetooth_interface);
401 
402   delete g_bluetooth_interface;
403   g_bluetooth_interface = nullptr;
404 }
405 
406 // static
IsInitialized()407 bool BluetoothInterface::IsInitialized() {
408   shared_lock<shared_mutex_impl> lock(g_instance_lock);
409 
410   return g_bluetooth_interface != nullptr;
411 }
412 
413 // static
Get()414 BluetoothInterface* BluetoothInterface::Get() {
415   shared_lock<shared_mutex_impl> lock(g_instance_lock);
416   CHECK(g_bluetooth_interface);
417   return g_bluetooth_interface;
418 }
419 
420 // static
InitializeForTesting(BluetoothInterface * test_instance)421 void BluetoothInterface::InitializeForTesting(
422     BluetoothInterface* test_instance) {
423   unique_lock<shared_mutex_impl> lock(g_instance_lock);
424   CHECK(test_instance);
425   CHECK(!g_bluetooth_interface);
426 
427   g_bluetooth_interface = test_instance;
428 }
429 
430 }  // namespace hal
431 }  // namespace bluetooth
432