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"
23 #include <hardware/bluetooth.h>
24 #include <hardware_legacy/power.h>
31 #include "osi/include/alarm.h"
32 #include "osi/include/allocator.h"
33 #include "osi/include/list.h"
34 #include "osi/include/log.h"
35 #include "osi/include/osi.h"
36 #include "osi/include/semaphore.h"
37 #include "osi/include/thread.h"
40 // The lock is held while the callback for this alarm is being executed.
41 // It allows us to release the coarse-grained monitor lock while a potentially
42 // long-running callback is executing. |alarm_cancel| uses this lock to provide
43 // a guarantee to its caller that the callback will not be in progress when it
45 pthread_mutex_t callback_lock;
50 alarm_callback_t callback;
54 extern bt_os_callouts_t *bt_os_callouts;
56 // If the next wakeup time is less than this threshold, we should acquire
57 // a wakelock instead of setting a wake alarm so we're not bouncing in
58 // and out of suspend frequently. This value is externally visible to allow
59 // unit tests to run faster. It should not be modified by production code.
60 int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 3000;
61 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
62 static const clockid_t CLOCK_ID_ALARM = CLOCK_BOOTTIME_ALARM;
63 static const char *WAKE_LOCK_ID = "bluedroid_timer";
65 // This mutex ensures that the |alarm_set|, |alarm_cancel|, and alarm callback
66 // functions execute serially and not concurrently. As a result, this mutex also
67 // protects the |alarms| list.
68 static pthread_mutex_t monitor;
69 static list_t *alarms;
71 static timer_t wakeup_timer;
72 static bool timer_set;
74 // All alarm callbacks are dispatched from |callback_thread|
75 static thread_t *callback_thread;
76 static bool callback_thread_active;
77 static semaphore_t *alarm_expired;
79 static bool lazy_initialize(void);
80 static period_ms_t now(void);
81 static void alarm_set_internal(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data, bool is_periodic);
82 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule);
83 static void reschedule_root_alarm(void);
84 static void timer_callback(void *data);
85 static void callback_dispatch(void *context);
86 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer);
88 alarm_t *alarm_new(void) {
89 // Make sure we have a list we can insert alarms into.
90 if (!alarms && !lazy_initialize())
93 pthread_mutexattr_t attr;
94 pthread_mutexattr_init(&attr);
96 alarm_t *ret = osi_calloc(sizeof(alarm_t));
98 LOG_ERROR("%s unable to allocate memory for alarm.", __func__);
102 // Make this a recursive mutex to make it safe to call |alarm_cancel| from
103 // within the callback function of the alarm.
104 int error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
106 LOG_ERROR("%s unable to create a recursive mutex: %s", __func__, strerror(error));
110 error = pthread_mutex_init(&ret->callback_lock, &attr);
112 LOG_ERROR("%s unable to initialize mutex: %s", __func__, strerror(error));
116 pthread_mutexattr_destroy(&attr);
120 pthread_mutexattr_destroy(&attr);
125 void alarm_free(alarm_t *alarm) {
130 pthread_mutex_destroy(&alarm->callback_lock);
134 period_ms_t alarm_get_remaining_ms(const alarm_t *alarm) {
135 assert(alarm != NULL);
136 period_ms_t remaining_ms = 0;
138 pthread_mutex_lock(&monitor);
140 remaining_ms = alarm->deadline - now();
141 pthread_mutex_unlock(&monitor);
146 void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
147 alarm_set_internal(alarm, deadline, cb, data, false);
150 void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data) {
151 alarm_set_internal(alarm, period, cb, data, true);
154 // Runs in exclusion with alarm_cancel and timer_callback.
155 static void alarm_set_internal(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data, bool is_periodic) {
156 assert(alarms != NULL);
157 assert(alarm != NULL);
160 pthread_mutex_lock(&monitor);
162 alarm->created = now();
163 alarm->is_periodic = is_periodic;
164 alarm->period = period;
165 alarm->callback = cb;
168 schedule_next_instance(alarm, false);
170 pthread_mutex_unlock(&monitor);
173 void alarm_cancel(alarm_t *alarm) {
174 assert(alarms != NULL);
175 assert(alarm != NULL);
177 pthread_mutex_lock(&monitor);
179 bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
181 list_remove(alarms, alarm);
183 alarm->callback = NULL;
186 if (needs_reschedule)
187 reschedule_root_alarm();
189 pthread_mutex_unlock(&monitor);
191 // If the callback for |alarm| is in progress, wait here until it completes.
192 pthread_mutex_lock(&alarm->callback_lock);
193 pthread_mutex_unlock(&alarm->callback_lock);
196 void alarm_cleanup(void) {
197 // If lazy_initialize never ran there is nothing to do
201 callback_thread_active = false;
202 semaphore_post(alarm_expired);
203 thread_free(callback_thread);
204 callback_thread = NULL;
206 semaphore_free(alarm_expired);
207 alarm_expired = NULL;
208 timer_delete(&timer);
212 pthread_mutex_destroy(&monitor);
215 static bool lazy_initialize(void) {
216 assert(alarms == NULL);
218 // timer_t doesn't have an invalid value so we must track whether
219 // the |timer| variable is valid ourselves.
220 bool timer_initialized = false;
221 bool wakeup_timer_initialized = false;
223 pthread_mutex_init(&monitor, NULL);
225 alarms = list_new(NULL);
227 LOG_ERROR("%s unable to allocate alarm list.", __func__);
231 if (!timer_create_internal(CLOCK_ID, &timer))
233 timer_initialized = true;
235 if (!timer_create_internal(CLOCK_ID_ALARM, &wakeup_timer))
237 wakeup_timer_initialized = true;
239 alarm_expired = semaphore_new(0);
240 if (!alarm_expired) {
241 LOG_ERROR("%s unable to create alarm expired semaphore", __func__);
245 callback_thread_active = true;
246 callback_thread = thread_new("alarm_callbacks");
247 if (!callback_thread) {
248 LOG_ERROR("%s unable to create alarm callback thread.", __func__);
252 thread_post(callback_thread, callback_dispatch, NULL);
256 thread_free(callback_thread);
257 callback_thread = NULL;
259 callback_thread_active = false;
261 semaphore_free(alarm_expired);
262 alarm_expired = NULL;
264 if (wakeup_timer_initialized)
265 timer_delete(wakeup_timer);
267 if (timer_initialized)
273 pthread_mutex_destroy(&monitor);
278 static period_ms_t now(void) {
279 assert(alarms != NULL);
282 if (clock_gettime(CLOCK_ID, &ts) == -1) {
283 LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
287 return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
290 // Must be called with monitor held
291 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule) {
292 // If the alarm is currently set and it's at the start of the list,
293 // we'll need to re-schedule since we've adjusted the earliest deadline.
294 bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
296 list_remove(alarms, alarm);
298 // Calculate the next deadline for this alarm
299 period_ms_t just_now = now();
300 period_ms_t ms_into_period = alarm->is_periodic ? ((just_now - alarm->created) % alarm->period) : 0;
301 alarm->deadline = just_now + (alarm->period - ms_into_period);
303 // Add it into the timer list sorted by deadline (earliest deadline first).
304 if (list_is_empty(alarms) || ((alarm_t *)list_front(alarms))->deadline >= alarm->deadline)
305 list_prepend(alarms, alarm);
307 for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
308 list_node_t *next = list_next(node);
309 if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
310 list_insert_after(alarms, node, alarm);
315 // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
316 if (force_reschedule || needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
317 reschedule_root_alarm();
320 // NOTE: must be called with monitor lock.
321 static void reschedule_root_alarm(void) {
322 assert(alarms != NULL);
324 const bool timer_was_set = timer_set;
326 // If used in a zeroed state, disarms the timer.
327 struct itimerspec timer_time;
328 memset(&timer_time, 0, sizeof(timer_time));
330 if (list_is_empty(alarms))
333 const alarm_t *next = list_front(alarms);
334 const int64_t next_expiration = next->deadline - now();
335 if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
337 int status = acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
338 if (status != (int) strlen(WAKE_LOCK_ID)) {
339 LOG_ERROR("%s unable to acquire wake lock: %d", __func__, status);
344 timer_time.it_value.tv_sec = (next->deadline / 1000);
345 timer_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
347 // It is entirely unsafe to call timer_settime(2) with a zeroed timerspec for
348 // timers with *_ALARM clock IDs. Although the man page states that the timer
349 // would be canceled, the current behavior (as of Linux kernel 3.17) is that
350 // the callback is issued immediately. The only way to cancel an *_ALARM timer
351 // is to delete the timer. But unfortunately, deleting and re-creating a timer
352 // is rather expensive; every timer_create(2) spawns a new thread. So we simply
353 // set the timer to fire at the largest possible time.
355 // If we've reached this code path, we're going to grab a wake lock and wait for
356 // the next timer to fire. In that case, there's no reason to have a pending wakeup
357 // timer so we simply cancel it.
358 struct itimerspec end_of_time;
359 memset(&end_of_time, 0, sizeof(end_of_time));
360 end_of_time.it_value.tv_sec = (time_t)((1LL << (sizeof(time_t) * 8 - 1)) - 1);
361 timer_settime(wakeup_timer, TIMER_ABSTIME, &end_of_time, NULL);
363 // WARNING: do not attempt to use relative timers with *_ALARM clock IDs
364 // in kernels before 3.17 unless you have the following patch:
365 // https://lkml.org/lkml/2014/7/7/576
366 struct itimerspec wakeup_time;
367 memset(&wakeup_time, 0, sizeof(wakeup_time));
368 wakeup_time.it_value.tv_sec = (next->deadline / 1000);
369 wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
370 if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
371 LOG_ERROR("%s unable to set wakeup timer: %s", __func__, strerror(errno));
375 timer_set = timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0;
376 if (timer_was_set && !timer_set) {
377 release_wake_lock(WAKE_LOCK_ID);
380 if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1)
381 LOG_ERROR("%s unable to set timer: %s", __func__, strerror(errno));
383 // If next expiration was in the past (e.g. short timer that got context switched)
384 // then the timer might have diarmed itself. Detect this case and work around it
385 // by manually signalling the |alarm_expired| semaphore.
387 // It is possible that the timer was actually super short (a few milliseconds)
388 // and the timer expired normally before we called |timer_gettime|. Worst case,
389 // |alarm_expired| is signaled twice for that alarm. Nothing bad should happen in
390 // that case though since the callback dispatch function checks to make sure the
391 // timer at the head of the list actually expired.
393 struct itimerspec time_to_expire;
394 timer_gettime(timer, &time_to_expire);
395 if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) {
396 LOG_ERROR("%s alarm expiration too close for posix timers, switching to guns", __func__);
397 semaphore_post(alarm_expired);
402 // Callback function for wake alarms and our posix timer
403 static void timer_callback(UNUSED_ATTR void *ptr) {
404 semaphore_post(alarm_expired);
407 // Function running on |callback_thread| that dispatches alarm callbacks upon
408 // alarm expiration, which is signaled using |alarm_expired|.
409 static void callback_dispatch(UNUSED_ATTR void *context) {
411 semaphore_wait(alarm_expired);
412 if (!callback_thread_active)
415 pthread_mutex_lock(&monitor);
418 // Take into account that the alarm may get cancelled before we get to it.
419 // We're done here if there are no alarms or the alarm at the front is in
420 // the future. Release the monitor lock and exit right away since there's
421 // nothing left to do.
422 if (list_is_empty(alarms) || (alarm = list_front(alarms))->deadline > now()) {
423 reschedule_root_alarm();
424 pthread_mutex_unlock(&monitor);
428 list_remove(alarms, alarm);
430 alarm_callback_t callback = alarm->callback;
431 void *data = alarm->data;
433 if (alarm->is_periodic) {
434 schedule_next_instance(alarm, true);
436 reschedule_root_alarm();
439 alarm->callback = NULL;
444 pthread_mutex_lock(&alarm->callback_lock);
445 pthread_mutex_unlock(&monitor);
449 pthread_mutex_unlock(&alarm->callback_lock);
452 LOG_DEBUG("%s Callback thread exited", __func__);
455 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer) {
456 assert(timer != NULL);
458 struct sigevent sigevent;
459 memset(&sigevent, 0, sizeof(sigevent));
460 sigevent.sigev_notify = SIGEV_THREAD;
461 sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
462 if (timer_create(clock_id, &sigevent, timer) == -1) {
463 LOG_ERROR("%s unable to create timer with clock %d: %s", __func__, clock_id, strerror(errno));