OSDN Git Service

DO NOT MERGE Use POSIX timer API for wake alarms instead of OSI callouts.
[android-x86/system-bt.git] / osi / src / alarm.c
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 <hardware_legacy/power.h>
25 #include <inttypes.h>
26 #include <malloc.h>
27 #include <string.h>
28 #include <signal.h>
29 #include <time.h>
30
31 #include "osi/include/alarm.h"
32 #include "osi/include/allocator.h"
33 #include "osi/include/list.h"
34 #include "osi/include/log.h"
35 #include "osi/include/osi.h"
36 #include "osi/include/semaphore.h"
37 #include "osi/include/thread.h"
38
39 struct alarm_t {
40   // The lock is held while the callback for this alarm is being executed.
41   // It allows us to release the coarse-grained monitor lock while a potentially
42   // long-running callback is executing. |alarm_cancel| uses this lock to provide
43   // a guarantee to its caller that the callback will not be in progress when it
44   // returns.
45   pthread_mutex_t callback_lock;
46   period_ms_t created;
47   period_ms_t period;
48   period_ms_t deadline;
49   bool is_periodic;
50   alarm_callback_t callback;
51   void *data;
52 };
53
54 extern bt_os_callouts_t *bt_os_callouts;
55
56 // If the next wakeup time is less than this threshold, we should acquire
57 // a wakelock instead of setting a wake alarm so we're not bouncing in
58 // and out of suspend frequently. This value is externally visible to allow
59 // unit tests to run faster. It should not be modified by production code.
60 int64_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 3000;
61 static const clockid_t CLOCK_ID = CLOCK_BOOTTIME;
62 static const clockid_t CLOCK_ID_ALARM = CLOCK_BOOTTIME_ALARM;
63 static const char *WAKE_LOCK_ID = "bluedroid_timer";
64
65 // This mutex ensures that the |alarm_set|, |alarm_cancel|, and alarm callback
66 // functions execute serially and not concurrently. As a result, this mutex also
67 // protects the |alarms| list.
68 static pthread_mutex_t monitor;
69 static list_t *alarms;
70 static timer_t timer;
71 static timer_t wakeup_timer;
72 static bool timer_set;
73
74 // All alarm callbacks are dispatched from |callback_thread|
75 static thread_t *callback_thread;
76 static bool callback_thread_active;
77 static semaphore_t *alarm_expired;
78
79 static bool lazy_initialize(void);
80 static period_ms_t now(void);
81 static void alarm_set_internal(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data, bool is_periodic);
82 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule);
83 static void reschedule_root_alarm(void);
84 static void timer_callback(void *data);
85 static void callback_dispatch(void *context);
86 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer);
87
88 alarm_t *alarm_new(void) {
89   // Make sure we have a list we can insert alarms into.
90   if (!alarms && !lazy_initialize())
91     return NULL;
92
93   pthread_mutexattr_t attr;
94   pthread_mutexattr_init(&attr);
95
96   alarm_t *ret = osi_calloc(sizeof(alarm_t));
97   if (!ret) {
98     LOG_ERROR("%s unable to allocate memory for alarm.", __func__);
99     goto error;
100   }
101
102   // Make this a recursive mutex to make it safe to call |alarm_cancel| from
103   // within the callback function of the alarm.
104   int error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
105   if (error) {
106     LOG_ERROR("%s unable to create a recursive mutex: %s", __func__, strerror(error));
107     goto error;
108   }
109
110   error = pthread_mutex_init(&ret->callback_lock, &attr);
111   if (error) {
112     LOG_ERROR("%s unable to initialize mutex: %s", __func__, strerror(error));
113     goto error;
114   }
115
116   pthread_mutexattr_destroy(&attr);
117   return ret;
118
119 error:;
120   pthread_mutexattr_destroy(&attr);
121   osi_free(ret);
122   return NULL;
123 }
124
125 void alarm_free(alarm_t *alarm) {
126   if (!alarm)
127     return;
128
129   alarm_cancel(alarm);
130   pthread_mutex_destroy(&alarm->callback_lock);
131   osi_free(alarm);
132 }
133
134 period_ms_t alarm_get_remaining_ms(const alarm_t *alarm) {
135   assert(alarm != NULL);
136   period_ms_t remaining_ms = 0;
137
138   pthread_mutex_lock(&monitor);
139   if (alarm->deadline)
140     remaining_ms = alarm->deadline - now();
141   pthread_mutex_unlock(&monitor);
142
143   return remaining_ms;
144 }
145
146 void alarm_set(alarm_t *alarm, period_ms_t deadline, alarm_callback_t cb, void *data) {
147   alarm_set_internal(alarm, deadline, cb, data, false);
148 }
149
150 void alarm_set_periodic(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data) {
151   alarm_set_internal(alarm, period, cb, data, true);
152 }
153
154 // Runs in exclusion with alarm_cancel and timer_callback.
155 static void alarm_set_internal(alarm_t *alarm, period_ms_t period, alarm_callback_t cb, void *data, bool is_periodic) {
156   assert(alarms != NULL);
157   assert(alarm != NULL);
158   assert(cb != NULL);
159
160   pthread_mutex_lock(&monitor);
161
162   alarm->created = now();
163   alarm->is_periodic = is_periodic;
164   alarm->period = period;
165   alarm->callback = cb;
166   alarm->data = data;
167
168   schedule_next_instance(alarm, false);
169
170   pthread_mutex_unlock(&monitor);
171 }
172
173 void alarm_cancel(alarm_t *alarm) {
174   assert(alarms != NULL);
175   assert(alarm != NULL);
176
177   pthread_mutex_lock(&monitor);
178
179   bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
180
181   list_remove(alarms, alarm);
182   alarm->deadline = 0;
183   alarm->callback = NULL;
184   alarm->data = NULL;
185
186   if (needs_reschedule)
187     reschedule_root_alarm();
188
189   pthread_mutex_unlock(&monitor);
190
191   // If the callback for |alarm| is in progress, wait here until it completes.
192   pthread_mutex_lock(&alarm->callback_lock);
193   pthread_mutex_unlock(&alarm->callback_lock);
194 }
195
196 void alarm_cleanup(void) {
197   // If lazy_initialize never ran there is nothing to do
198   if (!alarms)
199     return;
200
201   callback_thread_active = false;
202   semaphore_post(alarm_expired);
203   thread_free(callback_thread);
204   callback_thread = NULL;
205
206   semaphore_free(alarm_expired);
207   alarm_expired = NULL;
208   timer_delete(&timer);
209   list_free(alarms);
210   alarms = NULL;
211
212   pthread_mutex_destroy(&monitor);
213 }
214
215 static bool lazy_initialize(void) {
216   assert(alarms == NULL);
217
218   // timer_t doesn't have an invalid value so we must track whether
219   // the |timer| variable is valid ourselves.
220   bool timer_initialized = false;
221   bool wakeup_timer_initialized = false;
222
223   pthread_mutex_init(&monitor, NULL);
224
225   alarms = list_new(NULL);
226   if (!alarms) {
227     LOG_ERROR("%s unable to allocate alarm list.", __func__);
228     goto error;
229   }
230
231   if (!timer_create_internal(CLOCK_ID, &timer))
232     goto error;
233   timer_initialized = true;
234
235   if (!timer_create_internal(CLOCK_ID_ALARM, &wakeup_timer))
236     goto error;
237   wakeup_timer_initialized = true;
238
239   alarm_expired = semaphore_new(0);
240   if (!alarm_expired) {
241     LOG_ERROR("%s unable to create alarm expired semaphore", __func__);
242     goto error;
243   }
244
245   callback_thread_active = true;
246   callback_thread = thread_new("alarm_callbacks");
247   if (!callback_thread) {
248     LOG_ERROR("%s unable to create alarm callback thread.", __func__);
249     goto error;
250   }
251
252   thread_post(callback_thread, callback_dispatch, NULL);
253   return true;
254
255 error:
256   thread_free(callback_thread);
257   callback_thread = NULL;
258
259   callback_thread_active = false;
260
261   semaphore_free(alarm_expired);
262   alarm_expired = NULL;
263
264   if (wakeup_timer_initialized)
265     timer_delete(wakeup_timer);
266
267   if (timer_initialized)
268     timer_delete(timer);
269
270   list_free(alarms);
271   alarms = NULL;
272
273   pthread_mutex_destroy(&monitor);
274
275   return false;
276 }
277
278 static period_ms_t now(void) {
279   assert(alarms != NULL);
280
281   struct timespec ts;
282   if (clock_gettime(CLOCK_ID, &ts) == -1) {
283     LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
284     return 0;
285   }
286
287   return (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
288 }
289
290 // Must be called with monitor held
291 static void schedule_next_instance(alarm_t *alarm, bool force_reschedule) {
292   // If the alarm is currently set and it's at the start of the list,
293   // we'll need to re-schedule since we've adjusted the earliest deadline.
294   bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm);
295   if (alarm->callback)
296     list_remove(alarms, alarm);
297
298   // Calculate the next deadline for this alarm
299   period_ms_t just_now = now();
300   period_ms_t ms_into_period = alarm->is_periodic ? ((just_now - alarm->created) % alarm->period) : 0;
301   alarm->deadline = just_now + (alarm->period - ms_into_period);
302
303   // Add it into the timer list sorted by deadline (earliest deadline first).
304   if (list_is_empty(alarms) || ((alarm_t *)list_front(alarms))->deadline >= alarm->deadline)
305     list_prepend(alarms, alarm);
306   else
307     for (list_node_t *node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) {
308       list_node_t *next = list_next(node);
309       if (next == list_end(alarms) || ((alarm_t *)list_node(next))->deadline >= alarm->deadline) {
310         list_insert_after(alarms, node, alarm);
311         break;
312       }
313     }
314
315   // If the new alarm has the earliest deadline, we need to re-evaluate our schedule.
316   if (force_reschedule || needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm))
317     reschedule_root_alarm();
318 }
319
320 // NOTE: must be called with monitor lock.
321 static void reschedule_root_alarm(void) {
322   assert(alarms != NULL);
323
324   const bool timer_was_set = timer_set;
325
326   // If used in a zeroed state, disarms the timer.
327   struct itimerspec timer_time;
328   memset(&timer_time, 0, sizeof(timer_time));
329
330   if (list_is_empty(alarms))
331     goto done;
332
333   const alarm_t *next = list_front(alarms);
334   const int64_t next_expiration = next->deadline - now();
335   if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
336     if (!timer_set) {
337       int status = acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
338       if (status != (int) strlen(WAKE_LOCK_ID)) {
339         LOG_ERROR("%s unable to acquire wake lock: %d", __func__, status);
340         goto done;
341       }
342     }
343
344     timer_time.it_value.tv_sec = (next->deadline / 1000);
345     timer_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
346
347     // It is entirely unsafe to call timer_settime(2) with a zeroed timerspec for
348     // timers with *_ALARM clock IDs. Although the man page states that the timer
349     // would be canceled, the current behavior (as of Linux kernel 3.17) is that
350     // the callback is issued immediately. The only way to cancel an *_ALARM timer
351     // is to delete the timer. But unfortunately, deleting and re-creating a timer
352     // is rather expensive; every timer_create(2) spawns a new thread. So we simply
353     // set the timer to fire at the largest possible time.
354     //
355     // If we've reached this code path, we're going to grab a wake lock and wait for
356     // the next timer to fire. In that case, there's no reason to have a pending wakeup
357     // timer so we simply cancel it.
358     struct itimerspec end_of_time;
359     memset(&end_of_time, 0, sizeof(end_of_time));
360     end_of_time.it_value.tv_sec = (time_t)((1LL << (sizeof(time_t) * 8 - 1)) - 1);
361     timer_settime(wakeup_timer, TIMER_ABSTIME, &end_of_time, NULL);
362   } else {
363     // WARNING: do not attempt to use relative timers with *_ALARM clock IDs
364     // in kernels before 3.17 unless you have the following patch:
365     // https://lkml.org/lkml/2014/7/7/576
366     struct itimerspec wakeup_time;
367     memset(&wakeup_time, 0, sizeof(wakeup_time));
368     wakeup_time.it_value.tv_sec = (next->deadline / 1000);
369     wakeup_time.it_value.tv_nsec = (next->deadline % 1000) * 1000000LL;
370     if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
371       LOG_ERROR("%s unable to set wakeup timer: %s", __func__, strerror(errno));
372   }
373
374 done:
375   timer_set = timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0;
376   if (timer_was_set && !timer_set) {
377     release_wake_lock(WAKE_LOCK_ID);
378   }
379
380   if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1)
381     LOG_ERROR("%s unable to set timer: %s", __func__, strerror(errno));
382
383   // If next expiration was in the past (e.g. short timer that got context switched)
384   // then the timer might have diarmed itself. Detect this case and work around it
385   // by manually signalling the |alarm_expired| semaphore.
386   //
387   // It is possible that the timer was actually super short (a few milliseconds)
388   // and the timer expired normally before we called |timer_gettime|. Worst case,
389   // |alarm_expired| is signaled twice for that alarm. Nothing bad should happen in
390   // that case though since the callback dispatch function checks to make sure the
391   // timer at the head of the list actually expired.
392   if (timer_set) {
393     struct itimerspec time_to_expire;
394     timer_gettime(timer, &time_to_expire);
395     if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) {
396       LOG_ERROR("%s alarm expiration too close for posix timers, switching to guns", __func__);
397       semaphore_post(alarm_expired);
398     }
399   }
400 }
401
402 // Callback function for wake alarms and our posix timer
403 static void timer_callback(UNUSED_ATTR void *ptr) {
404   semaphore_post(alarm_expired);
405 }
406
407 // Function running on |callback_thread| that dispatches alarm callbacks upon
408 // alarm expiration, which is signaled using |alarm_expired|.
409 static void callback_dispatch(UNUSED_ATTR void *context) {
410   while (true) {
411     semaphore_wait(alarm_expired);
412     if (!callback_thread_active)
413       break;
414
415     pthread_mutex_lock(&monitor);
416     alarm_t *alarm;
417
418     // Take into account that the alarm may get cancelled before we get to it.
419     // We're done here if there are no alarms or the alarm at the front is in
420     // the future. Release the monitor lock and exit right away since there's
421     // nothing left to do.
422     if (list_is_empty(alarms) || (alarm = list_front(alarms))->deadline > now()) {
423       reschedule_root_alarm();
424       pthread_mutex_unlock(&monitor);
425       continue;
426     }
427
428     list_remove(alarms, alarm);
429
430     alarm_callback_t callback = alarm->callback;
431     void *data = alarm->data;
432
433     if (alarm->is_periodic) {
434       schedule_next_instance(alarm, true);
435     } else {
436       reschedule_root_alarm();
437
438       alarm->deadline = 0;
439       alarm->callback = NULL;
440       alarm->data = NULL;
441     }
442
443     // Downgrade lock.
444     pthread_mutex_lock(&alarm->callback_lock);
445     pthread_mutex_unlock(&monitor);
446
447     callback(data);
448
449     pthread_mutex_unlock(&alarm->callback_lock);
450   }
451
452   LOG_DEBUG("%s Callback thread exited", __func__);
453 }
454
455 static bool timer_create_internal(const clockid_t clock_id, timer_t *timer) {
456   assert(timer != NULL);
457
458   struct sigevent sigevent;
459   memset(&sigevent, 0, sizeof(sigevent));
460   sigevent.sigev_notify = SIGEV_THREAD;
461   sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
462   if (timer_create(clock_id, &sigevent, timer) == -1) {
463     LOG_ERROR("%s unable to create timer with clock %d: %s", __func__, clock_id, strerror(errno));
464     return false;
465   }
466
467   return true;
468 }