1 /******************************************************************************
2  *
3  *  Copyright 2015 Google, Inc.
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 #define LOG_TAG "bt_osi_wakelock"
20 
21 #include "osi/include/wakelock.h"
22 
23 #include <bluetooth/log.h>
24 #include <fcntl.h>
25 #include <hardware/bluetooth.h>
26 #include <pthread.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include <mutex>
34 #include <string>
35 
36 #include "common/metrics.h"
37 #include "osi/include/osi.h"
38 
39 using bluetooth::common::BluetoothMetricsLogger;
40 using namespace bluetooth;
41 
42 static bt_os_callouts_t* wakelock_os_callouts = NULL;
43 static bool is_native = true;
44 
45 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
46 static const char* WAKE_LOCK_ID = "bluetooth_timer";
47 static const std::string DEFAULT_WAKE_LOCK_PATH = "/sys/power/wake_lock";
48 static const std::string DEFAULT_WAKE_UNLOCK_PATH = "/sys/power/wake_unlock";
49 static std::string wake_lock_path;
50 static std::string wake_unlock_path;
51 static ssize_t locked_id_len = -1;
52 static pthread_once_t initialized = PTHREAD_ONCE_INIT;
53 static int wake_lock_fd = INVALID_FD;
54 static int wake_unlock_fd = INVALID_FD;
55 
56 // Wakelock statistics for the "bluetooth_timer"
57 typedef struct {
58   bool is_acquired;
59   size_t acquired_count;
60   size_t released_count;
61   size_t acquired_errors;
62   size_t released_errors;
63   uint64_t min_acquired_interval_ms;
64   uint64_t max_acquired_interval_ms;
65   uint64_t last_acquired_interval_ms;
66   uint64_t total_acquired_interval_ms;
67   uint64_t last_acquired_timestamp_ms;
68   uint64_t last_released_timestamp_ms;
69   uint64_t last_reset_timestamp_ms;
70   int last_acquired_error;
71   int last_released_error;
72 } wakelock_stats_t;
73 
74 static wakelock_stats_t wakelock_stats;
75 
76 // This mutex ensures that the functions that update and dump the statistics
77 // are executed serially.
78 static std::mutex stats_mutex;
79 
80 static bt_status_t wakelock_acquire_callout(void);
81 static bt_status_t wakelock_acquire_native(void);
82 static bt_status_t wakelock_release_callout(void);
83 static bt_status_t wakelock_release_native(void);
84 static void wakelock_initialize(void);
85 static void wakelock_initialize_native(void);
86 static void reset_wakelock_stats(void);
87 static void update_wakelock_acquired_stats(bt_status_t acquired_status);
88 static void update_wakelock_released_stats(bt_status_t released_status);
89 
wakelock_set_os_callouts(bt_os_callouts_t * callouts)90 void wakelock_set_os_callouts(bt_os_callouts_t* callouts) {
91   wakelock_os_callouts = callouts;
92   is_native = (wakelock_os_callouts == NULL);
93   log::info("set to {}", (is_native) ? "native" : "non-native");
94 }
95 
wakelock_acquire(void)96 bool wakelock_acquire(void) {
97   pthread_once(&initialized, wakelock_initialize);
98 
99   bt_status_t status = BT_STATUS_FAIL;
100 
101   if (is_native) {
102     status = wakelock_acquire_native();
103   } else {
104     status = wakelock_acquire_callout();
105   }
106 
107   update_wakelock_acquired_stats(status);
108 
109   if (status != BT_STATUS_SUCCESS) {
110     log::error("unable to acquire wake lock: {}", status);
111   }
112 
113   return status == BT_STATUS_SUCCESS;
114 }
115 
wakelock_acquire_callout(void)116 static bt_status_t wakelock_acquire_callout(void) {
117   return static_cast<bt_status_t>(wakelock_os_callouts->acquire_wake_lock(WAKE_LOCK_ID));
118 }
119 
wakelock_acquire_native(void)120 static bt_status_t wakelock_acquire_native(void) {
121   if (wake_lock_fd == INVALID_FD) {
122     log::error("lock not acquired, invalid fd");
123     return BT_STATUS_PARM_INVALID;
124   }
125 
126   if (wake_unlock_fd == INVALID_FD) {
127     log::error("not acquiring lock: can't release lock");
128     return BT_STATUS_PARM_INVALID;
129   }
130 
131   long lock_name_len = strlen(WAKE_LOCK_ID);
132   locked_id_len = write(wake_lock_fd, WAKE_LOCK_ID, lock_name_len);
133   if (locked_id_len == -1) {
134     log::error("wake lock not acquired: {}", strerror(errno));
135     return BT_STATUS_WAKELOCK_ERROR;
136   } else if (locked_id_len < lock_name_len) {
137     // TODO (jamuraa): this is weird. maybe we should release and retry.
138     log::warn("wake lock truncated to {} chars", locked_id_len);
139   }
140   return BT_STATUS_SUCCESS;
141 }
142 
wakelock_release(void)143 bool wakelock_release(void) {
144   pthread_once(&initialized, wakelock_initialize);
145 
146   bt_status_t status = BT_STATUS_FAIL;
147 
148   if (is_native) {
149     status = wakelock_release_native();
150   } else {
151     status = wakelock_release_callout();
152   }
153 
154   update_wakelock_released_stats(status);
155 
156   return status == BT_STATUS_SUCCESS;
157 }
158 
wakelock_release_callout(void)159 static bt_status_t wakelock_release_callout(void) {
160   return static_cast<bt_status_t>(wakelock_os_callouts->release_wake_lock(WAKE_LOCK_ID));
161 }
162 
wakelock_release_native(void)163 static bt_status_t wakelock_release_native(void) {
164   if (wake_unlock_fd == INVALID_FD) {
165     log::error("lock not released, invalid fd");
166     return BT_STATUS_PARM_INVALID;
167   }
168 
169   ssize_t wrote_name_len = write(wake_unlock_fd, WAKE_LOCK_ID, locked_id_len);
170   if (wrote_name_len == -1) {
171     log::error("can't release wake lock: {}", strerror(errno));
172   } else if (wrote_name_len < locked_id_len) {
173     log::error("lock release only wrote {}, assuming released", wrote_name_len);
174   }
175   return BT_STATUS_SUCCESS;
176 }
177 
wakelock_initialize(void)178 static void wakelock_initialize(void) {
179   reset_wakelock_stats();
180 
181   if (is_native) {
182     wakelock_initialize_native();
183   }
184 }
185 
wakelock_initialize_native(void)186 static void wakelock_initialize_native(void) {
187   log::info("opening wake locks");
188 
189   if (wake_lock_path.empty()) {
190     wake_lock_path = DEFAULT_WAKE_LOCK_PATH;
191   }
192 
193   wake_lock_fd = open(wake_lock_path.c_str(), O_RDWR | O_CLOEXEC);
194   if (wake_lock_fd == INVALID_FD) {
195     log::error("can't open wake lock {}: {}", wake_lock_path, strerror(errno));
196   }
197 
198   if (wake_unlock_path.empty()) {
199     wake_unlock_path = DEFAULT_WAKE_UNLOCK_PATH;
200   }
201 
202   wake_unlock_fd = open(wake_unlock_path.c_str(), O_RDWR | O_CLOEXEC);
203   if (wake_unlock_fd == INVALID_FD) {
204     log::error("can't open wake unlock {}: {}", wake_unlock_path, strerror(errno));
205   }
206 }
207 
wakelock_cleanup(void)208 void wakelock_cleanup(void) {
209   if (wakelock_stats.is_acquired) {
210     log::error("releasing wake lock as part of cleanup");
211     wakelock_release();
212   }
213   wake_lock_path.clear();
214   wake_unlock_path.clear();
215   initialized = PTHREAD_ONCE_INIT;
216 }
217 
wakelock_set_paths(const char * lock_path,const char * unlock_path)218 void wakelock_set_paths(const char* lock_path, const char* unlock_path) {
219   if (lock_path) {
220     wake_lock_path = lock_path;
221   }
222 
223   if (unlock_path) {
224     wake_unlock_path = unlock_path;
225   }
226 }
227 
now_ms(void)228 static uint64_t now_ms(void) {
229   struct timespec ts;
230   if (clock_gettime(CLOCK_ID, &ts) == -1) {
231     log::error("unable to get current time: {}", strerror(errno));
232     return 0;
233   }
234 
235   return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
236 }
237 
238 // Reset the Bluetooth wakelock statistics.
239 // This function is thread-safe.
reset_wakelock_stats(void)240 static void reset_wakelock_stats(void) {
241   std::lock_guard<std::mutex> lock(stats_mutex);
242 
243   wakelock_stats.is_acquired = false;
244   wakelock_stats.acquired_count = 0;
245   wakelock_stats.released_count = 0;
246   wakelock_stats.acquired_errors = 0;
247   wakelock_stats.released_errors = 0;
248   wakelock_stats.min_acquired_interval_ms = 0;
249   wakelock_stats.max_acquired_interval_ms = 0;
250   wakelock_stats.last_acquired_interval_ms = 0;
251   wakelock_stats.total_acquired_interval_ms = 0;
252   wakelock_stats.last_acquired_timestamp_ms = 0;
253   wakelock_stats.last_released_timestamp_ms = 0;
254   wakelock_stats.last_reset_timestamp_ms = now_ms();
255 }
256 
257 //
258 // Update the Bluetooth acquire wakelock statistics.
259 //
260 // This function should be called every time when the wakelock is acquired.
261 // |acquired_status| is the status code that was return when the wakelock was
262 // acquired.
263 // This function is thread-safe.
264 //
update_wakelock_acquired_stats(bt_status_t acquired_status)265 static void update_wakelock_acquired_stats(bt_status_t acquired_status) {
266   const uint64_t just_now_ms = now_ms();
267 
268   std::lock_guard<std::mutex> lock(stats_mutex);
269 
270   if (acquired_status != BT_STATUS_SUCCESS) {
271     wakelock_stats.acquired_errors++;
272     wakelock_stats.last_acquired_error = acquired_status;
273   }
274 
275   if (wakelock_stats.is_acquired) {
276     return;
277   }
278 
279   wakelock_stats.is_acquired = true;
280   wakelock_stats.acquired_count++;
281   wakelock_stats.last_acquired_timestamp_ms = just_now_ms;
282 
283   BluetoothMetricsLogger::GetInstance()->LogWakeEvent(bluetooth::common::WAKE_EVENT_ACQUIRED, "",
284                                                       "", just_now_ms);
285 }
286 
287 //
288 // Update the Bluetooth release wakelock statistics.
289 //
290 // This function should be called every time when the wakelock is released.
291 // |released_status| is the status code that was return when the wakelock was
292 // released.
293 // This function is thread-safe.
294 //
update_wakelock_released_stats(bt_status_t released_status)295 static void update_wakelock_released_stats(bt_status_t released_status) {
296   const uint64_t just_now_ms = now_ms();
297 
298   std::lock_guard<std::mutex> lock(stats_mutex);
299 
300   if (released_status != BT_STATUS_SUCCESS) {
301     wakelock_stats.released_errors++;
302     wakelock_stats.last_released_error = released_status;
303   }
304 
305   if (!wakelock_stats.is_acquired) {
306     return;
307   }
308 
309   wakelock_stats.is_acquired = false;
310   wakelock_stats.released_count++;
311   wakelock_stats.last_released_timestamp_ms = just_now_ms;
312 
313   // Compute the acquired interval and update the statistics
314   uint64_t delta_ms = just_now_ms - wakelock_stats.last_acquired_timestamp_ms;
315   if (delta_ms < wakelock_stats.min_acquired_interval_ms || wakelock_stats.released_count == 1) {
316     wakelock_stats.min_acquired_interval_ms = delta_ms;
317   }
318   if (delta_ms > wakelock_stats.max_acquired_interval_ms) {
319     wakelock_stats.max_acquired_interval_ms = delta_ms;
320   }
321   wakelock_stats.last_acquired_interval_ms = delta_ms;
322   wakelock_stats.total_acquired_interval_ms += delta_ms;
323 
324   BluetoothMetricsLogger::GetInstance()->LogWakeEvent(bluetooth::common::WAKE_EVENT_RELEASED, "",
325                                                       "", just_now_ms);
326 }
327 
wakelock_debug_dump(int fd)328 void wakelock_debug_dump(int fd) {
329   const uint64_t just_now_ms = now_ms();
330 
331   std::lock_guard<std::mutex> lock(stats_mutex);
332 
333   // Compute the last acquired interval if the wakelock is still acquired
334   uint64_t delta_ms = 0;
335   uint64_t last_interval_ms = wakelock_stats.last_acquired_interval_ms;
336   uint64_t min_interval_ms = wakelock_stats.min_acquired_interval_ms;
337   uint64_t max_interval_ms = wakelock_stats.max_acquired_interval_ms;
338   uint64_t avg_interval_ms = 0;
339 
340   if (wakelock_stats.is_acquired) {
341     delta_ms = just_now_ms - wakelock_stats.last_acquired_timestamp_ms;
342     if (delta_ms > max_interval_ms) {
343       max_interval_ms = delta_ms;
344     }
345     if (delta_ms < min_interval_ms) {
346       min_interval_ms = delta_ms;
347     }
348     last_interval_ms = delta_ms;
349   }
350   uint64_t total_interval_ms = wakelock_stats.total_acquired_interval_ms + delta_ms;
351 
352   if (wakelock_stats.acquired_count > 0) {
353     avg_interval_ms = total_interval_ms / wakelock_stats.acquired_count;
354   }
355 
356   dprintf(fd, "\nBluetooth Wakelock Statistics:\n");
357   dprintf(fd, "  Is acquired                    : %s\n",
358           wakelock_stats.is_acquired ? "true" : "false");
359   dprintf(fd, "  Acquired/released count        : %zu / %zu\n", wakelock_stats.acquired_count,
360           wakelock_stats.released_count);
361   dprintf(fd, "  Acquired/released error count  : %zu / %zu\n", wakelock_stats.acquired_errors,
362           wakelock_stats.released_errors);
363   dprintf(fd, "  Last acquire/release error code: %d / %d\n", wakelock_stats.last_acquired_error,
364           wakelock_stats.last_released_error);
365   dprintf(fd, "  Last acquired time (ms)        : %llu\n", (unsigned long long)last_interval_ms);
366   dprintf(fd, "  Acquired time min/max/avg (ms) : %llu / %llu / %llu\n",
367           (unsigned long long)min_interval_ms, (unsigned long long)max_interval_ms,
368           (unsigned long long)avg_interval_ms);
369   dprintf(fd, "  Total acquired time (ms)       : %llu\n", (unsigned long long)total_interval_ms);
370   dprintf(fd, "  Total run time (ms)            : %llu\n",
371           (unsigned long long)(just_now_ms - wakelock_stats.last_reset_timestamp_ms));
372 }
373