Home | History | Annotate | Download | only in bionic
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  *  * Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  *  * Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in
     12  *    the documentation and/or other materials provided with the
     13  *    distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
     22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 #include <errno.h>
     30 #include <malloc.h>
     31 #include <pthread.h>
     32 #include <stdatomic.h>
     33 #include <stdio.h>
     34 #include <string.h>
     35 #include <time.h>
     36 
     37 // System calls.
     38 extern "C" int __rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t);
     39 extern "C" int __rt_sigtimedwait(const sigset64_t*, siginfo_t*, const timespec*, size_t);
     40 extern "C" int __timer_create(clockid_t, sigevent*, __kernel_timer_t*);
     41 extern "C" int __timer_delete(__kernel_timer_t);
     42 extern "C" int __timer_getoverrun(__kernel_timer_t);
     43 extern "C" int __timer_gettime(__kernel_timer_t, itimerspec*);
     44 extern "C" int __timer_settime(__kernel_timer_t, int, const itimerspec*, itimerspec*);
     45 
     46 // Most POSIX timers are handled directly by the kernel. We translate SIGEV_THREAD timers
     47 // into SIGEV_THREAD_ID timers so the kernel handles all the time-related stuff and we just
     48 // need to worry about running user code on a thread.
     49 
     50 // We can't use SIGALRM because too many other C library functions throw that around, and since
     51 // they don't send to a specific thread, all threads are eligible to handle the signal and we can
     52 // end up with one of our POSIX timer threads handling it (meaning that the intended recipient
     53 // doesn't). glibc uses SIGRTMIN for its POSIX timer implementation, so in the absence of any
     54 // reason to use anything else, we use that too.
     55 static const int TIMER_SIGNAL = (__SIGRTMIN + 0);
     56 
     57 struct PosixTimer {
     58   __kernel_timer_t kernel_timer_id;
     59 
     60   int sigev_notify;
     61 
     62   // The fields below are only needed for a SIGEV_THREAD timer.
     63   pthread_t callback_thread;
     64   void (*callback)(sigval_t);
     65   sigval_t callback_argument;
     66   atomic_bool deleted;  // Set when the timer is deleted, to prevent further calling of callback.
     67 };
     68 
     69 static __kernel_timer_t to_kernel_timer_id(timer_t timer) {
     70   return reinterpret_cast<PosixTimer*>(timer)->kernel_timer_id;
     71 }
     72 
     73 static void* __timer_thread_start(void* arg) {
     74   PosixTimer* timer = reinterpret_cast<PosixTimer*>(arg);
     75 
     76   sigset64_t sigset = {};
     77   sigaddset64(&sigset, TIMER_SIGNAL);
     78 
     79   while (true) {
     80     // Wait for a signal...
     81     siginfo_t si = {};
     82     if (__rt_sigtimedwait(&sigset, &si, nullptr, sizeof(sigset)) == -1) continue;
     83 
     84     if (si.si_code == SI_TIMER) {
     85       // This signal was sent because a timer fired, so call the callback.
     86 
     87       // All events to the callback will be ignored when the timer is deleted.
     88       if (atomic_load(&timer->deleted) == true) {
     89         continue;
     90       }
     91       timer->callback(timer->callback_argument);
     92     } else if (si.si_code == SI_TKILL) {
     93       // This signal was sent because someone wants us to exit.
     94       free(timer);
     95       return NULL;
     96     }
     97   }
     98 }
     99 
    100 static void __timer_thread_stop(PosixTimer* timer) {
    101   atomic_store(&timer->deleted, true);
    102   pthread_kill(timer->callback_thread, TIMER_SIGNAL);
    103 }
    104 
    105 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_create.html
    106 int timer_create(clockid_t clock_id, sigevent* evp, timer_t* timer_id) {
    107   PosixTimer* timer = reinterpret_cast<PosixTimer*>(malloc(sizeof(PosixTimer)));
    108   if (timer == NULL) {
    109     return -1;
    110   }
    111 
    112   timer->sigev_notify = (evp == NULL) ? SIGEV_SIGNAL : evp->sigev_notify;
    113 
    114   // If not a SIGEV_THREAD timer, the kernel can handle it without our help.
    115   if (timer->sigev_notify != SIGEV_THREAD) {
    116     if (__timer_create(clock_id, evp, &timer->kernel_timer_id) == -1) {
    117       free(timer);
    118       return -1;
    119     }
    120 
    121     *timer_id = timer;
    122     return 0;
    123   }
    124 
    125   // Otherwise, this must be SIGEV_THREAD timer...
    126   timer->callback = evp->sigev_notify_function;
    127   timer->callback_argument = evp->sigev_value;
    128   atomic_init(&timer->deleted, false);
    129 
    130   // Check arguments that the kernel doesn't care about but we do.
    131   if (timer->callback == NULL) {
    132     free(timer);
    133     errno = EINVAL;
    134     return -1;
    135   }
    136 
    137   // Create this timer's thread.
    138   pthread_attr_t thread_attributes;
    139   if (evp->sigev_notify_attributes == NULL) {
    140     pthread_attr_init(&thread_attributes);
    141   } else {
    142     thread_attributes = *reinterpret_cast<pthread_attr_t*>(evp->sigev_notify_attributes);
    143   }
    144   pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_DETACHED);
    145 
    146   // We start the thread with TIMER_SIGNAL blocked by blocking the signal here and letting it
    147   // inherit. If it tried to block the signal itself, there would be a race.
    148   sigset64_t sigset = {};
    149   sigaddset64(&sigset, TIMER_SIGNAL);
    150   sigset64_t old_sigset;
    151 
    152   // Use __rt_sigprocmask instead of sigprocmask64 to avoid filtering out TIMER_SIGNAL.
    153   __rt_sigprocmask(SIG_BLOCK, &sigset, &old_sigset, sizeof(sigset));
    154 
    155   int rc = pthread_create(&timer->callback_thread, &thread_attributes, __timer_thread_start, timer);
    156 
    157   __rt_sigprocmask(SIG_BLOCK, &old_sigset, nullptr, sizeof(old_sigset));
    158 
    159   if (rc != 0) {
    160     free(timer);
    161     errno = rc;
    162     return -1;
    163   }
    164 
    165   sigevent se = *evp;
    166   se.sigev_signo = TIMER_SIGNAL;
    167   se.sigev_notify = SIGEV_THREAD_ID;
    168   se.sigev_notify_thread_id = pthread_gettid_np(timer->callback_thread);
    169   if (__timer_create(clock_id, &se, &timer->kernel_timer_id) == -1) {
    170     __timer_thread_stop(timer);
    171     return -1;
    172   }
    173 
    174   // Give the thread a specific meaningful name.
    175   // It can't do this itself because the kernel timer isn't created until after it's running.
    176   char name[16]; // 16 is the kernel-imposed limit.
    177   snprintf(name, sizeof(name), "POSIX timer %d", to_kernel_timer_id(timer));
    178   pthread_setname_np(timer->callback_thread, name);
    179 
    180   *timer_id = timer;
    181   return 0;
    182 }
    183 
    184 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_delete.html
    185 int timer_delete(timer_t id) {
    186   int rc = __timer_delete(to_kernel_timer_id(id));
    187   if (rc == -1) {
    188     return -1;
    189   }
    190 
    191   PosixTimer* timer = reinterpret_cast<PosixTimer*>(id);
    192   if (timer->sigev_notify == SIGEV_THREAD) {
    193     // Stopping the timer's thread frees the timer data when it's safe.
    194     __timer_thread_stop(timer);
    195   } else {
    196     // For timers without threads, we can just free right away.
    197     free(timer);
    198   }
    199 
    200   return 0;
    201 }
    202 
    203 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_gettime.html
    204 int timer_gettime(timer_t id, itimerspec* ts) {
    205   return __timer_gettime(to_kernel_timer_id(id), ts);
    206 }
    207 
    208 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_settime.html
    209 // When using timer_settime to disarm a repeatable SIGEV_THREAD timer with a very small
    210 // period (like below 1ms), the kernel may continue to send events to the callback thread
    211 // for a few extra times. This behavior is fine because in POSIX standard: The effect of
    212 // disarming or resetting a timer with pending expiration notifications is unspecified.
    213 int timer_settime(timer_t id, int flags, const itimerspec* ts, itimerspec* ots) {
    214   PosixTimer* timer= reinterpret_cast<PosixTimer*>(id);
    215   return __timer_settime(timer->kernel_timer_id, flags, ts, ots);
    216 }
    217 
    218 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_getoverrun.html
    219 int timer_getoverrun(timer_t id) {
    220   return __timer_getoverrun(to_kernel_timer_id(id));
    221 }
    222