Home | History | Annotate | Download | only in src
      1 /******************************************************************************
      2  *
      3  *  Copyright (C) 2014 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 #include "include/bt_target.h"
     20 
     21 #define LOG_TAG "bt_osi_alarm"
     22 
     23 #include "osi/include/alarm.h"
     24 
     25 #include <base/cancelable_callback.h>
     26 #include <base/logging.h>
     27 #include <base/message_loop/message_loop.h>
     28 #include <errno.h>
     29 #include <fcntl.h>
     30 #include <inttypes.h>
     31 #include <malloc.h>
     32 #include <pthread.h>
     33 #include <signal.h>
     34 #include <string.h>
     35 #include <time.h>
     36 
     37 #include <hardware/bluetooth.h>
     38 
     39 #include <mutex>
     40 
     41 #include "osi/include/allocator.h"
     42 #include "osi/include/fixed_queue.h"
     43 #include "osi/include/list.h"
     44 #include "osi/include/log.h"
     45 #include "osi/include/osi.h"
     46 #include "osi/include/semaphore.h"
     47 #include "osi/include/thread.h"
     48 #include "osi/include/wakelock.h"
     49 
     50 using base::Bind;
     51 using base::CancelableClosure;
     52 using base::MessageLoop;
     53 
     54 extern base::MessageLoop* get_message_loop();
     55 
     56 // Callback and timer threads should run at RT priority in order to ensure they
     57 // meet audio deadlines.  Use this priority for all audio/timer related thread.
     58 static const int THREAD_RT_PRIORITY = 1;
     59 
     60 typedef struct {
     61   size_t count;
     62   period_ms_t total_ms;
     63   period_ms_t max_ms;
     64 } stat_t;
     65 
     66 // Alarm-related information and statistics
     67 typedef struct {
     68   const char* name;
     69   size_t scheduled_count;
     70   size_t canceled_count;
     71   size_t rescheduled_count;
     72   size_t total_updates;
     73   period_ms_t last_update_ms;
     74   stat_t callback_execution;
     75   stat_t overdue_scheduling;
     76   stat_t premature_scheduling;
     77 } alarm_stats_t;
     78 
     79 /* Wrapper around CancellableClosure that let it be embedded in structs, without
     80  * need to define copy operator. */
     81 struct CancelableClosureInStruct {
     82   base::CancelableClosure i;
     83 
     84   CancelableClosureInStruct& operator=(const CancelableClosureInStruct& in) {
     85     if (!in.i.callback().is_null()) i.Reset(in.i.callback());
     86     return *this;
     87   }
     88 };
     89 
     90 struct alarm_t {
     91   // The mutex is held while the callback for this alarm is being executed.
     92   // It allows us to release the coarse-grained monitor lock while a
     93   // potentially long-running callback is executing. |alarm_cancel| uses this
     94   // mutex to provide a guarantee to its caller that the callback will not be
     95   // in progress when it returns.
     96   std::recursive_mutex* callback_mutex;
     97   period_ms_t creation_time;
     98   period_ms_t period;
     99   period_ms_t deadline;
    100   period_ms_t prev_deadline;  // Previous deadline - used for accounting of
    101                               // periodic timers
    102   bool is_periodic;
    103   fixed_queue_t* queue;  // The processing queue to add this alarm to
    104   alarm_callback_t callback;
    105   void* data;
    106   alarm_stats_t stats;
    107 
    108   bool for_msg_loop;  // True, if the alarm should be processed on message loop
    109   CancelableClosureInStruct closure;  // posted to message loop for processing
    110 };
    111 
    112 // If the next wakeup time is less than this threshold, we should acquire
    113 // a wakelock instead of setting a wake alarm so we're not bouncing in
    114 // and out of suspend frequently. This value is externally visible to allow
    115 // unit tests to run faster. It should not be modified by production code.
    116 int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 3000;
    117 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
    118 
    119 #if (KERNEL_MISSING_CLOCK_BOOTTIME_ALARM == TRUE)
    120 static const clockid_t CLOCK_ID_ALARM = CLOCK_BOOTTIME;
    121 #else
    122 static const clockid_t CLOCK_ID_ALARM = CLOCK_BOOTTIME_ALARM;
    123 #endif
    124 
    125 // This mutex ensures that the |alarm_set|, |alarm_cancel|, and alarm callback
    126 // functions execute serially and not concurrently. As a result, this mutex
    127 // also protects the |alarms| list.
    128 static std::mutex alarms_mutex;
    129 static list_t* alarms;
    130 static timer_t timer;
    131 static timer_t wakeup_timer;
    132 static bool timer_set;
    133 
    134 // All alarm callbacks are dispatched from |dispatcher_thread|
    135 static thread_t* dispatcher_thread;
    136 static bool dispatcher_thread_active;
    137 static semaphore_t* alarm_expired;
    138 
    139 // Default alarm callback thread and queue
    140 static thread_t* default_callback_thread;
    141 static fixed_queue_t* default_callback_queue;
    142 
    143 static alarm_t* alarm_new_internal(const char* name, bool is_periodic);
    144 static bool lazy_initialize(void);
    145 static period_ms_t now(void);
    146 static void alarm_set_internal(alarm_t* alarm, period_ms_t period,
    147                                alarm_callback_t cb, void* data,
    148                                fixed_queue_t* queue, bool for_msg_loop);
    149 static void alarm_cancel_internal(alarm_t* alarm);
    150 static void remove_pending_alarm(alarm_t* alarm);
    151 static void schedule_next_instance(alarm_t* alarm);
    152 static void reschedule_root_alarm(void);
    153 static void alarm_queue_ready(fixed_queue_t* queue, void* context);
    154 static void timer_callback(void* data);
    155 static void callback_dispatch(void* context);
    156 static bool timer_create_internal(const clockid_t clock_id, timer_t* timer);
    157 static void update_scheduling_stats(alarm_stats_t* stats, period_ms_t now_ms,
    158                                     period_ms_t deadline_ms,
    159                                     period_ms_t execution_delta_ms);
    160 // Registers |queue| for processing alarm callbacks on |thread|.
    161 // |queue| may not be NULL. |thread| may not be NULL.
    162 static void alarm_register_processing_queue(fixed_queue_t* queue,
    163                                             thread_t* thread);
    164 
    165 static void update_stat(stat_t* stat, period_ms_t delta) {
    166   if (stat->max_ms < delta) stat->max_ms = delta;
    167   stat->total_ms += delta;
    168   stat->count++;
    169 }
    170 
    171 alarm_t* alarm_new(const char* name) { return alarm_new_internal(name, false); }
    172 
    173 alarm_t* alarm_new_periodic(const char* name) {
    174   return alarm_new_internal(name, true);
    175 }
    176 
    177 static alarm_t* alarm_new_internal(const char* name, bool is_periodic) {
    178   // Make sure we have a list we can insert alarms into.
    179   if (!alarms && !lazy_initialize()) {
    180     CHECK(false);  // if initialization failed, we should not continue
    181     return NULL;
    182   }
    183 
    184   alarm_t* ret = static_cast<alarm_t*>(osi_calloc(sizeof(alarm_t)));
    185 
    186   ret->callback_mutex = new std::recursive_mutex;
    187   ret->is_periodic = is_periodic;
    188   ret->stats.name = osi_strdup(name);
    189 
    190   ret->for_msg_loop = false;
    191   // placement new
    192   new (&ret->closure) CancelableClosureInStruct();
    193 
    194   // NOTE: The stats were reset by osi_calloc() above
    195 
    196   return ret;
    197 }
    198 
    199 void alarm_free(alarm_t* alarm) {
    200   if (!alarm) return;
    201 
    202   alarm_cancel(alarm);
    203   delete alarm->callback_mutex;
    204   osi_free((void*)alarm->stats.name);
    205   alarm->closure.~CancelableClosureInStruct();
    206   osi_free(alarm);
    207 }
    208 
    209 period_ms_t alarm_get_remaining_ms(const alarm_t* alarm) {
    210   CHECK(alarm != NULL);
    211   period_ms_t remaining_ms = 0;
    212   period_ms_t just_now = now();
    213 
    214   std::lock_guard<std::mutex> lock(alarms_mutex);
    215   if (alarm->deadline > just_now) remaining_ms = alarm->deadline - just_now;
    216 
    217   return remaining_ms;
    218 }
    219 
    220 void alarm_set(alarm_t* alarm, period_ms_t interval_ms, alarm_callback_t cb,
    221                void* data) {
    222   alarm_set_internal(alarm, interval_ms, cb, data, default_callback_queue,
    223                      false);
    224 }
    225 
    226 void alarm_set_on_mloop(alarm_t* alarm, period_ms_t interval_ms,
    227                         alarm_callback_t cb, void* data) {
    228   alarm_set_internal(alarm, interval_ms, cb, data, NULL, true);
    229 }
    230 
    231 // Runs in exclusion with alarm_cancel and timer_callback.
    232 static void alarm_set_internal(alarm_t* alarm, period_ms_t period,
    233                                alarm_callback_t cb, void* data,
    234                                fixed_queue_t* queue, bool for_msg_loop) {
    235   CHECK(alarms != NULL);
    236   CHECK(alarm != NULL);
    237   CHECK(cb != NULL);
    238 
    239   std::lock_guard<std::mutex> lock(alarms_mutex);
    240 
    241   alarm->creation_time = now();
    242   alarm->period = period;
    243   alarm->queue = queue;
    244   alarm->callback = cb;
    245   alarm->data = data;
    246   alarm->for_msg_loop = for_msg_loop;
    247 
    248   schedule_next_instance(alarm);
    249   alarm->stats.scheduled_count++;
    250 }
    251 
    252 void alarm_cancel(alarm_t* alarm) {
    253   CHECK(alarms != NULL);
    254   if (!alarm) return;
    255 
    256   {
    257     std::lock_guard<std::mutex> lock(alarms_mutex);
    258     alarm_cancel_internal(alarm);
    259   }
    260 
    261   // If the callback for |alarm| is in progress, wait here until it completes.
    262   std::lock_guard<std::recursive_mutex> lock(*alarm->callback_mutex);
    263 }
    264 
    265 // Internal implementation of canceling an alarm.
    266 // The caller must hold the |alarms_mutex|
    267 static void alarm_cancel_internal(alarm_t* alarm) {
    268   bool needs_reschedule =
    269       (!list_is_empty(alarms) && list_front(alarms) == alarm);
    270 
    271   remove_pending_alarm(alarm);
    272 
    273   alarm->deadline = 0;
    274   alarm->prev_deadline = 0;
    275   alarm->callback = NULL;
    276   alarm->data = NULL;
    277   alarm->stats.canceled_count++;
    278   alarm->queue = NULL;
    279 
    280   if (needs_reschedule) reschedule_root_alarm();
    281 }
    282 
    283 bool alarm_is_scheduled(const alarm_t* alarm) {
    284   if ((alarms == NULL) || (alarm == NULL)) return false;
    285   return (alarm->callback != NULL);
    286 }
    287 
    288 void alarm_cleanup(void) {
    289   // If lazy_initialize never ran there is nothing else to do
    290   if (!alarms) return;
    291 
    292   dispatcher_thread_active = false;
    293   semaphore_post(alarm_expired);
    294   thread_free(dispatcher_thread);
    295   dispatcher_thread = NULL;
    296 
    297   std::lock_guard<std::mutex> lock(alarms_mutex);
    298 
    299   fixed_queue_free(default_callback_queue, NULL);
    300   default_callback_queue = NULL;
    301   thread_free(default_callback_thread);
    302   default_callback_thread = NULL;
    303 
    304   timer_delete(wakeup_timer);
    305   timer_delete(timer);
    306   semaphore_free(alarm_expired);
    307   alarm_expired = NULL;
    308 
    309   list_free(alarms);
    310   alarms = NULL;
    311 }
    312 
    313 static bool lazy_initialize(void) {
    314   CHECK(alarms == NULL);
    315 
    316   // timer_t doesn't have an invalid value so we must track whether
    317   // the |timer| variable is valid ourselves.
    318   bool timer_initialized = false;
    319   bool wakeup_timer_initialized = false;
    320 
    321   std::lock_guard<std::mutex> lock(alarms_mutex);
    322 
    323   alarms = list_new(NULL);
    324   if (!alarms) {
    325     LOG_ERROR(LOG_TAG, "%s unable to allocate alarm list.", __func__);
    326     goto error;
    327   }
    328 
    329   if (!timer_create_internal(CLOCK_ID, &timer)) goto error;
    330   timer_initialized = true;
    331 
    332   if (!timer_create_internal(CLOCK_ID_ALARM, &wakeup_timer)) goto error;
    333   wakeup_timer_initialized = true;
    334 
    335   alarm_expired = semaphore_new(0);
    336   if (!alarm_expired) {
    337     LOG_ERROR(LOG_TAG, "%s unable to create alarm expired semaphore", __func__);
    338     goto error;
    339   }
    340 
    341   default_callback_thread =
    342       thread_new_sized("alarm_default_callbacks", SIZE_MAX);
    343   if (default_callback_thread == NULL) {
    344     LOG_ERROR(LOG_TAG, "%s unable to create default alarm callbacks thread.",
    345               __func__);
    346     goto error;
    347   }
    348   thread_set_rt_priority(default_callback_thread, THREAD_RT_PRIORITY);
    349   default_callback_queue = fixed_queue_new(SIZE_MAX);
    350   if (default_callback_queue == NULL) {
    351     LOG_ERROR(LOG_TAG, "%s unable to create default alarm callbacks queue.",
    352               __func__);
    353     goto error;
    354   }
    355   alarm_register_processing_queue(default_callback_queue,
    356                                   default_callback_thread);
    357 
    358   dispatcher_thread_active = true;
    359   dispatcher_thread = thread_new("alarm_dispatcher");
    360   if (!dispatcher_thread) {
    361     LOG_ERROR(LOG_TAG, "%s unable to create alarm callback thread.", __func__);
    362     goto error;
    363   }
    364   thread_set_rt_priority(dispatcher_thread, THREAD_RT_PRIORITY);
    365   thread_post(dispatcher_thread, callback_dispatch, NULL);
    366   return true;
    367 
    368 error:
    369   fixed_queue_free(default_callback_queue, NULL);
    370   default_callback_queue = NULL;
    371   thread_free(default_callback_thread);
    372   default_callback_thread = NULL;
    373 
    374   thread_free(dispatcher_thread);
    375   dispatcher_thread = NULL;
    376 
    377   dispatcher_thread_active = false;
    378 
    379   semaphore_free(alarm_expired);
    380   alarm_expired = NULL;
    381 
    382   if (wakeup_timer_initialized) timer_delete(wakeup_timer);
    383 
    384   if (timer_initialized) timer_delete(timer);
    385 
    386   list_free(alarms);
    387   alarms = NULL;
    388 
    389   return false;
    390 }
    391 
    392 static period_ms_t now(void) {
    393   CHECK(alarms != NULL);
    394 
    395   struct timespec ts;
    396   if (clock_gettime(CLOCK_ID, &ts) == -1) {
    397     LOG_ERROR(LOG_TAG, "%s unable to get current time: %s", __func__,
    398               strerror(errno));
    399     return 0;
    400   }
    401 
    402   return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
    403 }
    404 
    405 // Remove alarm from internal alarm list and the processing queue
    406 // The caller must hold the |alarms_mutex|
    407 static void remove_pending_alarm(alarm_t* alarm) {
    408   list_remove(alarms, alarm);
    409 
    410   if (alarm->for_msg_loop) {
    411     alarm->closure.i.Cancel();
    412   } else {
    413     while (fixed_queue_try_remove_from_queue(alarm->queue, alarm) != NULL) {
    414       // Remove all repeated alarm instances from the queue.
    415       // NOTE: We are defensive here - we shouldn't have repeated alarm
    416       // instances
    417     }
    418   }
    419 }
    420 
    421 // Must be called with |alarms_mutex| held
    422 static void schedule_next_instance(alarm_t* alarm) {
    423   // If the alarm is currently set and it's at the start of the list,
    424   // we'll need to re-schedule since we've adjusted the earliest deadline.
    425   bool needs_reschedule =
    426       (!list_is_empty(alarms) && list_front(alarms) == alarm);
    427   if (alarm->callback) remove_pending_alarm(alarm);
    428 
    429   // Calculate the next deadline for this alarm
    430   period_ms_t just_now = now();
    431   period_ms_t ms_into_period = 0;
    432   if ((alarm->is_periodic) && (alarm->period != 0))
    433     ms_into_period = ((just_now - alarm->creation_time) % alarm->period);
    434   alarm->deadline = just_now + (alarm->period - ms_into_period);
    435 
    436   // Add it into the timer list sorted by deadline (earliest deadline first).
    437   if (list_is_empty(alarms) ||
    438       ((alarm_t*)list_front(alarms))->deadline > alarm->deadline) {
    439     list_prepend(alarms, alarm);
    440   } else {
    441     for (list_node_t* node = list_begin(alarms); node != list_end(alarms);
    442          node = list_next(node)) {
    443       list_node_t* next = list_next(node);
    444       if (next == list_end(alarms) ||
    445           ((alarm_t*)list_node(next))->deadline > alarm->deadline) {
    446         list_insert_after(alarms, node, alarm);
    447         break;
    448       }
    449     }
    450   }
    451 
    452   // If the new alarm has the earliest deadline, we need to re-evaluate our
    453   // schedule.
    454   if (needs_reschedule ||
    455       (!list_is_empty(alarms) && list_front(alarms) == alarm)) {
    456     reschedule_root_alarm();
    457   }
    458 }
    459 
    460 // NOTE: must be called with |alarms_mutex| held
    461 static void reschedule_root_alarm(void) {
    462   CHECK(alarms != NULL);
    463 
    464   const bool timer_was_set = timer_set;
    465   alarm_t* next;
    466   int64_t next_expiration;
    467 
    468   // If used in a zeroed state, disarms the timer.
    469   struct itimerspec timer_time;
    470   memset(&timer_time, 0, sizeof(timer_time));
    471 
    472   if (list_is_empty(alarms)) goto done;
    473 
    474   next = static_cast<alarm_t*>(list_front(alarms));
    475   next_expiration = next->deadline - now();
    476   if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
    477     if (!timer_set) {
    478       if (!wakelock_acquire()) {
    479         LOG_ERROR(LOG_TAG, "%s unable to acquire wake lock", __func__);
    480         goto done;
    481       }
    482     }
    483 
    484     timer_time.it_value.tv_sec = (next->deadline / 1000);
    485     timer_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
    486 
    487     // It is entirely unsafe to call timer_settime(2) with a zeroed timerspec
    488     // for timers with *_ALARM clock IDs. Although the man page states that the
    489     // timer would be canceled, the current behavior (as of Linux kernel 3.17)
    490     // is that the callback is issued immediately. The only way to cancel an
    491     // *_ALARM timer is to delete the timer. But unfortunately, deleting and
    492     // re-creating a timer is rather expensive; every timer_create(2) spawns a
    493     // new thread. So we simply set the timer to fire at the largest possible
    494     // time.
    495     //
    496     // If we've reached this code path, we're going to grab a wake lock and
    497     // wait for the next timer to fire. In that case, there's no reason to
    498     // have a pending wakeup timer so we simply cancel it.
    499     struct itimerspec end_of_time;
    500     memset(&end_of_time, 0, sizeof(end_of_time));
    501     end_of_time.it_value.tv_sec = (time_t)(1LL << (sizeof(time_t) * 8 - 2));
    502     timer_settime(wakeup_timer, TIMER_ABSTIME, &end_of_time, NULL);
    503   } else {
    504     // WARNING: do not attempt to use relative timers with *_ALARM clock IDs
    505     // in kernels before 3.17 unless you have the following patch:
    506     // https://lkml.org/lkml/2014/7/7/576
    507     struct itimerspec wakeup_time;
    508     memset(&wakeup_time, 0, sizeof(wakeup_time));
    509 
    510     wakeup_time.it_value.tv_sec = (next->deadline / 1000);
    511     wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
    512     if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
    513       LOG_ERROR(LOG_TAG, "%s unable to set wakeup timer: %s", __func__,
    514                 strerror(errno));
    515   }
    516 
    517 done:
    518   timer_set =
    519       timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0;
    520   if (timer_was_set && !timer_set) {
    521     wakelock_release();
    522   }
    523 
    524   if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1)
    525     LOG_ERROR(LOG_TAG, "%s unable to set timer: %s", __func__, strerror(errno));
    526 
    527   // If next expiration was in the past (e.g. short timer that got context
    528   // switched) then the timer might have diarmed itself. Detect this case and
    529   // work around it by manually signalling the |alarm_expired| semaphore.
    530   //
    531   // It is possible that the timer was actually super short (a few
    532   // milliseconds) and the timer expired normally before we called
    533   // |timer_gettime|. Worst case, |alarm_expired| is signaled twice for that
    534   // alarm. Nothing bad should happen in that case though since the callback
    535   // dispatch function checks to make sure the timer at the head of the list
    536   // actually expired.
    537   if (timer_set) {
    538     struct itimerspec time_to_expire;
    539     timer_gettime(timer, &time_to_expire);
    540     if (time_to_expire.it_value.tv_sec == 0 &&
    541         time_to_expire.it_value.tv_nsec == 0) {
    542       LOG_DEBUG(
    543           LOG_TAG,
    544           "%s alarm expiration too close for posix timers, switching to guns",
    545           __func__);
    546       semaphore_post(alarm_expired);
    547     }
    548   }
    549 }
    550 
    551 static void alarm_register_processing_queue(fixed_queue_t* queue,
    552                                             thread_t* thread) {
    553   CHECK(queue != NULL);
    554   CHECK(thread != NULL);
    555 
    556   fixed_queue_register_dequeue(queue, thread_get_reactor(thread),
    557                                alarm_queue_ready, NULL);
    558 }
    559 
    560 static void alarm_ready_generic(alarm_t* alarm,
    561                                 std::unique_lock<std::mutex>& lock) {
    562   if (alarm == NULL) {
    563     return;  // The alarm was probably canceled
    564   }
    565   //
    566   // If the alarm is not periodic, we've fully serviced it now, and can reset
    567   // some of its internal state. This is useful to distinguish between expired
    568   // alarms and active ones.
    569   //
    570   alarm_callback_t callback = alarm->callback;
    571   void* data = alarm->data;
    572   period_ms_t deadline = alarm->deadline;
    573   if (alarm->is_periodic) {
    574     // The periodic alarm has been rescheduled and alarm->deadline has been
    575     // updated, hence we need to use the previous deadline.
    576     deadline = alarm->prev_deadline;
    577   } else {
    578     alarm->deadline = 0;
    579     alarm->callback = NULL;
    580     alarm->data = NULL;
    581     alarm->queue = NULL;
    582   }
    583 
    584   std::lock_guard<std::recursive_mutex> cb_lock(*alarm->callback_mutex);
    585   lock.unlock();
    586 
    587   period_ms_t t0 = now();
    588   callback(data);
    589   period_ms_t t1 = now();
    590 
    591   // Update the statistics
    592   CHECK(t1 >= t0);
    593   period_ms_t delta = t1 - t0;
    594   update_scheduling_stats(&alarm->stats, t0, deadline, delta);
    595 }
    596 
    597 static void alarm_ready_mloop(alarm_t* alarm) {
    598   std::unique_lock<std::mutex> lock(alarms_mutex);
    599   alarm_ready_generic(alarm, lock);
    600 }
    601 
    602 static void alarm_queue_ready(fixed_queue_t* queue, UNUSED_ATTR void* context) {
    603   CHECK(queue != NULL);
    604 
    605   std::unique_lock<std::mutex> lock(alarms_mutex);
    606   alarm_t* alarm = (alarm_t*)fixed_queue_try_dequeue(queue);
    607   alarm_ready_generic(alarm, lock);
    608 }
    609 
    610 // Callback function for wake alarms and our posix timer
    611 static void timer_callback(UNUSED_ATTR void* ptr) {
    612   semaphore_post(alarm_expired);
    613 }
    614 
    615 // Function running on |dispatcher_thread| that performs the following:
    616 //   (1) Receives a signal using |alarm_exired| that the alarm has expired
    617 //   (2) Dispatches the alarm callback for processing by the corresponding
    618 // thread for that alarm.
    619 static void callback_dispatch(UNUSED_ATTR void* context) {
    620   while (true) {
    621     semaphore_wait(alarm_expired);
    622     if (!dispatcher_thread_active) break;
    623 
    624     std::lock_guard<std::mutex> lock(alarms_mutex);
    625     alarm_t* alarm;
    626 
    627     // Take into account that the alarm may get cancelled before we get to it.
    628     // We're done here if there are no alarms or the alarm at the front is in
    629     // the future. Exit right away since there's nothing left to do.
    630     if (list_is_empty(alarms) ||
    631         (alarm = static_cast<alarm_t*>(list_front(alarms)))->deadline > now()) {
    632       reschedule_root_alarm();
    633       continue;
    634     }
    635 
    636     list_remove(alarms, alarm);
    637 
    638     if (alarm->is_periodic) {
    639       alarm->prev_deadline = alarm->deadline;
    640       schedule_next_instance(alarm);
    641       alarm->stats.rescheduled_count++;
    642     }
    643     reschedule_root_alarm();
    644 
    645     // Enqueue the alarm for processing
    646     if (alarm->for_msg_loop) {
    647       if (!get_message_loop()) {
    648         LOG_ERROR(LOG_TAG, "%s: message loop already NULL. Alarm: %s", __func__,
    649                   alarm->stats.name);
    650         continue;
    651       }
    652 
    653       alarm->closure.i.Reset(Bind(alarm_ready_mloop, alarm));
    654       get_message_loop()->PostTask(FROM_HERE, alarm->closure.i.callback());
    655     } else {
    656       fixed_queue_enqueue(alarm->queue, alarm);
    657     }
    658   }
    659 
    660   LOG_DEBUG(LOG_TAG, "%s Callback thread exited", __func__);
    661 }
    662 
    663 static bool timer_create_internal(const clockid_t clock_id, timer_t* timer) {
    664   CHECK(timer != NULL);
    665 
    666   struct sigevent sigevent;
    667   // create timer with RT priority thread
    668   pthread_attr_t thread_attr;
    669   pthread_attr_init(&thread_attr);
    670   pthread_attr_setschedpolicy(&thread_attr, SCHED_FIFO);
    671   struct sched_param param;
    672   param.sched_priority = THREAD_RT_PRIORITY;
    673   pthread_attr_setschedparam(&thread_attr, &param);
    674 
    675   memset(&sigevent, 0, sizeof(sigevent));
    676   sigevent.sigev_notify = SIGEV_THREAD;
    677   sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
    678   sigevent.sigev_notify_attributes = &thread_attr;
    679   if (timer_create(clock_id, &sigevent, timer) == -1) {
    680     LOG_ERROR(LOG_TAG, "%s unable to create timer with clock %d: %s", __func__,
    681               clock_id, strerror(errno));
    682     if (clock_id == CLOCK_BOOTTIME_ALARM) {
    683       LOG_ERROR(LOG_TAG,
    684                 "The kernel might not have support for "
    685                 "timer_create(CLOCK_BOOTTIME_ALARM): "
    686                 "https://lwn.net/Articles/429925/");
    687       LOG_ERROR(LOG_TAG,
    688                 "See following patches: "
    689                 "https://git.kernel.org/cgit/linux/kernel/git/torvalds/"
    690                 "linux.git/log/?qt=grep&q=CLOCK_BOOTTIME_ALARM");
    691     }
    692     return false;
    693   }
    694 
    695   return true;
    696 }
    697 
    698 static void update_scheduling_stats(alarm_stats_t* stats, period_ms_t now_ms,
    699                                     period_ms_t deadline_ms,
    700                                     period_ms_t execution_delta_ms) {
    701   stats->total_updates++;
    702   stats->last_update_ms = now_ms;
    703 
    704   update_stat(&stats->callback_execution, execution_delta_ms);
    705 
    706   if (deadline_ms < now_ms) {
    707     // Overdue scheduling
    708     period_ms_t delta_ms = now_ms - deadline_ms;
    709     update_stat(&stats->overdue_scheduling, delta_ms);
    710   } else if (deadline_ms > now_ms) {
    711     // Premature scheduling
    712     period_ms_t delta_ms = deadline_ms - now_ms;
    713     update_stat(&stats->premature_scheduling, delta_ms);
    714   }
    715 }
    716 
    717 static void dump_stat(int fd, stat_t* stat, const char* description) {
    718   period_ms_t average_time_ms = 0;
    719   if (stat->count != 0) average_time_ms = stat->total_ms / stat->count;
    720 
    721   dprintf(fd, "%-51s: %llu / %llu / %llu\n", description,
    722           (unsigned long long)stat->total_ms, (unsigned long long)stat->max_ms,
    723           (unsigned long long)average_time_ms);
    724 }
    725 
    726 void alarm_debug_dump(int fd) {
    727   dprintf(fd, "\nBluetooth Alarms Statistics:\n");
    728 
    729   std::lock_guard<std::mutex> lock(alarms_mutex);
    730 
    731   if (alarms == NULL) {
    732     dprintf(fd, "  None\n");
    733     return;
    734   }
    735 
    736   period_ms_t just_now = now();
    737 
    738   dprintf(fd, "  Total Alarms: %zu\n\n", list_length(alarms));
    739 
    740   // Dump info for each alarm
    741   for (list_node_t* node = list_begin(alarms); node != list_end(alarms);
    742        node = list_next(node)) {
    743     alarm_t* alarm = (alarm_t*)list_node(node);
    744     alarm_stats_t* stats = &alarm->stats;
    745 
    746     dprintf(fd, "  Alarm : %s (%s)\n", stats->name,
    747             (alarm->is_periodic) ? "PERIODIC" : "SINGLE");
    748 
    749     dprintf(fd, "%-51s: %zu / %zu / %zu / %zu\n",
    750             "    Action counts (sched/resched/exec/cancel)",
    751             stats->scheduled_count, stats->rescheduled_count,
    752             stats->callback_execution.count, stats->canceled_count);
    753 
    754     dprintf(fd, "%-51s: %zu / %zu\n",
    755             "    Deviation counts (overdue/premature)",
    756             stats->overdue_scheduling.count, stats->premature_scheduling.count);
    757 
    758     dprintf(fd, "%-51s: %llu / %llu / %lld\n",
    759             "    Time in ms (since creation/interval/remaining)",
    760             (unsigned long long)(just_now - alarm->creation_time),
    761             (unsigned long long)alarm->period,
    762             (long long)(alarm->deadline - just_now));
    763 
    764     dump_stat(fd, &stats->callback_execution,
    765               "    Callback execution time in ms (total/max/avg)");
    766 
    767     dump_stat(fd, &stats->overdue_scheduling,
    768               "    Overdue scheduling time in ms (total/max/avg)");
    769 
    770     dump_stat(fd, &stats->premature_scheduling,
    771               "    Premature scheduling time in ms (total/max/avg)");
    772 
    773     dprintf(fd, "\n");
    774   }
    775 }
    776