OSDN Git Service

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