1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 ******************************************************************************/
19 #define LOG_TAG "bt_osi_alarm"
21 #include "osi/include/alarm.h"
33 #include <hardware/bluetooth.h>
35 #include "osi/include/allocator.h"
36 #include "osi/include/list.h"
37 #include "osi/include/log.h"
38 #include "osi/include/osi.h"
39 #include "osi/include/semaphore.h"
40 #include "osi/include/thread.h"
42 // Make callbacks run at high thread priority. Some callbacks are used for audio
43 // related timer tasks as well as re-transmissions etc. Since we at this point
44 // cannot differentiate what callback we are dealing with, assume high priority
46 // TODO(eisenbach): Determine correct thread priority (from parent?/per alarm?)
47 static const int CALLBACK_THREAD_PRIORITY_HIGH = -19;
50 // The lock is held while the callback for this alarm is being executed.
51 // It allows us to release the coarse-grained monitor lock while a potentially
52 // long-running callback is executing. |alarm_cancel| uses this lock to provide
53 // a guarantee to its caller that the callback will not be in progress when it
55 pthread_mutex_t callback_lock;
56 period_ms_t creation_time;
60 alarm_callback_t callback;
65 // If the next wakeup time is less than this threshold, we should acquire
66 // a wakelock instead of setting a wake alarm so we're not bouncing in
67 // and out of suspend frequently. This value is externally visible to allow
68 // unit tests to run faster. It should not be modified by production code.
69 int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 3000;
70 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
71 static const clockid_t CLOCK_ID_ALARM = CLOCK_BOOTTIME_ALARM;
72 static const char *WAKE_LOCK_ID = "bluedroid_timer";
73 static const char *WAKE_LOCK_PATH = "/sys/power/wake_lock";
74 static const char *WAKE_UNLOCK_PATH = "/sys/power/wake_unlock";
75 static ssize_t locked_id_len = -1;
76 static pthread_once_t wake_fds_initialized = PTHREAD_ONCE_INIT;
77 static int wake_lock_fd = INVALID_FD;
78 static int wake_unlock_fd = INVALID_FD;
80 // This mutex ensures that the |alarm_set|, |alarm_cancel|, and alarm callback
81 // functions execute serially and not concurrently. As a result, this mutex also
82 // protects the |alarms| list.
83 static pthread_mutex_t monitor;
84 static list_t *alarms;
86 static timer_t wakeup_timer;
87 static bool timer_set;
89 // All alarm callbacks are dispatched from |callback_thread|
90 static thread_t *callback_thread;
91 static bool callback_thread_active;
92 static semaphore_t *alarm_expired;
94 static bool lazy_initialize(void);
95 static period_ms_t now(void);
96 static void alarm_set_internal(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data, bool is_periodic);
97 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule);
98 static void reschedule_root_alarm(void);
99 static void timer_callback(void *data);
100 static void callback_dispatch(void *context);
101 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer);
102 static void initialize_wake_fds(void);
103 static bool acquire_wake_lock(void);
104 static bool release_wake_lock(void);
106 alarm_t *alarm_new(void) {
107 // Make sure we have a list we can insert alarms into.
108 if (!alarms && !lazy_initialize()) {
109 assert(false); // if initialization failed, we should not continue
113 pthread_mutexattr_t attr;
114 pthread_mutexattr_init(&attr);
116 alarm_t *ret = osi_calloc(sizeof(alarm_t));
118 LOG_ERROR(LOG_TAG, "%s unable to allocate memory for alarm.", __func__);
122 // Make this a recursive mutex to make it safe to call |alarm_cancel| from
123 // within the callback function of the alarm.
124 int error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
126 LOG_ERROR(LOG_TAG, "%s unable to create a recursive mutex: %s", __func__, strerror(error));
130 error = pthread_mutex_init(&ret->callback_lock, &attr);
132 LOG_ERROR(LOG_TAG, "%s unable to initialize mutex: %s", __func__, strerror(error));
136 pthread_mutexattr_destroy(&attr);
140 pthread_mutexattr_destroy(&attr);
145 void alarm_free(alarm_t *alarm) {
150 pthread_mutex_destroy(&alarm->callback_lock);
154 period_ms_t alarm_get_remaining_ms(const alarm_t *alarm) {
155 assert(alarm != NULL);
156 period_ms_t remaining_ms = 0;
158 pthread_mutex_lock(&monitor);
160 remaining_ms = alarm->deadline - now();
161 pthread_mutex_unlock(&monitor);
166 void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
167 alarm_set_internal(alarm, deadline, cb, data, false);
170 void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data) {
171 alarm_set_internal(alarm, period, cb, data, true);
174 // Runs in exclusion with alarm_cancel and timer_callback.
175 static void alarm_set_internal(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data, bool is_periodic) {
176 assert(alarms != NULL);
177 assert(alarm != NULL);
180 pthread_mutex_lock(&monitor);
182 alarm->creation_time = now();
183 alarm->is_periodic = is_periodic;
184 alarm->period = period;
185 alarm->callback = cb;
188 schedule_next_instance(alarm, false);
190 pthread_mutex_unlock(&monitor);
193 void alarm_cancel(alarm_t *alarm) {
194 assert(alarms != NULL);
195 assert(alarm != NULL);
197 pthread_mutex_lock(&monitor);
199 bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
201 list_remove(alarms, alarm);
203 alarm->callback = NULL;
206 if (needs_reschedule)
207 reschedule_root_alarm();
209 pthread_mutex_unlock(&monitor);
211 // If the callback for |alarm| is in progress, wait here until it completes.
212 pthread_mutex_lock(&alarm->callback_lock);
213 pthread_mutex_unlock(&alarm->callback_lock);
216 void alarm_cleanup(void) {
217 // If lazy_initialize never ran there is nothing to do
221 callback_thread_active = false;
222 semaphore_post(alarm_expired);
223 thread_free(callback_thread);
224 callback_thread = NULL;
226 semaphore_free(alarm_expired);
227 alarm_expired = NULL;
228 timer_delete(&timer);
232 pthread_mutex_destroy(&monitor);
235 static bool lazy_initialize(void) {
236 assert(alarms == NULL);
238 // timer_t doesn't have an invalid value so we must track whether
239 // the |timer| variable is valid ourselves.
240 bool timer_initialized = false;
241 bool wakeup_timer_initialized = false;
243 pthread_mutex_init(&monitor, NULL);
245 alarms = list_new(NULL);
247 LOG_ERROR(LOG_TAG, "%s unable to allocate alarm list.", __func__);
251 if (!timer_create_internal(CLOCK_ID, &timer))
253 timer_initialized = true;
255 if (!timer_create_internal(CLOCK_ID_ALARM, &wakeup_timer))
257 wakeup_timer_initialized = true;
259 alarm_expired = semaphore_new(0);
260 if (!alarm_expired) {
261 LOG_ERROR(LOG_TAG, "%s unable to create alarm expired semaphore", __func__);
265 callback_thread_active = true;
266 callback_thread = thread_new("alarm_callbacks");
267 if (!callback_thread) {
268 LOG_ERROR(LOG_TAG, "%s unable to create alarm callback thread.", __func__);
272 thread_set_priority(callback_thread, CALLBACK_THREAD_PRIORITY_HIGH);
273 thread_post(callback_thread, callback_dispatch, NULL);
277 thread_free(callback_thread);
278 callback_thread = NULL;
280 callback_thread_active = false;
282 semaphore_free(alarm_expired);
283 alarm_expired = NULL;
285 if (wakeup_timer_initialized)
286 timer_delete(wakeup_timer);
288 if (timer_initialized)
294 pthread_mutex_destroy(&monitor);
299 static period_ms_t now(void) {
300 assert(alarms != NULL);
303 if (clock_gettime(CLOCK_ID, &ts) == -1) {
304 LOG_ERROR(LOG_TAG, "%s unable to get current time: %s", __func__, strerror(errno));
308 return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
311 // Must be called with monitor held
312 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule) {
313 // If the alarm is currently set and it's at the start of the list,
314 // we'll need to re-schedule since we've adjusted the earliest deadline.
315 bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
317 list_remove(alarms, alarm);
319 // Calculate the next deadline for this alarm
320 period_ms_t just_now = now();
321 period_ms_t ms_into_period = alarm->is_periodic ? ((just_now - alarm->creation_time) % alarm->period) : 0;
322 alarm->deadline = just_now + (alarm->period - ms_into_period);
324 // Add it into the timer list sorted by deadline (earliest deadline first).
325 if (list_is_empty(alarms) || ((alarm_t *)list_front(alarms))->deadline >= alarm->deadline)
326 list_prepend(alarms, alarm);
328 for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
329 list_node_t *next = list_next(node);
330 if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
331 list_insert_after(alarms, node, alarm);
336 // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
337 if (force_reschedule || needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
338 reschedule_root_alarm();
341 // NOTE: must be called with monitor lock.
342 static void reschedule_root_alarm(void) {
343 assert(alarms != NULL);
345 const bool timer_was_set = timer_set;
347 // If used in a zeroed state, disarms the timer.
348 struct itimerspec timer_time;
349 memset(&timer_time, 0, sizeof(timer_time));
351 if (list_is_empty(alarms))
354 const alarm_t *next = list_front(alarms);
355 const int64_t next_expiration = next->deadline - now();
356 if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
358 if (!acquire_wake_lock()) {
359 LOG_ERROR(LOG_TAG, "%s unable to acquire wake lock", __func__);
364 timer_time.it_value.tv_sec = (next->deadline / 1000);
365 timer_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
367 // It is entirely unsafe to call timer_settime(2) with a zeroed timerspec for
368 // timers with *_ALARM clock IDs. Although the man page states that the timer
369 // would be canceled, the current behavior (as of Linux kernel 3.17) is that
370 // the callback is issued immediately. The only way to cancel an *_ALARM timer
371 // is to delete the timer. But unfortunately, deleting and re-creating a timer
372 // is rather expensive; every timer_create(2) spawns a new thread. So we simply
373 // set the timer to fire at the largest possible time.
375 // If we've reached this code path, we're going to grab a wake lock and wait for
376 // the next timer to fire. In that case, there's no reason to have a pending wakeup
377 // timer so we simply cancel it.
378 struct itimerspec end_of_time;
379 memset(&end_of_time, 0, sizeof(end_of_time));
380 end_of_time.it_value.tv_sec = (time_t)(1LL << (sizeof(time_t) * 8 - 2));
381 timer_settime(wakeup_timer, TIMER_ABSTIME, &end_of_time, NULL);
383 // WARNING: do not attempt to use relative timers with *_ALARM clock IDs
384 // in kernels before 3.17 unless you have the following patch:
385 // https://lkml.org/lkml/2014/7/7/576
386 struct itimerspec wakeup_time;
387 memset(&wakeup_time, 0, sizeof(wakeup_time));
390 wakeup_time.it_value.tv_sec = (next->deadline / 1000);
391 wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
392 if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
393 LOG_ERROR(LOG_TAG, "%s unable to set wakeup timer: %s",
394 __func__, strerror(errno));
398 timer_set = timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0;
399 if (timer_was_set && !timer_set) {
403 if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1)
404 LOG_ERROR(LOG_TAG, "%s unable to set timer: %s", __func__, strerror(errno));
406 // If next expiration was in the past (e.g. short timer that got context switched)
407 // then the timer might have diarmed itself. Detect this case and work around it
408 // by manually signalling the |alarm_expired| semaphore.
410 // It is possible that the timer was actually super short (a few milliseconds)
411 // and the timer expired normally before we called |timer_gettime|. Worst case,
412 // |alarm_expired| is signaled twice for that alarm. Nothing bad should happen in
413 // that case though since the callback dispatch function checks to make sure the
414 // timer at the head of the list actually expired.
416 struct itimerspec time_to_expire;
417 timer_gettime(timer, &time_to_expire);
418 if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) {
419 LOG_ERROR(LOG_TAG, "%s alarm expiration too close for posix timers, switching to guns", __func__);
420 semaphore_post(alarm_expired);
425 // Callback function for wake alarms and our posix timer
426 static void timer_callback(UNUSED_ATTR void *ptr) {
427 semaphore_post(alarm_expired);
430 // Function running on |callback_thread| that dispatches alarm callbacks upon
431 // alarm expiration, which is signaled using |alarm_expired|.
432 static void callback_dispatch(UNUSED_ATTR void *context) {
434 semaphore_wait(alarm_expired);
435 if (!callback_thread_active)
438 pthread_mutex_lock(&monitor);
441 // Take into account that the alarm may get cancelled before we get to it.
442 // We're done here if there are no alarms or the alarm at the front is in
443 // the future. Release the monitor lock and exit right away since there's
444 // nothing left to do.
445 if (list_is_empty(alarms) || (alarm = list_front(alarms))->deadline > now()) {
446 reschedule_root_alarm();
447 pthread_mutex_unlock(&monitor);
451 list_remove(alarms, alarm);
453 alarm_callback_t callback = alarm->callback;
454 void *data = alarm->data;
456 if (alarm->is_periodic) {
457 schedule_next_instance(alarm, true);
459 reschedule_root_alarm();
462 alarm->callback = NULL;
467 pthread_mutex_lock(&alarm->callback_lock);
468 pthread_mutex_unlock(&monitor);
472 pthread_mutex_unlock(&alarm->callback_lock);
475 LOG_DEBUG(LOG_TAG, "%s Callback thread exited", __func__);
478 static void initialize_wake_fds(void) {
479 LOG_DEBUG(LOG_TAG, "%s opening wake locks", __func__);
481 wake_lock_fd = open(WAKE_LOCK_PATH, O_RDWR | O_CLOEXEC);
482 if (wake_lock_fd == INVALID_FD) {
483 LOG_ERROR(LOG_TAG, "%s can't open wake lock %s: %s",
484 __func__, WAKE_LOCK_PATH, strerror(errno));
487 wake_unlock_fd = open(WAKE_UNLOCK_PATH, O_RDWR | O_CLOEXEC);
488 if (wake_unlock_fd == INVALID_FD) {
489 LOG_ERROR(LOG_TAG, "%s can't open wake unlock %s: %s",
490 __func__, WAKE_UNLOCK_PATH, strerror(errno));
494 static bool acquire_wake_lock(void) {
495 pthread_once(&wake_fds_initialized, initialize_wake_fds);
497 if (wake_lock_fd == INVALID_FD) {
498 LOG_ERROR(LOG_TAG, "%s lock not acquired, invalid fd", __func__);
502 if (wake_unlock_fd == INVALID_FD) {
503 LOG_ERROR(LOG_TAG, "%s not acquiring lock: can't release lock", __func__);
507 long lock_name_len = strlen(WAKE_LOCK_ID);
508 locked_id_len = write(wake_lock_fd, WAKE_LOCK_ID, lock_name_len);
509 if (locked_id_len == -1) {
510 LOG_ERROR(LOG_TAG, "%s wake lock not acquired: %s",
511 __func__, strerror(errno));
513 } else if (locked_id_len < lock_name_len) {
514 // TODO (jamuraa): this is weird. maybe we should release and retry.
515 LOG_WARN(LOG_TAG, "%s wake lock truncated to %zd chars",
516 __func__, locked_id_len);
521 static bool release_wake_lock(void) {
522 pthread_once(&wake_fds_initialized, initialize_wake_fds);
524 if (wake_unlock_fd == INVALID_FD) {
525 LOG_ERROR(LOG_TAG, "%s lock not released, invalid fd", __func__);
529 ssize_t wrote_name_len = write(wake_unlock_fd, WAKE_LOCK_ID, locked_id_len);
530 if (wrote_name_len == -1) {
531 LOG_ERROR(LOG_TAG, "%s can't release wake lock: %s",
532 __func__, strerror(errno));
533 } else if (wrote_name_len < locked_id_len) {
534 LOG_ERROR(LOG_TAG, "%s lock release only wrote %zd, assuming released",
535 __func__, wrote_name_len);
540 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer) {
541 assert(timer != NULL);
543 struct sigevent sigevent;
544 memset(&sigevent, 0, sizeof(sigevent));
545 sigevent.sigev_notify = SIGEV_THREAD;
546 sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
547 if (timer_create(clock_id, &sigevent, timer) == -1) {
548 LOG_ERROR(LOG_TAG, "%s unable to create timer with clock %d: %s",
549 __func__, clock_id, strerror(errno));