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