• 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 #define LOG_TAG "bt_osi_alarm"
20 
21 #include <assert.h>
22 #include <errno.h>
23 #include <hardware/bluetooth.h>
24 #include <inttypes.h>
25 #include <malloc.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <time.h>
29 
30 #include "osi/include/alarm.h"
31 #include "osi/include/allocator.h"
32 #include "osi/include/list.h"
33 #include "osi/include/log.h"
34 #include "osi/include/osi.h"
35 #include "osi/include/semaphore.h"
36 #include "osi/include/thread.h"
37 
38 // Make callbacks run at high thread priority. Some callbacks are used for audio
39 // related timer tasks as well as re-transmissions etc. Since we at this point
40 // cannot differentiate what callback we are dealing with, assume high priority
41 // for now.
42 // TODO(eisenbach): Determine correct thread priority (from parent?/per alarm?)
43 static const int CALLBACK_THREAD_PRIORITY_HIGH = -19;
44 
45 struct alarm_t {
46   // The lock is held while the callback for this alarm is being executed.
47   // It allows us to release the coarse-grained monitor lock while a potentially
48   // long-running callback is executing. |alarm_cancel| uses this lock to provide
49   // a guarantee to its caller that the callback will not be in progress when it
50   // returns.
51   pthread_mutex_t callback_lock;
52   period_ms_t created;
53   period_ms_t period;
54   period_ms_t deadline;
55   bool is_periodic;
56   alarm_callback_t callback;
57   void *data;
58 };
59 
60 extern bt_os_callouts_t *bt_os_callouts;
61 
62 // If the next wakeup time is less than this threshold, we should acquire
63 // a wakelock instead of setting a wake alarm so we're not bouncing in
64 // and out of suspend frequently. This value is externally visible to allow
65 // unit tests to run faster. It should not be modified by production code.
66 int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 3000;
67 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
68 static const char *WAKE_LOCK_ID = "bluedroid_timer";
69 
70 // This mutex ensures that the |alarm_set|, |alarm_cancel|, and alarm callback
71 // functions execute serially and not concurrently. As a result, this mutex also
72 // protects the |alarms| list.
73 static pthread_mutex_t monitor;
74 static list_t *alarms;
75 static timer_t timer;
76 static bool timer_set;
77 
78 // All alarm callbacks are dispatched from |callback_thread|
79 static thread_t *callback_thread;
80 static bool callback_thread_active;
81 static semaphore_t *alarm_expired;
82 
83 static bool lazy_initialize(void);
84 static period_ms_t now(void);
85 static void alarm_set_internal(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data, bool is_periodic);
86 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule);
87 static void reschedule_root_alarm(void);
88 static void timer_callback(void *data);
89 static void callback_dispatch(void *context);
90 
alarm_new(void)91 alarm_t *alarm_new(void) {
92   // Make sure we have a list we can insert alarms into.
93   if (!alarms && !lazy_initialize())
94     return NULL;
95 
96   pthread_mutexattr_t attr;
97   pthread_mutexattr_init(&attr);
98 
99   alarm_t *ret = osi_calloc(sizeof(alarm_t));
100   if (!ret) {
101     LOG_ERROR("%s unable to allocate memory for alarm.", __func__);
102     goto error;
103   }
104 
105   // Make this a recursive mutex to make it safe to call |alarm_cancel| from
106   // within the callback function of the alarm.
107   int error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
108   if (error) {
109     LOG_ERROR("%s unable to create a recursive mutex: %s", __func__, strerror(error));
110     goto error;
111   }
112 
113   error = pthread_mutex_init(&ret->callback_lock, &attr);
114   if (error) {
115     LOG_ERROR("%s unable to initialize mutex: %s", __func__, strerror(error));
116     goto error;
117   }
118 
119   pthread_mutexattr_destroy(&attr);
120   return ret;
121 
122 error:;
123   pthread_mutexattr_destroy(&attr);
124   osi_free(ret);
125   return NULL;
126 }
127 
alarm_free(alarm_t * alarm)128 void alarm_free(alarm_t *alarm) {
129   if (!alarm)
130     return;
131 
132   alarm_cancel(alarm);
133   pthread_mutex_destroy(&alarm->callback_lock);
134   osi_free(alarm);
135 }
136 
alarm_get_remaining_ms(const alarm_t * alarm)137 period_ms_t alarm_get_remaining_ms(const alarm_t *alarm) {
138   assert(alarm != NULL);
139   period_ms_t remaining_ms = 0;
140 
141   pthread_mutex_lock(&monitor);
142   if (alarm->deadline)
143     remaining_ms = alarm->deadline - now();
144   pthread_mutex_unlock(&monitor);
145 
146   return remaining_ms;
147 }
148 
alarm_set(alarm_t * alarm,period_ms_t deadline,alarm_callback_t cb,void * data)149 void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
150   alarm_set_internal(alarm, deadline, cb, data, false);
151 }
152 
alarm_set_periodic(alarm_t * alarm,period_ms_t period,alarm_callback_t cb,void * data)153 void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data) {
154   alarm_set_internal(alarm, period, cb, data, true);
155 }
156 
157 // 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,bool is_periodic)158 static void alarm_set_internal(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data, bool is_periodic) {
159   assert(alarms != NULL);
160   assert(alarm != NULL);
161   assert(cb != NULL);
162 
163   pthread_mutex_lock(&monitor);
164 
165   alarm->created = now();
166   alarm->is_periodic = is_periodic;
167   alarm->period = period;
168   alarm->callback = cb;
169   alarm->data = data;
170 
171   schedule_next_instance(alarm, false);
172 
173   pthread_mutex_unlock(&monitor);
174 }
175 
alarm_cancel(alarm_t * alarm)176 void alarm_cancel(alarm_t *alarm) {
177   assert(alarms != NULL);
178   assert(alarm != NULL);
179 
180   pthread_mutex_lock(&monitor);
181 
182   bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
183 
184   list_remove(alarms, alarm);
185   alarm->deadline = 0;
186   alarm->callback = NULL;
187   alarm->data = NULL;
188 
189   if (needs_reschedule)
190     reschedule_root_alarm();
191 
192   pthread_mutex_unlock(&monitor);
193 
194   // If the callback for |alarm| is in progress, wait here until it completes.
195   pthread_mutex_lock(&alarm->callback_lock);
196   pthread_mutex_unlock(&alarm->callback_lock);
197 }
198 
alarm_cleanup(void)199 void alarm_cleanup(void) {
200   // If lazy_initialize never ran there is nothing to do
201   if (!alarms)
202     return;
203 
204   callback_thread_active = false;
205   semaphore_post(alarm_expired);
206   thread_free(callback_thread);
207   callback_thread = NULL;
208 
209   semaphore_free(alarm_expired);
210   alarm_expired = NULL;
211   timer_delete(&timer);
212   list_free(alarms);
213   alarms = NULL;
214 
215   pthread_mutex_destroy(&monitor);
216 }
217 
lazy_initialize(void)218 static bool lazy_initialize(void) {
219   assert(alarms == NULL);
220 
221   pthread_mutex_init(&monitor, NULL);
222 
223   alarms = list_new(NULL);
224   if (!alarms) {
225     LOG_ERROR("%s unable to allocate alarm list.", __func__);
226     return false;
227   }
228 
229   struct sigevent sigevent;
230   memset(&sigevent, 0, sizeof(sigevent));
231   sigevent.sigev_notify = SIGEV_THREAD;
232   sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
233   if (timer_create(CLOCK_ID, &sigevent, &timer) == -1) {
234     LOG_ERROR("%s unable to create timer: %s", __func__, strerror(errno));
235     return false;
236   }
237 
238   alarm_expired = semaphore_new(0);
239   if (!alarm_expired) {
240     LOG_ERROR("%s unable to create alarm expired semaphore", __func__);
241     return false;
242   }
243 
244   callback_thread_active = true;
245   callback_thread = thread_new("alarm_callbacks");
246   if (!callback_thread) {
247     LOG_ERROR("%s unable to create alarm callback thread.", __func__);
248     return false;
249   }
250 
251   thread_set_priority(callback_thread, CALLBACK_THREAD_PRIORITY_HIGH);
252   thread_post(callback_thread, callback_dispatch, NULL);
253   return true;
254 }
255 
now(void)256 static period_ms_t now(void) {
257   assert(alarms != NULL);
258 
259   struct timespec ts;
260   if (clock_gettime(CLOCK_ID, &ts) == -1) {
261     LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
262     return 0;
263   }
264 
265   return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
266 }
267 
268 // Must be called with monitor held
schedule_next_instance(alarm_t * alarm,bool force_reschedule)269 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule) {
270   // If the alarm is currently set and it's at the start of the list,
271   // we'll need to re-schedule since we've adjusted the earliest deadline.
272   bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
273   if (alarm->callback)
274     list_remove(alarms, alarm);
275 
276   // Calculate the next deadline for this alarm
277   period_ms_t just_now = now();
278   period_ms_t ms_into_period = alarm->is_periodic ? ((just_now - alarm->created) % alarm->period) : 0;
279   alarm->deadline = just_now + (alarm->period - ms_into_period);
280 
281   // Add it into the timer list sorted by deadline (earliest deadline first).
282   if (list_is_empty(alarms) || ((alarm_t *)list_front(alarms))->deadline >= alarm->deadline)
283     list_prepend(alarms, alarm);
284   else
285     for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
286       list_node_t *next = list_next(node);
287       if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
288         list_insert_after(alarms, node, alarm);
289         break;
290       }
291     }
292 
293   // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
294   if (force_reschedule || needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
295     reschedule_root_alarm();
296 }
297 
298 // NOTE: must be called with monitor lock.
reschedule_root_alarm(void)299 static void reschedule_root_alarm(void) {
300   bool timer_was_set = timer_set;
301   assert(alarms != NULL);
302 
303   // If used in a zeroed state, disarms the timer
304   struct itimerspec wakeup_time;
305   memset(&wakeup_time, 0, sizeof(wakeup_time));
306 
307   if (list_is_empty(alarms))
308     goto done;
309 
310   alarm_t *next = list_front(alarms);
311   int64_t next_expiration = next->deadline - now();
312   if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
313     if (!timer_set) {
314       int status = bt_os_callouts->acquire_wake_lock(WAKE_LOCK_ID);
315       if (status != BT_STATUS_SUCCESS) {
316         LOG_ERROR("%s unable to acquire wake lock: %d", __func__, status);
317         goto done;
318       }
319     }
320 
321     wakeup_time.it_value.tv_sec = (next->deadline / 1000);
322     wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
323   } else {
324     if (!bt_os_callouts->set_wake_alarm(next_expiration, true, timer_callback, NULL))
325       LOG_ERROR("%s unable to set wake alarm for %" PRId64 "ms.", __func__, next_expiration);
326   }
327 
328 done:
329   timer_set = wakeup_time.it_value.tv_sec != 0 || wakeup_time.it_value.tv_nsec != 0;
330   if (timer_was_set && !timer_set) {
331     bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
332   }
333 
334   if (timer_settime(timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
335     LOG_ERROR("%s unable to set timer: %s", __func__, strerror(errno));
336 
337   // If next expiration was in the past (e.g. short timer that got context switched)
338   // then the timer might have diarmed itself. Detect this case and work around it
339   // by manually signalling the |alarm_expired| semaphore.
340   //
341   // It is possible that the timer was actually super short (a few milliseconds)
342   // and the timer expired normally before we called |timer_gettime|. Worst case,
343   // |alarm_expired| is signaled twice for that alarm. Nothing bad should happen in
344   // that case though since the callback dispatch function checks to make sure the
345   // timer at the head of the list actually expired.
346   if (timer_set) {
347     struct itimerspec time_to_expire;
348     timer_gettime(timer, &time_to_expire);
349     if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) {
350       LOG_ERROR("%s alarm expiration too close for posix timers, switching to guns", __func__);
351       semaphore_post(alarm_expired);
352     }
353   }
354 }
355 
356 // Callback function for wake alarms and our posix timer
timer_callback(UNUSED_ATTR void * ptr)357 static void timer_callback(UNUSED_ATTR void *ptr) {
358   semaphore_post(alarm_expired);
359 }
360 
361 // Function running on |callback_thread| that dispatches alarm callbacks upon
362 // alarm expiration, which is signaled using |alarm_expired|.
callback_dispatch(UNUSED_ATTR void * context)363 static void callback_dispatch(UNUSED_ATTR void *context) {
364   while (true) {
365     semaphore_wait(alarm_expired);
366     if (!callback_thread_active)
367       break;
368 
369     pthread_mutex_lock(&monitor);
370     alarm_t *alarm;
371 
372     // Take into account that the alarm may get cancelled before we get to it.
373     // We're done here if there are no alarms or the alarm at the front is in
374     // the future. Release the monitor lock and exit right away since there's
375     // nothing left to do.
376     if (list_is_empty(alarms) || (alarm = list_front(alarms))->deadline > now()) {
377       reschedule_root_alarm();
378       pthread_mutex_unlock(&monitor);
379       continue;
380     }
381 
382     list_remove(alarms, alarm);
383 
384     alarm_callback_t callback = alarm->callback;
385     void *data = alarm->data;
386 
387     if (alarm->is_periodic) {
388       schedule_next_instance(alarm, true);
389     } else {
390       reschedule_root_alarm();
391 
392       alarm->deadline = 0;
393       alarm->callback = NULL;
394       alarm->data = NULL;
395     }
396 
397     // Downgrade lock.
398     pthread_mutex_lock(&alarm->callback_lock);
399     pthread_mutex_unlock(&monitor);
400 
401     callback(data);
402 
403     pthread_mutex_unlock(&alarm->callback_lock);
404   }
405 
406   LOG_DEBUG("%s Callback thread exited", __func__);
407 }
408