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