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