__timedwait.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <pthread.h>
  2. #include <time.h>
  3. #include <errno.h>
  4. #include "futex.h"
  5. #include "syscall.h"
  6. static int do_wait(volatile int *addr, int val, clockid_t clk, const struct timespec *at, int cp, int priv)
  7. {
  8. int r, flag = 0;
  9. struct timespec to, *top=0;
  10. if (!at) goto notimeout;
  11. if (at->tv_nsec >= 1000000000UL)
  12. return EINVAL;
  13. if (clk == CLOCK_REALTIME || clk == CLOCK_MONOTONIC) {
  14. if (clk == CLOCK_REALTIME) flag = FUTEX_CLOCK_REALTIME;
  15. if (cp) r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT_BITSET|flag, val, at, 0, -1);
  16. else r = -__syscall(SYS_futex, addr, FUTEX_WAIT_BITSET|flag, val, at, 0, -1);
  17. if (r != EINVAL && r != ENOSYS) goto done;
  18. }
  19. if (clock_gettime(clk, &to)) return EINVAL;
  20. to.tv_sec = at->tv_sec - to.tv_sec;
  21. if ((to.tv_nsec = at->tv_nsec - to.tv_nsec) < 0) {
  22. to.tv_sec--;
  23. to.tv_nsec += 1000000000;
  24. }
  25. if (to.tv_sec < 0) return ETIMEDOUT;
  26. top = &to;
  27. notimeout:
  28. if (cp) r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT, val, top);
  29. else r = -__syscall(SYS_futex, addr, FUTEX_WAIT, val, top);
  30. done:
  31. if (r == EINTR || r == EINVAL || r == ETIMEDOUT) return r;
  32. return 0;
  33. }
  34. int __timedwait(volatile int *addr, int val, clockid_t clk, const struct timespec *at, void (*cleanup)(void *), void *arg, int priv)
  35. {
  36. int r;
  37. if (cleanup) {
  38. pthread_cleanup_push(cleanup, arg);
  39. r = do_wait(addr, val, clk, at, 1, priv);
  40. pthread_cleanup_pop(0);
  41. } else {
  42. r = do_wait(addr, val, clk, at, 0, priv);
  43. }
  44. return r;
  45. }