2.9
[glibc/nacl-glibc.git] / nptl / sysdeps / unix / sysv / linux / lowlevelrobustlock.c
blob3830f94daa7f37aae14fead389e4e598357296a8
1 /* Copyright (C) 2006, 2007 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Jakub Jelinek <jakub@redhat.com>, 2006.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 #include <errno.h>
21 #include <sysdep.h>
22 #include <lowlevellock.h>
23 #include <sys/time.h>
24 #include <pthreadP.h>
27 int
28 __lll_robust_lock_wait (int *futex, int private)
30 int oldval = *futex;
31 int tid = THREAD_GETMEM (THREAD_SELF, tid);
33 /* If the futex changed meanwhile try locking again. */
34 if (oldval == 0)
35 goto try;
39 if (__builtin_expect (oldval & FUTEX_OWNER_DIED, 0))
40 return oldval;
42 int newval = oldval | FUTEX_WAITERS;
43 if (oldval != newval
44 && atomic_compare_and_exchange_bool_acq (futex, newval, oldval))
45 continue;
47 lll_futex_wait (futex, newval, private);
49 try:
52 while ((oldval = atomic_compare_and_exchange_val_acq (futex,
53 tid | FUTEX_WAITERS,
54 0)) != 0);
55 return 0;
59 int
60 __lll_robust_timedlock_wait (int *futex, const struct timespec *abstime,
61 int private)
63 /* Reject invalid timeouts. */
64 if (abstime->tv_nsec < 0 || abstime->tv_nsec >= 1000000000)
65 return EINVAL;
67 int tid = THREAD_GETMEM (THREAD_SELF, tid);
68 int oldval = *futex;
70 /* If the futex changed meanwhile try locking again. */
71 if (oldval == 0)
72 goto try;
76 struct timeval tv;
77 struct timespec rt;
79 /* Get the current time. */
80 (void) __gettimeofday (&tv, NULL);
82 /* Compute relative timeout. */
83 rt.tv_sec = abstime->tv_sec - tv.tv_sec;
84 rt.tv_nsec = abstime->tv_nsec - tv.tv_usec * 1000;
85 if (rt.tv_nsec < 0)
87 rt.tv_nsec += 1000000000;
88 --rt.tv_sec;
91 /* Already timed out? */
92 if (rt.tv_sec < 0)
93 return ETIMEDOUT;
95 /* Wait. */
96 if (__builtin_expect (oldval & FUTEX_OWNER_DIED, 0))
97 return oldval;
99 int newval = oldval | FUTEX_WAITERS;
100 if (oldval != newval
101 && atomic_compare_and_exchange_bool_acq (futex, newval, oldval))
102 continue;
104 lll_futex_timed_wait (futex, newval, &rt, private);
106 try:
109 while ((oldval = atomic_compare_and_exchange_val_acq (futex,
110 tid | FUTEX_WAITERS,
111 0)) != 0);
113 return 0;