2 * Fast Userspace Mutexes (which I call "Futexes!").
3 * (C) Rusty Russell, IBM 2002
5 * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
6 * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
8 * Removed page pinning, fix privately mapped COW pages and other cleanups
9 * (C) Copyright 2003, 2004 Jamie Lokier
11 * Robust futex support started by Ingo Molnar
12 * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
13 * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
15 * PI-futex support started by Ingo Molnar and Thomas Gleixner
16 * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
17 * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
19 * PRIVATE futexes by Eric Dumazet
20 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
22 * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
23 * Copyright (C) IBM Corporation, 2009
24 * Thanks to Thomas Gleixner for conceptual design and careful reviews.
26 * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
27 * enough at me, Linus for the original (flawed) idea, Matthew
28 * Kirkwood for proof-of-concept implementation.
30 * "The futexes are also cursed."
31 * "But they come in a choice of three flavours!"
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program; if not, write to the Free Software
45 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
47 #include <linux/slab.h>
48 #include <linux/poll.h>
50 #include <linux/file.h>
51 #include <linux/jhash.h>
52 #include <linux/init.h>
53 #include <linux/futex.h>
54 #include <linux/mount.h>
55 #include <linux/pagemap.h>
56 #include <linux/syscalls.h>
57 #include <linux/signal.h>
58 #include <linux/export.h>
59 #include <linux/magic.h>
60 #include <linux/pid.h>
61 #include <linux/nsproxy.h>
62 #include <linux/ptrace.h>
63 #include <linux/sched/rt.h>
64 #include <linux/hugetlb.h>
65 #include <linux/freezer.h>
66 #include <linux/bootmem.h>
68 #include <asm/futex.h>
70 #include "locking/rtmutex_common.h"
73 * Basic futex operation and ordering guarantees:
75 * The waiter reads the futex value in user space and calls
76 * futex_wait(). This function computes the hash bucket and acquires
77 * the hash bucket lock. After that it reads the futex user space value
78 * again and verifies that the data has not changed. If it has not changed
79 * it enqueues itself into the hash bucket, releases the hash bucket lock
82 * The waker side modifies the user space value of the futex and calls
83 * futex_wake(). This function computes the hash bucket and acquires the
84 * hash bucket lock. Then it looks for waiters on that futex in the hash
85 * bucket and wakes them.
87 * In futex wake up scenarios where no tasks are blocked on a futex, taking
88 * the hb spinlock can be avoided and simply return. In order for this
89 * optimization to work, ordering guarantees must exist so that the waiter
90 * being added to the list is acknowledged when the list is concurrently being
91 * checked by the waker, avoiding scenarios like the following:
95 * sys_futex(WAIT, futex, val);
96 * futex_wait(futex, val);
99 * sys_futex(WAKE, futex);
104 * lock(hash_bucket(futex));
106 * unlock(hash_bucket(futex));
109 * This would cause the waiter on CPU 0 to wait forever because it
110 * missed the transition of the user space value from val to newval
111 * and the waker did not find the waiter in the hash bucket queue.
113 * The correct serialization ensures that a waiter either observes
114 * the changed user space value before blocking or is woken by a
119 * sys_futex(WAIT, futex, val);
120 * futex_wait(futex, val);
123 * mb(); (A) <-- paired with -.
125 * lock(hash_bucket(futex)); |
129 * | sys_futex(WAKE, futex);
130 * | futex_wake(futex);
132 * `-------> mb(); (B)
135 * unlock(hash_bucket(futex));
136 * schedule(); if (waiters)
137 * lock(hash_bucket(futex));
138 * wake_waiters(futex);
139 * unlock(hash_bucket(futex));
141 * Where (A) orders the waiters increment and the futex value read -- this
142 * is guaranteed by the head counter in the hb spinlock; and where (B)
143 * orders the write to futex and the waiters read -- this is done by the
144 * barriers in get_futex_key_refs(), through either ihold or atomic_inc,
145 * depending on the futex type.
147 * This yields the following case (where X:=waiters, Y:=futex):
155 * Which guarantees that x==0 && y==0 is impossible; which translates back into
156 * the guarantee that we cannot both miss the futex variable change and the
160 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
161 int __read_mostly futex_cmpxchg_enabled
;
165 * Futex flags used to encode options to functions and preserve them across
168 #define FLAGS_SHARED 0x01
169 #define FLAGS_CLOCKRT 0x02
170 #define FLAGS_HAS_TIMEOUT 0x04
173 * Priority Inheritance state:
175 struct futex_pi_state
{
177 * list of 'owned' pi_state instances - these have to be
178 * cleaned up in do_exit() if the task exits prematurely:
180 struct list_head list
;
185 struct rt_mutex pi_mutex
;
187 struct task_struct
*owner
;
194 * struct futex_q - The hashed futex queue entry, one per waiting task
195 * @list: priority-sorted list of tasks waiting on this futex
196 * @task: the task waiting on the futex
197 * @lock_ptr: the hash bucket lock
198 * @key: the key the futex is hashed on
199 * @pi_state: optional priority inheritance state
200 * @rt_waiter: rt_waiter storage for use with requeue_pi
201 * @requeue_pi_key: the requeue_pi target futex key
202 * @bitset: bitset for the optional bitmasked wakeup
204 * We use this hashed waitqueue, instead of a normal wait_queue_t, so
205 * we can wake only the relevant ones (hashed queues may be shared).
207 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
208 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
209 * The order of wakeup is always to make the first condition true, then
212 * PI futexes are typically woken before they are removed from the hash list via
213 * the rt_mutex code. See unqueue_me_pi().
216 struct plist_node list
;
218 struct task_struct
*task
;
219 spinlock_t
*lock_ptr
;
221 struct futex_pi_state
*pi_state
;
222 struct rt_mutex_waiter
*rt_waiter
;
223 union futex_key
*requeue_pi_key
;
227 static const struct futex_q futex_q_init
= {
228 /* list gets initialized in queue_me()*/
229 .key
= FUTEX_KEY_INIT
,
230 .bitset
= FUTEX_BITSET_MATCH_ANY
234 * Hash buckets are shared by all the futex_keys that hash to the same
235 * location. Each key may have multiple futex_q structures, one for each task
236 * waiting on a futex.
238 struct futex_hash_bucket
{
241 struct plist_head chain
;
242 } ____cacheline_aligned_in_smp
;
244 static unsigned long __read_mostly futex_hashsize
;
246 static struct futex_hash_bucket
*futex_queues
;
248 static inline void futex_get_mm(union futex_key
*key
)
250 atomic_inc(&key
->private.mm
->mm_count
);
252 * Ensure futex_get_mm() implies a full barrier such that
253 * get_futex_key() implies a full barrier. This is relied upon
254 * as full barrier (B), see the ordering comment above.
256 smp_mb__after_atomic_inc();
260 * Reflects a new waiter being added to the waitqueue.
262 static inline void hb_waiters_inc(struct futex_hash_bucket
*hb
)
265 atomic_inc(&hb
->waiters
);
267 * Full barrier (A), see the ordering comment above.
269 smp_mb__after_atomic_inc();
274 * Reflects a waiter being removed from the waitqueue by wakeup
277 static inline void hb_waiters_dec(struct futex_hash_bucket
*hb
)
280 atomic_dec(&hb
->waiters
);
284 static inline int hb_waiters_pending(struct futex_hash_bucket
*hb
)
287 return atomic_read(&hb
->waiters
);
294 * We hash on the keys returned from get_futex_key (see below).
296 static struct futex_hash_bucket
*hash_futex(union futex_key
*key
)
298 u32 hash
= jhash2((u32
*)&key
->both
.word
,
299 (sizeof(key
->both
.word
)+sizeof(key
->both
.ptr
))/4,
301 return &futex_queues
[hash
& (futex_hashsize
- 1)];
305 * Return 1 if two futex_keys are equal, 0 otherwise.
307 static inline int match_futex(union futex_key
*key1
, union futex_key
*key2
)
310 && key1
->both
.word
== key2
->both
.word
311 && key1
->both
.ptr
== key2
->both
.ptr
312 && key1
->both
.offset
== key2
->both
.offset
);
316 * Take a reference to the resource addressed by a key.
317 * Can be called while holding spinlocks.
320 static void get_futex_key_refs(union futex_key
*key
)
325 switch (key
->both
.offset
& (FUT_OFF_INODE
|FUT_OFF_MMSHARED
)) {
327 ihold(key
->shared
.inode
); /* implies MB (B) */
329 case FUT_OFF_MMSHARED
:
330 futex_get_mm(key
); /* implies MB (B) */
333 smp_mb(); /* explicit MB (B) */
338 * Drop a reference to the resource addressed by a key.
339 * The hash bucket spinlock must not be held.
341 static void drop_futex_key_refs(union futex_key
*key
)
343 if (!key
->both
.ptr
) {
344 /* If we're here then we tried to put a key we failed to get */
349 switch (key
->both
.offset
& (FUT_OFF_INODE
|FUT_OFF_MMSHARED
)) {
351 iput(key
->shared
.inode
);
353 case FUT_OFF_MMSHARED
:
354 mmdrop(key
->private.mm
);
360 * get_futex_key() - Get parameters which are the keys for a futex
361 * @uaddr: virtual address of the futex
362 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
363 * @key: address where result is stored.
364 * @rw: mapping needs to be read/write (values: VERIFY_READ,
367 * Return: a negative error code or 0
369 * The key words are stored in *key on success.
371 * For shared mappings, it's (page->index, file_inode(vma->vm_file),
372 * offset_within_page). For private mappings, it's (uaddr, current->mm).
373 * We can usually work out the index without swapping in the page.
375 * lock_page() might sleep, the caller should not hold a spinlock.
378 get_futex_key(u32 __user
*uaddr
, int fshared
, union futex_key
*key
, int rw
)
380 unsigned long address
= (unsigned long)uaddr
;
381 struct mm_struct
*mm
= current
->mm
;
382 struct page
*page
, *page_head
;
386 * The futex address must be "naturally" aligned.
388 key
->both
.offset
= address
% PAGE_SIZE
;
389 if (unlikely((address
% sizeof(u32
)) != 0))
391 address
-= key
->both
.offset
;
393 if (unlikely(!access_ok(rw
, uaddr
, sizeof(u32
))))
397 * PROCESS_PRIVATE futexes are fast.
398 * As the mm cannot disappear under us and the 'key' only needs
399 * virtual address, we dont even have to find the underlying vma.
400 * Note : We do have to check 'uaddr' is a valid user address,
401 * but access_ok() should be faster than find_vma()
404 key
->private.mm
= mm
;
405 key
->private.address
= address
;
406 get_futex_key_refs(key
); /* implies MB (B) */
411 err
= get_user_pages_fast(address
, 1, 1, &page
);
413 * If write access is not required (eg. FUTEX_WAIT), try
414 * and get read-only access.
416 if (err
== -EFAULT
&& rw
== VERIFY_READ
) {
417 err
= get_user_pages_fast(address
, 1, 0, &page
);
425 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
427 if (unlikely(PageTail(page
))) {
429 /* serialize against __split_huge_page_splitting() */
431 if (likely(__get_user_pages_fast(address
, 1, !ro
, &page
) == 1)) {
432 page_head
= compound_head(page
);
434 * page_head is valid pointer but we must pin
435 * it before taking the PG_lock and/or
436 * PG_compound_lock. The moment we re-enable
437 * irqs __split_huge_page_splitting() can
438 * return and the head page can be freed from
439 * under us. We can't take the PG_lock and/or
440 * PG_compound_lock on a page that could be
441 * freed from under us.
443 if (page
!= page_head
) {
454 page_head
= compound_head(page
);
455 if (page
!= page_head
) {
461 lock_page(page_head
);
464 * If page_head->mapping is NULL, then it cannot be a PageAnon
465 * page; but it might be the ZERO_PAGE or in the gate area or
466 * in a special mapping (all cases which we are happy to fail);
467 * or it may have been a good file page when get_user_pages_fast
468 * found it, but truncated or holepunched or subjected to
469 * invalidate_complete_page2 before we got the page lock (also
470 * cases which we are happy to fail). And we hold a reference,
471 * so refcount care in invalidate_complete_page's remove_mapping
472 * prevents drop_caches from setting mapping to NULL beneath us.
474 * The case we do have to guard against is when memory pressure made
475 * shmem_writepage move it from filecache to swapcache beneath us:
476 * an unlikely race, but we do need to retry for page_head->mapping.
478 if (!page_head
->mapping
) {
479 int shmem_swizzled
= PageSwapCache(page_head
);
480 unlock_page(page_head
);
488 * Private mappings are handled in a simple way.
490 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
491 * it's a read-only handle, it's expected that futexes attach to
492 * the object not the particular process.
494 if (PageAnon(page_head
)) {
496 * A RO anonymous page will never change and thus doesn't make
497 * sense for futex operations.
504 key
->both
.offset
|= FUT_OFF_MMSHARED
; /* ref taken on mm */
505 key
->private.mm
= mm
;
506 key
->private.address
= address
;
508 key
->both
.offset
|= FUT_OFF_INODE
; /* inode-based key */
509 key
->shared
.inode
= page_head
->mapping
->host
;
510 key
->shared
.pgoff
= basepage_index(page
);
513 get_futex_key_refs(key
); /* implies MB (B) */
516 unlock_page(page_head
);
521 static inline void put_futex_key(union futex_key
*key
)
523 drop_futex_key_refs(key
);
527 * fault_in_user_writeable() - Fault in user address and verify RW access
528 * @uaddr: pointer to faulting user space address
530 * Slow path to fixup the fault we just took in the atomic write
533 * We have no generic implementation of a non-destructive write to the
534 * user address. We know that we faulted in the atomic pagefault
535 * disabled section so we can as well avoid the #PF overhead by
536 * calling get_user_pages() right away.
538 static int fault_in_user_writeable(u32 __user
*uaddr
)
540 struct mm_struct
*mm
= current
->mm
;
543 down_read(&mm
->mmap_sem
);
544 ret
= fixup_user_fault(current
, mm
, (unsigned long)uaddr
,
546 up_read(&mm
->mmap_sem
);
548 return ret
< 0 ? ret
: 0;
552 * futex_top_waiter() - Return the highest priority waiter on a futex
553 * @hb: the hash bucket the futex_q's reside in
554 * @key: the futex key (to distinguish it from other futex futex_q's)
556 * Must be called with the hb lock held.
558 static struct futex_q
*futex_top_waiter(struct futex_hash_bucket
*hb
,
559 union futex_key
*key
)
561 struct futex_q
*this;
563 plist_for_each_entry(this, &hb
->chain
, list
) {
564 if (match_futex(&this->key
, key
))
570 static int cmpxchg_futex_value_locked(u32
*curval
, u32 __user
*uaddr
,
571 u32 uval
, u32 newval
)
576 ret
= futex_atomic_cmpxchg_inatomic(curval
, uaddr
, uval
, newval
);
582 static int get_futex_value_locked(u32
*dest
, u32 __user
*from
)
587 ret
= __copy_from_user_inatomic(dest
, from
, sizeof(u32
));
590 return ret
? -EFAULT
: 0;
597 static int refill_pi_state_cache(void)
599 struct futex_pi_state
*pi_state
;
601 if (likely(current
->pi_state_cache
))
604 pi_state
= kzalloc(sizeof(*pi_state
), GFP_KERNEL
);
609 INIT_LIST_HEAD(&pi_state
->list
);
610 /* pi_mutex gets initialized later */
611 pi_state
->owner
= NULL
;
612 atomic_set(&pi_state
->refcount
, 1);
613 pi_state
->key
= FUTEX_KEY_INIT
;
615 current
->pi_state_cache
= pi_state
;
620 static struct futex_pi_state
* alloc_pi_state(void)
622 struct futex_pi_state
*pi_state
= current
->pi_state_cache
;
625 current
->pi_state_cache
= NULL
;
630 static void free_pi_state(struct futex_pi_state
*pi_state
)
632 if (!atomic_dec_and_test(&pi_state
->refcount
))
636 * If pi_state->owner is NULL, the owner is most probably dying
637 * and has cleaned up the pi_state already
639 if (pi_state
->owner
) {
640 raw_spin_lock_irq(&pi_state
->owner
->pi_lock
);
641 list_del_init(&pi_state
->list
);
642 raw_spin_unlock_irq(&pi_state
->owner
->pi_lock
);
644 rt_mutex_proxy_unlock(&pi_state
->pi_mutex
, pi_state
->owner
);
647 if (current
->pi_state_cache
)
651 * pi_state->list is already empty.
652 * clear pi_state->owner.
653 * refcount is at 0 - put it back to 1.
655 pi_state
->owner
= NULL
;
656 atomic_set(&pi_state
->refcount
, 1);
657 current
->pi_state_cache
= pi_state
;
662 * Look up the task based on what TID userspace gave us.
665 static struct task_struct
* futex_find_get_task(pid_t pid
)
667 struct task_struct
*p
;
670 p
= find_task_by_vpid(pid
);
680 * This task is holding PI mutexes at exit time => bad.
681 * Kernel cleans up PI-state, but userspace is likely hosed.
682 * (Robust-futex cleanup is separate and might save the day for userspace.)
684 void exit_pi_state_list(struct task_struct
*curr
)
686 struct list_head
*next
, *head
= &curr
->pi_state_list
;
687 struct futex_pi_state
*pi_state
;
688 struct futex_hash_bucket
*hb
;
689 union futex_key key
= FUTEX_KEY_INIT
;
691 if (!futex_cmpxchg_enabled
)
694 * We are a ZOMBIE and nobody can enqueue itself on
695 * pi_state_list anymore, but we have to be careful
696 * versus waiters unqueueing themselves:
698 raw_spin_lock_irq(&curr
->pi_lock
);
699 while (!list_empty(head
)) {
702 pi_state
= list_entry(next
, struct futex_pi_state
, list
);
704 hb
= hash_futex(&key
);
705 raw_spin_unlock_irq(&curr
->pi_lock
);
707 spin_lock(&hb
->lock
);
709 raw_spin_lock_irq(&curr
->pi_lock
);
711 * We dropped the pi-lock, so re-check whether this
712 * task still owns the PI-state:
714 if (head
->next
!= next
) {
715 spin_unlock(&hb
->lock
);
719 WARN_ON(pi_state
->owner
!= curr
);
720 WARN_ON(list_empty(&pi_state
->list
));
721 list_del_init(&pi_state
->list
);
722 pi_state
->owner
= NULL
;
723 raw_spin_unlock_irq(&curr
->pi_lock
);
725 rt_mutex_unlock(&pi_state
->pi_mutex
);
727 spin_unlock(&hb
->lock
);
729 raw_spin_lock_irq(&curr
->pi_lock
);
731 raw_spin_unlock_irq(&curr
->pi_lock
);
735 * We need to check the following states:
737 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
739 * [1] NULL | --- | --- | 0 | 0/1 | Valid
740 * [2] NULL | --- | --- | >0 | 0/1 | Valid
742 * [3] Found | NULL | -- | Any | 0/1 | Invalid
744 * [4] Found | Found | NULL | 0 | 1 | Valid
745 * [5] Found | Found | NULL | >0 | 1 | Invalid
747 * [6] Found | Found | task | 0 | 1 | Valid
749 * [7] Found | Found | NULL | Any | 0 | Invalid
751 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
752 * [9] Found | Found | task | 0 | 0 | Invalid
753 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
755 * [1] Indicates that the kernel can acquire the futex atomically. We
756 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
758 * [2] Valid, if TID does not belong to a kernel thread. If no matching
759 * thread is found then it indicates that the owner TID has died.
761 * [3] Invalid. The waiter is queued on a non PI futex
763 * [4] Valid state after exit_robust_list(), which sets the user space
764 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
766 * [5] The user space value got manipulated between exit_robust_list()
767 * and exit_pi_state_list()
769 * [6] Valid state after exit_pi_state_list() which sets the new owner in
770 * the pi_state but cannot access the user space value.
772 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
774 * [8] Owner and user space value match
776 * [9] There is no transient state which sets the user space TID to 0
777 * except exit_robust_list(), but this is indicated by the
778 * FUTEX_OWNER_DIED bit. See [4]
780 * [10] There is no transient state which leaves owner and user space
784 lookup_pi_state(u32 uval
, struct futex_hash_bucket
*hb
,
785 union futex_key
*key
, struct futex_pi_state
**ps
)
787 struct futex_pi_state
*pi_state
= NULL
;
788 struct futex_q
*this, *next
;
789 struct task_struct
*p
;
790 pid_t pid
= uval
& FUTEX_TID_MASK
;
792 plist_for_each_entry_safe(this, next
, &hb
->chain
, list
) {
793 if (match_futex(&this->key
, key
)) {
795 * Sanity check the waiter before increasing
796 * the refcount and attaching to it.
798 pi_state
= this->pi_state
;
800 * Userspace might have messed up non-PI and
803 if (unlikely(!pi_state
))
806 WARN_ON(!atomic_read(&pi_state
->refcount
));
809 * Handle the owner died case:
811 if (uval
& FUTEX_OWNER_DIED
) {
813 * exit_pi_state_list sets owner to NULL and
814 * wakes the topmost waiter. The task which
815 * acquires the pi_state->rt_mutex will fixup
818 if (!pi_state
->owner
) {
820 * No pi state owner, but the user
821 * space TID is not 0. Inconsistent
827 * Take a ref on the state and
834 * If TID is 0, then either the dying owner
835 * has not yet executed exit_pi_state_list()
836 * or some waiter acquired the rtmutex in the
837 * pi state, but did not yet fixup the TID in
840 * Take a ref on the state and return. [6]
846 * If the owner died bit is not set,
847 * then the pi_state must have an
850 if (!pi_state
->owner
)
855 * Bail out if user space manipulated the
856 * futex value. If pi state exists then the
857 * owner TID must be the same as the user
860 if (pid
!= task_pid_vnr(pi_state
->owner
))
864 atomic_inc(&pi_state
->refcount
);
871 * We are the first waiter - try to look up the real owner and attach
872 * the new pi_state to it, but bail out when TID = 0 [1]
876 p
= futex_find_get_task(pid
);
886 * We need to look at the task state flags to figure out,
887 * whether the task is exiting. To protect against the do_exit
888 * change of the task flags, we do this protected by
891 raw_spin_lock_irq(&p
->pi_lock
);
892 if (unlikely(p
->flags
& PF_EXITING
)) {
894 * The task is on the way out. When PF_EXITPIDONE is
895 * set, we know that the task has finished the
898 int ret
= (p
->flags
& PF_EXITPIDONE
) ? -ESRCH
: -EAGAIN
;
900 raw_spin_unlock_irq(&p
->pi_lock
);
906 * No existing pi state. First waiter. [2]
908 pi_state
= alloc_pi_state();
911 * Initialize the pi_mutex in locked state and make 'p'
914 rt_mutex_init_proxy_locked(&pi_state
->pi_mutex
, p
);
916 /* Store the key for possible exit cleanups: */
917 pi_state
->key
= *key
;
919 WARN_ON(!list_empty(&pi_state
->list
));
920 list_add(&pi_state
->list
, &p
->pi_state_list
);
922 raw_spin_unlock_irq(&p
->pi_lock
);
932 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
933 * @uaddr: the pi futex user address
934 * @hb: the pi futex hash bucket
935 * @key: the futex key associated with uaddr and hb
936 * @ps: the pi_state pointer where we store the result of the
938 * @task: the task to perform the atomic lock work for. This will
939 * be "current" except in the case of requeue pi.
940 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
944 * 1 - acquired the lock;
947 * The hb->lock and futex_key refs shall be held by the caller.
949 static int futex_lock_pi_atomic(u32 __user
*uaddr
, struct futex_hash_bucket
*hb
,
950 union futex_key
*key
,
951 struct futex_pi_state
**ps
,
952 struct task_struct
*task
, int set_waiters
)
954 int lock_taken
, ret
, force_take
= 0;
955 u32 uval
, newval
, curval
, vpid
= task_pid_vnr(task
);
958 ret
= lock_taken
= 0;
961 * To avoid races, we attempt to take the lock here again
962 * (by doing a 0 -> TID atomic cmpxchg), while holding all
963 * the locks. It will most likely not succeed.
967 newval
|= FUTEX_WAITERS
;
969 if (unlikely(cmpxchg_futex_value_locked(&curval
, uaddr
, 0, newval
)))
975 if ((unlikely((curval
& FUTEX_TID_MASK
) == vpid
)))
979 * Surprise - we got the lock, but we do not trust user space at all.
981 if (unlikely(!curval
)) {
983 * We verify whether there is kernel state for this
984 * futex. If not, we can safely assume, that the 0 ->
985 * TID transition is correct. If state exists, we do
986 * not bother to fixup the user space state as it was
989 return futex_top_waiter(hb
, key
) ? -EINVAL
: 1;
995 * Set the FUTEX_WAITERS flag, so the owner will know it has someone
996 * to wake at the next unlock.
998 newval
= curval
| FUTEX_WAITERS
;
1001 * Should we force take the futex? See below.
1003 if (unlikely(force_take
)) {
1005 * Keep the OWNER_DIED and the WAITERS bit and set the
1008 newval
= (curval
& ~FUTEX_TID_MASK
) | vpid
;
1013 if (unlikely(cmpxchg_futex_value_locked(&curval
, uaddr
, uval
, newval
)))
1015 if (unlikely(curval
!= uval
))
1019 * We took the lock due to forced take over.
1021 if (unlikely(lock_taken
))
1025 * We dont have the lock. Look up the PI state (or create it if
1026 * we are the first waiter):
1028 ret
= lookup_pi_state(uval
, hb
, key
, ps
);
1030 if (unlikely(ret
)) {
1034 * We failed to find an owner for this
1035 * futex. So we have no pi_state to block
1036 * on. This can happen in two cases:
1039 * 2) A stale FUTEX_WAITERS bit
1041 * Re-read the futex value.
1043 if (get_futex_value_locked(&curval
, uaddr
))
1047 * If the owner died or we have a stale
1048 * WAITERS bit the owner TID in the user space
1051 if (!(curval
& FUTEX_TID_MASK
)) {
1064 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1065 * @q: The futex_q to unqueue
1067 * The q->lock_ptr must not be NULL and must be held by the caller.
1069 static void __unqueue_futex(struct futex_q
*q
)
1071 struct futex_hash_bucket
*hb
;
1073 if (WARN_ON_SMP(!q
->lock_ptr
|| !spin_is_locked(q
->lock_ptr
))
1074 || WARN_ON(plist_node_empty(&q
->list
)))
1077 hb
= container_of(q
->lock_ptr
, struct futex_hash_bucket
, lock
);
1078 plist_del(&q
->list
, &hb
->chain
);
1083 * The hash bucket lock must be held when this is called.
1084 * Afterwards, the futex_q must not be accessed.
1086 static void wake_futex(struct futex_q
*q
)
1088 struct task_struct
*p
= q
->task
;
1090 if (WARN(q
->pi_state
|| q
->rt_waiter
, "refusing to wake PI futex\n"))
1094 * We set q->lock_ptr = NULL _before_ we wake up the task. If
1095 * a non-futex wake up happens on another CPU then the task
1096 * might exit and p would dereference a non-existing task
1097 * struct. Prevent this by holding a reference on p across the
1104 * The waiting task can free the futex_q as soon as
1105 * q->lock_ptr = NULL is written, without taking any locks. A
1106 * memory barrier is required here to prevent the following
1107 * store to lock_ptr from getting ahead of the plist_del.
1112 wake_up_state(p
, TASK_NORMAL
);
1116 static int wake_futex_pi(u32 __user
*uaddr
, u32 uval
, struct futex_q
*this)
1118 struct task_struct
*new_owner
;
1119 struct futex_pi_state
*pi_state
= this->pi_state
;
1120 u32
uninitialized_var(curval
), newval
;
1127 * If current does not own the pi_state then the futex is
1128 * inconsistent and user space fiddled with the futex value.
1130 if (pi_state
->owner
!= current
)
1133 raw_spin_lock(&pi_state
->pi_mutex
.wait_lock
);
1134 new_owner
= rt_mutex_next_owner(&pi_state
->pi_mutex
);
1137 * It is possible that the next waiter (the one that brought
1138 * this owner to the kernel) timed out and is no longer
1139 * waiting on the lock.
1142 new_owner
= this->task
;
1145 * We pass it to the next owner. The WAITERS bit is always
1146 * kept enabled while there is PI state around. We cleanup the
1147 * owner died bit, because we are the owner.
1149 newval
= FUTEX_WAITERS
| task_pid_vnr(new_owner
);
1151 if (cmpxchg_futex_value_locked(&curval
, uaddr
, uval
, newval
))
1153 else if (curval
!= uval
)
1156 raw_spin_unlock(&pi_state
->pi_mutex
.wait_lock
);
1160 raw_spin_lock_irq(&pi_state
->owner
->pi_lock
);
1161 WARN_ON(list_empty(&pi_state
->list
));
1162 list_del_init(&pi_state
->list
);
1163 raw_spin_unlock_irq(&pi_state
->owner
->pi_lock
);
1165 raw_spin_lock_irq(&new_owner
->pi_lock
);
1166 WARN_ON(!list_empty(&pi_state
->list
));
1167 list_add(&pi_state
->list
, &new_owner
->pi_state_list
);
1168 pi_state
->owner
= new_owner
;
1169 raw_spin_unlock_irq(&new_owner
->pi_lock
);
1171 raw_spin_unlock(&pi_state
->pi_mutex
.wait_lock
);
1172 rt_mutex_unlock(&pi_state
->pi_mutex
);
1177 static int unlock_futex_pi(u32 __user
*uaddr
, u32 uval
)
1179 u32
uninitialized_var(oldval
);
1182 * There is no waiter, so we unlock the futex. The owner died
1183 * bit has not to be preserved here. We are the owner:
1185 if (cmpxchg_futex_value_locked(&oldval
, uaddr
, uval
, 0))
1194 * Express the locking dependencies for lockdep:
1197 double_lock_hb(struct futex_hash_bucket
*hb1
, struct futex_hash_bucket
*hb2
)
1200 spin_lock(&hb1
->lock
);
1202 spin_lock_nested(&hb2
->lock
, SINGLE_DEPTH_NESTING
);
1203 } else { /* hb1 > hb2 */
1204 spin_lock(&hb2
->lock
);
1205 spin_lock_nested(&hb1
->lock
, SINGLE_DEPTH_NESTING
);
1210 double_unlock_hb(struct futex_hash_bucket
*hb1
, struct futex_hash_bucket
*hb2
)
1212 spin_unlock(&hb1
->lock
);
1214 spin_unlock(&hb2
->lock
);
1218 * Wake up waiters matching bitset queued on this futex (uaddr).
1221 futex_wake(u32 __user
*uaddr
, unsigned int flags
, int nr_wake
, u32 bitset
)
1223 struct futex_hash_bucket
*hb
;
1224 struct futex_q
*this, *next
;
1225 union futex_key key
= FUTEX_KEY_INIT
;
1231 ret
= get_futex_key(uaddr
, flags
& FLAGS_SHARED
, &key
, VERIFY_READ
);
1232 if (unlikely(ret
!= 0))
1235 hb
= hash_futex(&key
);
1237 /* Make sure we really have tasks to wakeup */
1238 if (!hb_waiters_pending(hb
))
1241 spin_lock(&hb
->lock
);
1243 plist_for_each_entry_safe(this, next
, &hb
->chain
, list
) {
1244 if (match_futex (&this->key
, &key
)) {
1245 if (this->pi_state
|| this->rt_waiter
) {
1250 /* Check if one of the bits is set in both bitsets */
1251 if (!(this->bitset
& bitset
))
1255 if (++ret
>= nr_wake
)
1260 spin_unlock(&hb
->lock
);
1262 put_futex_key(&key
);
1268 * Wake up all waiters hashed on the physical page that is mapped
1269 * to this virtual address:
1272 futex_wake_op(u32 __user
*uaddr1
, unsigned int flags
, u32 __user
*uaddr2
,
1273 int nr_wake
, int nr_wake2
, int op
)
1275 union futex_key key1
= FUTEX_KEY_INIT
, key2
= FUTEX_KEY_INIT
;
1276 struct futex_hash_bucket
*hb1
, *hb2
;
1277 struct futex_q
*this, *next
;
1281 ret
= get_futex_key(uaddr1
, flags
& FLAGS_SHARED
, &key1
, VERIFY_READ
);
1282 if (unlikely(ret
!= 0))
1284 ret
= get_futex_key(uaddr2
, flags
& FLAGS_SHARED
, &key2
, VERIFY_WRITE
);
1285 if (unlikely(ret
!= 0))
1288 hb1
= hash_futex(&key1
);
1289 hb2
= hash_futex(&key2
);
1292 double_lock_hb(hb1
, hb2
);
1293 op_ret
= futex_atomic_op_inuser(op
, uaddr2
);
1294 if (unlikely(op_ret
< 0)) {
1296 double_unlock_hb(hb1
, hb2
);
1300 * we don't get EFAULT from MMU faults if we don't have an MMU,
1301 * but we might get them from range checking
1307 if (unlikely(op_ret
!= -EFAULT
)) {
1312 ret
= fault_in_user_writeable(uaddr2
);
1316 if (!(flags
& FLAGS_SHARED
))
1319 put_futex_key(&key2
);
1320 put_futex_key(&key1
);
1324 plist_for_each_entry_safe(this, next
, &hb1
->chain
, list
) {
1325 if (match_futex (&this->key
, &key1
)) {
1326 if (this->pi_state
|| this->rt_waiter
) {
1331 if (++ret
>= nr_wake
)
1338 plist_for_each_entry_safe(this, next
, &hb2
->chain
, list
) {
1339 if (match_futex (&this->key
, &key2
)) {
1340 if (this->pi_state
|| this->rt_waiter
) {
1345 if (++op_ret
>= nr_wake2
)
1353 double_unlock_hb(hb1
, hb2
);
1355 put_futex_key(&key2
);
1357 put_futex_key(&key1
);
1363 * requeue_futex() - Requeue a futex_q from one hb to another
1364 * @q: the futex_q to requeue
1365 * @hb1: the source hash_bucket
1366 * @hb2: the target hash_bucket
1367 * @key2: the new key for the requeued futex_q
1370 void requeue_futex(struct futex_q
*q
, struct futex_hash_bucket
*hb1
,
1371 struct futex_hash_bucket
*hb2
, union futex_key
*key2
)
1375 * If key1 and key2 hash to the same bucket, no need to
1378 if (likely(&hb1
->chain
!= &hb2
->chain
)) {
1379 plist_del(&q
->list
, &hb1
->chain
);
1380 hb_waiters_dec(hb1
);
1381 plist_add(&q
->list
, &hb2
->chain
);
1382 hb_waiters_inc(hb2
);
1383 q
->lock_ptr
= &hb2
->lock
;
1385 get_futex_key_refs(key2
);
1390 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1392 * @key: the key of the requeue target futex
1393 * @hb: the hash_bucket of the requeue target futex
1395 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1396 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1397 * to the requeue target futex so the waiter can detect the wakeup on the right
1398 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1399 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1400 * to protect access to the pi_state to fixup the owner later. Must be called
1401 * with both q->lock_ptr and hb->lock held.
1404 void requeue_pi_wake_futex(struct futex_q
*q
, union futex_key
*key
,
1405 struct futex_hash_bucket
*hb
)
1407 get_futex_key_refs(key
);
1412 WARN_ON(!q
->rt_waiter
);
1413 q
->rt_waiter
= NULL
;
1415 q
->lock_ptr
= &hb
->lock
;
1417 wake_up_state(q
->task
, TASK_NORMAL
);
1421 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1422 * @pifutex: the user address of the to futex
1423 * @hb1: the from futex hash bucket, must be locked by the caller
1424 * @hb2: the to futex hash bucket, must be locked by the caller
1425 * @key1: the from futex key
1426 * @key2: the to futex key
1427 * @ps: address to store the pi_state pointer
1428 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1430 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1431 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1432 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1433 * hb1 and hb2 must be held by the caller.
1436 * 0 - failed to acquire the lock atomically;
1437 * >0 - acquired the lock, return value is vpid of the top_waiter
1440 static int futex_proxy_trylock_atomic(u32 __user
*pifutex
,
1441 struct futex_hash_bucket
*hb1
,
1442 struct futex_hash_bucket
*hb2
,
1443 union futex_key
*key1
, union futex_key
*key2
,
1444 struct futex_pi_state
**ps
, int set_waiters
)
1446 struct futex_q
*top_waiter
= NULL
;
1450 if (get_futex_value_locked(&curval
, pifutex
))
1454 * Find the top_waiter and determine if there are additional waiters.
1455 * If the caller intends to requeue more than 1 waiter to pifutex,
1456 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1457 * as we have means to handle the possible fault. If not, don't set
1458 * the bit unecessarily as it will force the subsequent unlock to enter
1461 top_waiter
= futex_top_waiter(hb1
, key1
);
1463 /* There are no waiters, nothing for us to do. */
1467 /* Ensure we requeue to the expected futex. */
1468 if (!match_futex(top_waiter
->requeue_pi_key
, key2
))
1472 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1473 * the contended case or if set_waiters is 1. The pi_state is returned
1474 * in ps in contended cases.
1476 vpid
= task_pid_vnr(top_waiter
->task
);
1477 ret
= futex_lock_pi_atomic(pifutex
, hb2
, key2
, ps
, top_waiter
->task
,
1480 requeue_pi_wake_futex(top_waiter
, key2
, hb2
);
1487 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1488 * @uaddr1: source futex user address
1489 * @flags: futex flags (FLAGS_SHARED, etc.)
1490 * @uaddr2: target futex user address
1491 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1492 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1493 * @cmpval: @uaddr1 expected value (or %NULL)
1494 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
1495 * pi futex (pi to pi requeue is not supported)
1497 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1498 * uaddr2 atomically on behalf of the top waiter.
1501 * >=0 - on success, the number of tasks requeued or woken;
1504 static int futex_requeue(u32 __user
*uaddr1
, unsigned int flags
,
1505 u32 __user
*uaddr2
, int nr_wake
, int nr_requeue
,
1506 u32
*cmpval
, int requeue_pi
)
1508 union futex_key key1
= FUTEX_KEY_INIT
, key2
= FUTEX_KEY_INIT
;
1509 int drop_count
= 0, task_count
= 0, ret
;
1510 struct futex_pi_state
*pi_state
= NULL
;
1511 struct futex_hash_bucket
*hb1
, *hb2
;
1512 struct futex_q
*this, *next
;
1516 * Requeue PI only works on two distinct uaddrs. This
1517 * check is only valid for private futexes. See below.
1519 if (uaddr1
== uaddr2
)
1523 * requeue_pi requires a pi_state, try to allocate it now
1524 * without any locks in case it fails.
1526 if (refill_pi_state_cache())
1529 * requeue_pi must wake as many tasks as it can, up to nr_wake
1530 * + nr_requeue, since it acquires the rt_mutex prior to
1531 * returning to userspace, so as to not leave the rt_mutex with
1532 * waiters and no owner. However, second and third wake-ups
1533 * cannot be predicted as they involve race conditions with the
1534 * first wake and a fault while looking up the pi_state. Both
1535 * pthread_cond_signal() and pthread_cond_broadcast() should
1543 if (pi_state
!= NULL
) {
1545 * We will have to lookup the pi_state again, so free this one
1546 * to keep the accounting correct.
1548 free_pi_state(pi_state
);
1552 ret
= get_futex_key(uaddr1
, flags
& FLAGS_SHARED
, &key1
, VERIFY_READ
);
1553 if (unlikely(ret
!= 0))
1555 ret
= get_futex_key(uaddr2
, flags
& FLAGS_SHARED
, &key2
,
1556 requeue_pi
? VERIFY_WRITE
: VERIFY_READ
);
1557 if (unlikely(ret
!= 0))
1561 * The check above which compares uaddrs is not sufficient for
1562 * shared futexes. We need to compare the keys:
1564 if (requeue_pi
&& match_futex(&key1
, &key2
)) {
1569 hb1
= hash_futex(&key1
);
1570 hb2
= hash_futex(&key2
);
1573 hb_waiters_inc(hb2
);
1574 double_lock_hb(hb1
, hb2
);
1576 if (likely(cmpval
!= NULL
)) {
1579 ret
= get_futex_value_locked(&curval
, uaddr1
);
1581 if (unlikely(ret
)) {
1582 double_unlock_hb(hb1
, hb2
);
1583 hb_waiters_dec(hb2
);
1585 ret
= get_user(curval
, uaddr1
);
1589 if (!(flags
& FLAGS_SHARED
))
1592 put_futex_key(&key2
);
1593 put_futex_key(&key1
);
1596 if (curval
!= *cmpval
) {
1602 if (requeue_pi
&& (task_count
- nr_wake
< nr_requeue
)) {
1604 * Attempt to acquire uaddr2 and wake the top waiter. If we
1605 * intend to requeue waiters, force setting the FUTEX_WAITERS
1606 * bit. We force this here where we are able to easily handle
1607 * faults rather in the requeue loop below.
1609 ret
= futex_proxy_trylock_atomic(uaddr2
, hb1
, hb2
, &key1
,
1610 &key2
, &pi_state
, nr_requeue
);
1613 * At this point the top_waiter has either taken uaddr2 or is
1614 * waiting on it. If the former, then the pi_state will not
1615 * exist yet, look it up one more time to ensure we have a
1616 * reference to it. If the lock was taken, ret contains the
1617 * vpid of the top waiter task.
1624 * If we acquired the lock, then the user
1625 * space value of uaddr2 should be vpid. It
1626 * cannot be changed by the top waiter as it
1627 * is blocked on hb2 lock if it tries to do
1628 * so. If something fiddled with it behind our
1629 * back the pi state lookup might unearth
1630 * it. So we rather use the known value than
1631 * rereading and handing potential crap to
1634 ret
= lookup_pi_state(ret
, hb2
, &key2
, &pi_state
);
1641 double_unlock_hb(hb1
, hb2
);
1642 hb_waiters_dec(hb2
);
1643 put_futex_key(&key2
);
1644 put_futex_key(&key1
);
1645 ret
= fault_in_user_writeable(uaddr2
);
1650 /* The owner was exiting, try again. */
1651 double_unlock_hb(hb1
, hb2
);
1652 hb_waiters_dec(hb2
);
1653 put_futex_key(&key2
);
1654 put_futex_key(&key1
);
1662 plist_for_each_entry_safe(this, next
, &hb1
->chain
, list
) {
1663 if (task_count
- nr_wake
>= nr_requeue
)
1666 if (!match_futex(&this->key
, &key1
))
1670 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
1671 * be paired with each other and no other futex ops.
1673 * We should never be requeueing a futex_q with a pi_state,
1674 * which is awaiting a futex_unlock_pi().
1676 if ((requeue_pi
&& !this->rt_waiter
) ||
1677 (!requeue_pi
&& this->rt_waiter
) ||
1684 * Wake nr_wake waiters. For requeue_pi, if we acquired the
1685 * lock, we already woke the top_waiter. If not, it will be
1686 * woken by futex_unlock_pi().
1688 if (++task_count
<= nr_wake
&& !requeue_pi
) {
1693 /* Ensure we requeue to the expected futex for requeue_pi. */
1694 if (requeue_pi
&& !match_futex(this->requeue_pi_key
, &key2
)) {
1700 * Requeue nr_requeue waiters and possibly one more in the case
1701 * of requeue_pi if we couldn't acquire the lock atomically.
1704 /* Prepare the waiter to take the rt_mutex. */
1705 atomic_inc(&pi_state
->refcount
);
1706 this->pi_state
= pi_state
;
1707 ret
= rt_mutex_start_proxy_lock(&pi_state
->pi_mutex
,
1711 /* We got the lock. */
1712 requeue_pi_wake_futex(this, &key2
, hb2
);
1717 this->pi_state
= NULL
;
1718 free_pi_state(pi_state
);
1722 requeue_futex(this, hb1
, hb2
, &key2
);
1727 double_unlock_hb(hb1
, hb2
);
1728 hb_waiters_dec(hb2
);
1731 * drop_futex_key_refs() must be called outside the spinlocks. During
1732 * the requeue we moved futex_q's from the hash bucket at key1 to the
1733 * one at key2 and updated their key pointer. We no longer need to
1734 * hold the references to key1.
1736 while (--drop_count
>= 0)
1737 drop_futex_key_refs(&key1
);
1740 put_futex_key(&key2
);
1742 put_futex_key(&key1
);
1744 if (pi_state
!= NULL
)
1745 free_pi_state(pi_state
);
1746 return ret
? ret
: task_count
;
1749 /* The key must be already stored in q->key. */
1750 static inline struct futex_hash_bucket
*queue_lock(struct futex_q
*q
)
1751 __acquires(&hb
->lock
)
1753 struct futex_hash_bucket
*hb
;
1755 hb
= hash_futex(&q
->key
);
1758 * Increment the counter before taking the lock so that
1759 * a potential waker won't miss a to-be-slept task that is
1760 * waiting for the spinlock. This is safe as all queue_lock()
1761 * users end up calling queue_me(). Similarly, for housekeeping,
1762 * decrement the counter at queue_unlock() when some error has
1763 * occurred and we don't end up adding the task to the list.
1767 q
->lock_ptr
= &hb
->lock
;
1769 spin_lock(&hb
->lock
); /* implies MB (A) */
1774 queue_unlock(struct futex_hash_bucket
*hb
)
1775 __releases(&hb
->lock
)
1777 spin_unlock(&hb
->lock
);
1782 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
1783 * @q: The futex_q to enqueue
1784 * @hb: The destination hash bucket
1786 * The hb->lock must be held by the caller, and is released here. A call to
1787 * queue_me() is typically paired with exactly one call to unqueue_me(). The
1788 * exceptions involve the PI related operations, which may use unqueue_me_pi()
1789 * or nothing if the unqueue is done as part of the wake process and the unqueue
1790 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
1793 static inline void queue_me(struct futex_q
*q
, struct futex_hash_bucket
*hb
)
1794 __releases(&hb
->lock
)
1799 * The priority used to register this element is
1800 * - either the real thread-priority for the real-time threads
1801 * (i.e. threads with a priority lower than MAX_RT_PRIO)
1802 * - or MAX_RT_PRIO for non-RT threads.
1803 * Thus, all RT-threads are woken first in priority order, and
1804 * the others are woken last, in FIFO order.
1806 prio
= min(current
->normal_prio
, MAX_RT_PRIO
);
1808 plist_node_init(&q
->list
, prio
);
1809 plist_add(&q
->list
, &hb
->chain
);
1811 spin_unlock(&hb
->lock
);
1815 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
1816 * @q: The futex_q to unqueue
1818 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
1819 * be paired with exactly one earlier call to queue_me().
1822 * 1 - if the futex_q was still queued (and we removed unqueued it);
1823 * 0 - if the futex_q was already removed by the waking thread
1825 static int unqueue_me(struct futex_q
*q
)
1827 spinlock_t
*lock_ptr
;
1830 /* In the common case we don't take the spinlock, which is nice. */
1832 lock_ptr
= q
->lock_ptr
;
1834 if (lock_ptr
!= NULL
) {
1835 spin_lock(lock_ptr
);
1837 * q->lock_ptr can change between reading it and
1838 * spin_lock(), causing us to take the wrong lock. This
1839 * corrects the race condition.
1841 * Reasoning goes like this: if we have the wrong lock,
1842 * q->lock_ptr must have changed (maybe several times)
1843 * between reading it and the spin_lock(). It can
1844 * change again after the spin_lock() but only if it was
1845 * already changed before the spin_lock(). It cannot,
1846 * however, change back to the original value. Therefore
1847 * we can detect whether we acquired the correct lock.
1849 if (unlikely(lock_ptr
!= q
->lock_ptr
)) {
1850 spin_unlock(lock_ptr
);
1855 BUG_ON(q
->pi_state
);
1857 spin_unlock(lock_ptr
);
1861 drop_futex_key_refs(&q
->key
);
1866 * PI futexes can not be requeued and must remove themself from the
1867 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1870 static void unqueue_me_pi(struct futex_q
*q
)
1871 __releases(q
->lock_ptr
)
1875 BUG_ON(!q
->pi_state
);
1876 free_pi_state(q
->pi_state
);
1879 spin_unlock(q
->lock_ptr
);
1883 * Fixup the pi_state owner with the new owner.
1885 * Must be called with hash bucket lock held and mm->sem held for non
1888 static int fixup_pi_state_owner(u32 __user
*uaddr
, struct futex_q
*q
,
1889 struct task_struct
*newowner
)
1891 u32 newtid
= task_pid_vnr(newowner
) | FUTEX_WAITERS
;
1892 struct futex_pi_state
*pi_state
= q
->pi_state
;
1893 struct task_struct
*oldowner
= pi_state
->owner
;
1894 u32 uval
, uninitialized_var(curval
), newval
;
1898 if (!pi_state
->owner
)
1899 newtid
|= FUTEX_OWNER_DIED
;
1902 * We are here either because we stole the rtmutex from the
1903 * previous highest priority waiter or we are the highest priority
1904 * waiter but failed to get the rtmutex the first time.
1905 * We have to replace the newowner TID in the user space variable.
1906 * This must be atomic as we have to preserve the owner died bit here.
1908 * Note: We write the user space value _before_ changing the pi_state
1909 * because we can fault here. Imagine swapped out pages or a fork
1910 * that marked all the anonymous memory readonly for cow.
1912 * Modifying pi_state _before_ the user space value would
1913 * leave the pi_state in an inconsistent state when we fault
1914 * here, because we need to drop the hash bucket lock to
1915 * handle the fault. This might be observed in the PID check
1916 * in lookup_pi_state.
1919 if (get_futex_value_locked(&uval
, uaddr
))
1923 newval
= (uval
& FUTEX_OWNER_DIED
) | newtid
;
1925 if (cmpxchg_futex_value_locked(&curval
, uaddr
, uval
, newval
))
1933 * We fixed up user space. Now we need to fix the pi_state
1936 if (pi_state
->owner
!= NULL
) {
1937 raw_spin_lock_irq(&pi_state
->owner
->pi_lock
);
1938 WARN_ON(list_empty(&pi_state
->list
));
1939 list_del_init(&pi_state
->list
);
1940 raw_spin_unlock_irq(&pi_state
->owner
->pi_lock
);
1943 pi_state
->owner
= newowner
;
1945 raw_spin_lock_irq(&newowner
->pi_lock
);
1946 WARN_ON(!list_empty(&pi_state
->list
));
1947 list_add(&pi_state
->list
, &newowner
->pi_state_list
);
1948 raw_spin_unlock_irq(&newowner
->pi_lock
);
1952 * To handle the page fault we need to drop the hash bucket
1953 * lock here. That gives the other task (either the highest priority
1954 * waiter itself or the task which stole the rtmutex) the
1955 * chance to try the fixup of the pi_state. So once we are
1956 * back from handling the fault we need to check the pi_state
1957 * after reacquiring the hash bucket lock and before trying to
1958 * do another fixup. When the fixup has been done already we
1962 spin_unlock(q
->lock_ptr
);
1964 ret
= fault_in_user_writeable(uaddr
);
1966 spin_lock(q
->lock_ptr
);
1969 * Check if someone else fixed it for us:
1971 if (pi_state
->owner
!= oldowner
)
1980 static long futex_wait_restart(struct restart_block
*restart
);
1983 * fixup_owner() - Post lock pi_state and corner case management
1984 * @uaddr: user address of the futex
1985 * @q: futex_q (contains pi_state and access to the rt_mutex)
1986 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
1988 * After attempting to lock an rt_mutex, this function is called to cleanup
1989 * the pi_state owner as well as handle race conditions that may allow us to
1990 * acquire the lock. Must be called with the hb lock held.
1993 * 1 - success, lock taken;
1994 * 0 - success, lock not taken;
1995 * <0 - on error (-EFAULT)
1997 static int fixup_owner(u32 __user
*uaddr
, struct futex_q
*q
, int locked
)
1999 struct task_struct
*owner
;
2004 * Got the lock. We might not be the anticipated owner if we
2005 * did a lock-steal - fix up the PI-state in that case:
2007 if (q
->pi_state
->owner
!= current
)
2008 ret
= fixup_pi_state_owner(uaddr
, q
, current
);
2013 * Catch the rare case, where the lock was released when we were on the
2014 * way back before we locked the hash bucket.
2016 if (q
->pi_state
->owner
== current
) {
2018 * Try to get the rt_mutex now. This might fail as some other
2019 * task acquired the rt_mutex after we removed ourself from the
2020 * rt_mutex waiters list.
2022 if (rt_mutex_trylock(&q
->pi_state
->pi_mutex
)) {
2028 * pi_state is incorrect, some other task did a lock steal and
2029 * we returned due to timeout or signal without taking the
2030 * rt_mutex. Too late.
2032 raw_spin_lock(&q
->pi_state
->pi_mutex
.wait_lock
);
2033 owner
= rt_mutex_owner(&q
->pi_state
->pi_mutex
);
2035 owner
= rt_mutex_next_owner(&q
->pi_state
->pi_mutex
);
2036 raw_spin_unlock(&q
->pi_state
->pi_mutex
.wait_lock
);
2037 ret
= fixup_pi_state_owner(uaddr
, q
, owner
);
2042 * Paranoia check. If we did not take the lock, then we should not be
2043 * the owner of the rt_mutex.
2045 if (rt_mutex_owner(&q
->pi_state
->pi_mutex
) == current
)
2046 printk(KERN_ERR
"fixup_owner: ret = %d pi-mutex: %p "
2047 "pi-state %p\n", ret
,
2048 q
->pi_state
->pi_mutex
.owner
,
2049 q
->pi_state
->owner
);
2052 return ret
? ret
: locked
;
2056 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2057 * @hb: the futex hash bucket, must be locked by the caller
2058 * @q: the futex_q to queue up on
2059 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
2061 static void futex_wait_queue_me(struct futex_hash_bucket
*hb
, struct futex_q
*q
,
2062 struct hrtimer_sleeper
*timeout
)
2065 * The task state is guaranteed to be set before another task can
2066 * wake it. set_current_state() is implemented using set_mb() and
2067 * queue_me() calls spin_unlock() upon completion, both serializing
2068 * access to the hash list and forcing another memory barrier.
2070 set_current_state(TASK_INTERRUPTIBLE
);
2075 hrtimer_start_expires(&timeout
->timer
, HRTIMER_MODE_ABS
);
2076 if (!hrtimer_active(&timeout
->timer
))
2077 timeout
->task
= NULL
;
2081 * If we have been removed from the hash list, then another task
2082 * has tried to wake us, and we can skip the call to schedule().
2084 if (likely(!plist_node_empty(&q
->list
))) {
2086 * If the timer has already expired, current will already be
2087 * flagged for rescheduling. Only call schedule if there
2088 * is no timeout, or if it has yet to expire.
2090 if (!timeout
|| timeout
->task
)
2091 freezable_schedule();
2093 __set_current_state(TASK_RUNNING
);
2097 * futex_wait_setup() - Prepare to wait on a futex
2098 * @uaddr: the futex userspace address
2099 * @val: the expected value
2100 * @flags: futex flags (FLAGS_SHARED, etc.)
2101 * @q: the associated futex_q
2102 * @hb: storage for hash_bucket pointer to be returned to caller
2104 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2105 * compare it with the expected value. Handle atomic faults internally.
2106 * Return with the hb lock held and a q.key reference on success, and unlocked
2107 * with no q.key reference on failure.
2110 * 0 - uaddr contains val and hb has been locked;
2111 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
2113 static int futex_wait_setup(u32 __user
*uaddr
, u32 val
, unsigned int flags
,
2114 struct futex_q
*q
, struct futex_hash_bucket
**hb
)
2120 * Access the page AFTER the hash-bucket is locked.
2121 * Order is important:
2123 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2124 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2126 * The basic logical guarantee of a futex is that it blocks ONLY
2127 * if cond(var) is known to be true at the time of blocking, for
2128 * any cond. If we locked the hash-bucket after testing *uaddr, that
2129 * would open a race condition where we could block indefinitely with
2130 * cond(var) false, which would violate the guarantee.
2132 * On the other hand, we insert q and release the hash-bucket only
2133 * after testing *uaddr. This guarantees that futex_wait() will NOT
2134 * absorb a wakeup if *uaddr does not match the desired values
2135 * while the syscall executes.
2138 ret
= get_futex_key(uaddr
, flags
& FLAGS_SHARED
, &q
->key
, VERIFY_READ
);
2139 if (unlikely(ret
!= 0))
2143 *hb
= queue_lock(q
);
2145 ret
= get_futex_value_locked(&uval
, uaddr
);
2150 ret
= get_user(uval
, uaddr
);
2154 if (!(flags
& FLAGS_SHARED
))
2157 put_futex_key(&q
->key
);
2168 put_futex_key(&q
->key
);
2172 static int futex_wait(u32 __user
*uaddr
, unsigned int flags
, u32 val
,
2173 ktime_t
*abs_time
, u32 bitset
)
2175 struct hrtimer_sleeper timeout
, *to
= NULL
;
2176 struct restart_block
*restart
;
2177 struct futex_hash_bucket
*hb
;
2178 struct futex_q q
= futex_q_init
;
2188 hrtimer_init_on_stack(&to
->timer
, (flags
& FLAGS_CLOCKRT
) ?
2189 CLOCK_REALTIME
: CLOCK_MONOTONIC
,
2191 hrtimer_init_sleeper(to
, current
);
2192 hrtimer_set_expires_range_ns(&to
->timer
, *abs_time
,
2193 current
->timer_slack_ns
);
2198 * Prepare to wait on uaddr. On success, holds hb lock and increments
2201 ret
= futex_wait_setup(uaddr
, val
, flags
, &q
, &hb
);
2205 /* queue_me and wait for wakeup, timeout, or a signal. */
2206 futex_wait_queue_me(hb
, &q
, to
);
2208 /* If we were woken (and unqueued), we succeeded, whatever. */
2210 /* unqueue_me() drops q.key ref */
2211 if (!unqueue_me(&q
))
2214 if (to
&& !to
->task
)
2218 * We expect signal_pending(current), but we might be the
2219 * victim of a spurious wakeup as well.
2221 if (!signal_pending(current
))
2228 restart
= ¤t_thread_info()->restart_block
;
2229 restart
->fn
= futex_wait_restart
;
2230 restart
->futex
.uaddr
= uaddr
;
2231 restart
->futex
.val
= val
;
2232 restart
->futex
.time
= abs_time
->tv64
;
2233 restart
->futex
.bitset
= bitset
;
2234 restart
->futex
.flags
= flags
| FLAGS_HAS_TIMEOUT
;
2236 ret
= -ERESTART_RESTARTBLOCK
;
2240 hrtimer_cancel(&to
->timer
);
2241 destroy_hrtimer_on_stack(&to
->timer
);
2247 static long futex_wait_restart(struct restart_block
*restart
)
2249 u32 __user
*uaddr
= restart
->futex
.uaddr
;
2250 ktime_t t
, *tp
= NULL
;
2252 if (restart
->futex
.flags
& FLAGS_HAS_TIMEOUT
) {
2253 t
.tv64
= restart
->futex
.time
;
2256 restart
->fn
= do_no_restart_syscall
;
2258 return (long)futex_wait(uaddr
, restart
->futex
.flags
,
2259 restart
->futex
.val
, tp
, restart
->futex
.bitset
);
2264 * Userspace tried a 0 -> TID atomic transition of the futex value
2265 * and failed. The kernel side here does the whole locking operation:
2266 * if there are waiters then it will block, it does PI, etc. (Due to
2267 * races the kernel might see a 0 value of the futex too.)
2269 static int futex_lock_pi(u32 __user
*uaddr
, unsigned int flags
, int detect
,
2270 ktime_t
*time
, int trylock
)
2272 struct hrtimer_sleeper timeout
, *to
= NULL
;
2273 struct futex_hash_bucket
*hb
;
2274 struct futex_q q
= futex_q_init
;
2277 if (refill_pi_state_cache())
2282 hrtimer_init_on_stack(&to
->timer
, CLOCK_REALTIME
,
2284 hrtimer_init_sleeper(to
, current
);
2285 hrtimer_set_expires(&to
->timer
, *time
);
2289 ret
= get_futex_key(uaddr
, flags
& FLAGS_SHARED
, &q
.key
, VERIFY_WRITE
);
2290 if (unlikely(ret
!= 0))
2294 hb
= queue_lock(&q
);
2296 ret
= futex_lock_pi_atomic(uaddr
, hb
, &q
.key
, &q
.pi_state
, current
, 0);
2297 if (unlikely(ret
)) {
2300 /* We got the lock. */
2302 goto out_unlock_put_key
;
2307 * Task is exiting and we just wait for the
2311 put_futex_key(&q
.key
);
2315 goto out_unlock_put_key
;
2320 * Only actually queue now that the atomic ops are done:
2324 WARN_ON(!q
.pi_state
);
2326 * Block on the PI mutex:
2329 ret
= rt_mutex_timed_lock(&q
.pi_state
->pi_mutex
, to
, 1);
2331 ret
= rt_mutex_trylock(&q
.pi_state
->pi_mutex
);
2332 /* Fixup the trylock return value: */
2333 ret
= ret
? 0 : -EWOULDBLOCK
;
2336 spin_lock(q
.lock_ptr
);
2338 * Fixup the pi_state owner and possibly acquire the lock if we
2341 res
= fixup_owner(uaddr
, &q
, !ret
);
2343 * If fixup_owner() returned an error, proprogate that. If it acquired
2344 * the lock, clear our -ETIMEDOUT or -EINTR.
2347 ret
= (res
< 0) ? res
: 0;
2350 * If fixup_owner() faulted and was unable to handle the fault, unlock
2351 * it and return the fault to userspace.
2353 if (ret
&& (rt_mutex_owner(&q
.pi_state
->pi_mutex
) == current
))
2354 rt_mutex_unlock(&q
.pi_state
->pi_mutex
);
2356 /* Unqueue and drop the lock */
2365 put_futex_key(&q
.key
);
2368 destroy_hrtimer_on_stack(&to
->timer
);
2369 return ret
!= -EINTR
? ret
: -ERESTARTNOINTR
;
2374 ret
= fault_in_user_writeable(uaddr
);
2378 if (!(flags
& FLAGS_SHARED
))
2381 put_futex_key(&q
.key
);
2386 * Userspace attempted a TID -> 0 atomic transition, and failed.
2387 * This is the in-kernel slowpath: we look up the PI state (if any),
2388 * and do the rt-mutex unlock.
2390 static int futex_unlock_pi(u32 __user
*uaddr
, unsigned int flags
)
2392 struct futex_hash_bucket
*hb
;
2393 struct futex_q
*this, *next
;
2394 union futex_key key
= FUTEX_KEY_INIT
;
2395 u32 uval
, vpid
= task_pid_vnr(current
);
2399 if (get_user(uval
, uaddr
))
2402 * We release only a lock we actually own:
2404 if ((uval
& FUTEX_TID_MASK
) != vpid
)
2407 ret
= get_futex_key(uaddr
, flags
& FLAGS_SHARED
, &key
, VERIFY_WRITE
);
2408 if (unlikely(ret
!= 0))
2411 hb
= hash_futex(&key
);
2412 spin_lock(&hb
->lock
);
2415 * To avoid races, try to do the TID -> 0 atomic transition
2416 * again. If it succeeds then we can return without waking
2417 * anyone else up. We only try this if neither the waiters nor
2418 * the owner died bit are set.
2420 if (!(uval
& ~FUTEX_TID_MASK
) &&
2421 cmpxchg_futex_value_locked(&uval
, uaddr
, vpid
, 0))
2424 * Rare case: we managed to release the lock atomically,
2425 * no need to wake anyone else up:
2427 if (unlikely(uval
== vpid
))
2431 * Ok, other tasks may need to be woken up - check waiters
2432 * and do the wakeup if necessary:
2434 plist_for_each_entry_safe(this, next
, &hb
->chain
, list
) {
2435 if (!match_futex (&this->key
, &key
))
2437 ret
= wake_futex_pi(uaddr
, uval
, this);
2439 * The atomic access to the futex value
2440 * generated a pagefault, so retry the
2441 * user-access and the wakeup:
2448 * No waiters - kernel unlocks the futex:
2450 ret
= unlock_futex_pi(uaddr
, uval
);
2455 spin_unlock(&hb
->lock
);
2456 put_futex_key(&key
);
2462 spin_unlock(&hb
->lock
);
2463 put_futex_key(&key
);
2465 ret
= fault_in_user_writeable(uaddr
);
2473 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
2474 * @hb: the hash_bucket futex_q was original enqueued on
2475 * @q: the futex_q woken while waiting to be requeued
2476 * @key2: the futex_key of the requeue target futex
2477 * @timeout: the timeout associated with the wait (NULL if none)
2479 * Detect if the task was woken on the initial futex as opposed to the requeue
2480 * target futex. If so, determine if it was a timeout or a signal that caused
2481 * the wakeup and return the appropriate error code to the caller. Must be
2482 * called with the hb lock held.
2485 * 0 = no early wakeup detected;
2486 * <0 = -ETIMEDOUT or -ERESTARTNOINTR
2489 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket
*hb
,
2490 struct futex_q
*q
, union futex_key
*key2
,
2491 struct hrtimer_sleeper
*timeout
)
2496 * With the hb lock held, we avoid races while we process the wakeup.
2497 * We only need to hold hb (and not hb2) to ensure atomicity as the
2498 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
2499 * It can't be requeued from uaddr2 to something else since we don't
2500 * support a PI aware source futex for requeue.
2502 if (!match_futex(&q
->key
, key2
)) {
2503 WARN_ON(q
->lock_ptr
&& (&hb
->lock
!= q
->lock_ptr
));
2505 * We were woken prior to requeue by a timeout or a signal.
2506 * Unqueue the futex_q and determine which it was.
2508 plist_del(&q
->list
, &hb
->chain
);
2511 /* Handle spurious wakeups gracefully */
2513 if (timeout
&& !timeout
->task
)
2515 else if (signal_pending(current
))
2516 ret
= -ERESTARTNOINTR
;
2522 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
2523 * @uaddr: the futex we initially wait on (non-pi)
2524 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
2525 * the same type, no requeueing from private to shared, etc.
2526 * @val: the expected value of uaddr
2527 * @abs_time: absolute timeout
2528 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
2529 * @uaddr2: the pi futex we will take prior to returning to user-space
2531 * The caller will wait on uaddr and will be requeued by futex_requeue() to
2532 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
2533 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
2534 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
2535 * without one, the pi logic would not know which task to boost/deboost, if
2536 * there was a need to.
2538 * We call schedule in futex_wait_queue_me() when we enqueue and return there
2539 * via the following--
2540 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
2541 * 2) wakeup on uaddr2 after a requeue
2545 * If 3, cleanup and return -ERESTARTNOINTR.
2547 * If 2, we may then block on trying to take the rt_mutex and return via:
2548 * 5) successful lock
2551 * 8) other lock acquisition failure
2553 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
2555 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
2561 static int futex_wait_requeue_pi(u32 __user
*uaddr
, unsigned int flags
,
2562 u32 val
, ktime_t
*abs_time
, u32 bitset
,
2565 struct hrtimer_sleeper timeout
, *to
= NULL
;
2566 struct rt_mutex_waiter rt_waiter
;
2567 struct rt_mutex
*pi_mutex
= NULL
;
2568 struct futex_hash_bucket
*hb
;
2569 union futex_key key2
= FUTEX_KEY_INIT
;
2570 struct futex_q q
= futex_q_init
;
2573 if (uaddr
== uaddr2
)
2581 hrtimer_init_on_stack(&to
->timer
, (flags
& FLAGS_CLOCKRT
) ?
2582 CLOCK_REALTIME
: CLOCK_MONOTONIC
,
2584 hrtimer_init_sleeper(to
, current
);
2585 hrtimer_set_expires_range_ns(&to
->timer
, *abs_time
,
2586 current
->timer_slack_ns
);
2590 * The waiter is allocated on our stack, manipulated by the requeue
2591 * code while we sleep on uaddr.
2593 debug_rt_mutex_init_waiter(&rt_waiter
);
2594 RB_CLEAR_NODE(&rt_waiter
.pi_tree_entry
);
2595 RB_CLEAR_NODE(&rt_waiter
.tree_entry
);
2596 rt_waiter
.task
= NULL
;
2598 ret
= get_futex_key(uaddr2
, flags
& FLAGS_SHARED
, &key2
, VERIFY_WRITE
);
2599 if (unlikely(ret
!= 0))
2603 q
.rt_waiter
= &rt_waiter
;
2604 q
.requeue_pi_key
= &key2
;
2607 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
2610 ret
= futex_wait_setup(uaddr
, val
, flags
, &q
, &hb
);
2615 * The check above which compares uaddrs is not sufficient for
2616 * shared futexes. We need to compare the keys:
2618 if (match_futex(&q
.key
, &key2
)) {
2624 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
2625 futex_wait_queue_me(hb
, &q
, to
);
2627 spin_lock(&hb
->lock
);
2628 ret
= handle_early_requeue_pi_wakeup(hb
, &q
, &key2
, to
);
2629 spin_unlock(&hb
->lock
);
2634 * In order for us to be here, we know our q.key == key2, and since
2635 * we took the hb->lock above, we also know that futex_requeue() has
2636 * completed and we no longer have to concern ourselves with a wakeup
2637 * race with the atomic proxy lock acquisition by the requeue code. The
2638 * futex_requeue dropped our key1 reference and incremented our key2
2642 /* Check if the requeue code acquired the second futex for us. */
2645 * Got the lock. We might not be the anticipated owner if we
2646 * did a lock-steal - fix up the PI-state in that case.
2648 if (q
.pi_state
&& (q
.pi_state
->owner
!= current
)) {
2649 spin_lock(q
.lock_ptr
);
2650 ret
= fixup_pi_state_owner(uaddr2
, &q
, current
);
2651 spin_unlock(q
.lock_ptr
);
2655 * We have been woken up by futex_unlock_pi(), a timeout, or a
2656 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
2659 WARN_ON(!q
.pi_state
);
2660 pi_mutex
= &q
.pi_state
->pi_mutex
;
2661 ret
= rt_mutex_finish_proxy_lock(pi_mutex
, to
, &rt_waiter
, 1);
2662 debug_rt_mutex_free_waiter(&rt_waiter
);
2664 spin_lock(q
.lock_ptr
);
2666 * Fixup the pi_state owner and possibly acquire the lock if we
2669 res
= fixup_owner(uaddr2
, &q
, !ret
);
2671 * If fixup_owner() returned an error, proprogate that. If it
2672 * acquired the lock, clear -ETIMEDOUT or -EINTR.
2675 ret
= (res
< 0) ? res
: 0;
2677 /* Unqueue and drop the lock. */
2682 * If fixup_pi_state_owner() faulted and was unable to handle the
2683 * fault, unlock the rt_mutex and return the fault to userspace.
2685 if (ret
== -EFAULT
) {
2686 if (pi_mutex
&& rt_mutex_owner(pi_mutex
) == current
)
2687 rt_mutex_unlock(pi_mutex
);
2688 } else if (ret
== -EINTR
) {
2690 * We've already been requeued, but cannot restart by calling
2691 * futex_lock_pi() directly. We could restart this syscall, but
2692 * it would detect that the user space "val" changed and return
2693 * -EWOULDBLOCK. Save the overhead of the restart and return
2694 * -EWOULDBLOCK directly.
2700 put_futex_key(&q
.key
);
2702 put_futex_key(&key2
);
2706 hrtimer_cancel(&to
->timer
);
2707 destroy_hrtimer_on_stack(&to
->timer
);
2713 * Support for robust futexes: the kernel cleans up held futexes at
2716 * Implementation: user-space maintains a per-thread list of locks it
2717 * is holding. Upon do_exit(), the kernel carefully walks this list,
2718 * and marks all locks that are owned by this thread with the
2719 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
2720 * always manipulated with the lock held, so the list is private and
2721 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
2722 * field, to allow the kernel to clean up if the thread dies after
2723 * acquiring the lock, but just before it could have added itself to
2724 * the list. There can only be one such pending lock.
2728 * sys_set_robust_list() - Set the robust-futex list head of a task
2729 * @head: pointer to the list-head
2730 * @len: length of the list-head, as userspace expects
2732 SYSCALL_DEFINE2(set_robust_list
, struct robust_list_head __user
*, head
,
2735 if (!futex_cmpxchg_enabled
)
2738 * The kernel knows only one size for now:
2740 if (unlikely(len
!= sizeof(*head
)))
2743 current
->robust_list
= head
;
2749 * sys_get_robust_list() - Get the robust-futex list head of a task
2750 * @pid: pid of the process [zero for current task]
2751 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
2752 * @len_ptr: pointer to a length field, the kernel fills in the header size
2754 SYSCALL_DEFINE3(get_robust_list
, int, pid
,
2755 struct robust_list_head __user
* __user
*, head_ptr
,
2756 size_t __user
*, len_ptr
)
2758 struct robust_list_head __user
*head
;
2760 struct task_struct
*p
;
2762 if (!futex_cmpxchg_enabled
)
2771 p
= find_task_by_vpid(pid
);
2777 if (!ptrace_may_access(p
, PTRACE_MODE_READ
))
2780 head
= p
->robust_list
;
2783 if (put_user(sizeof(*head
), len_ptr
))
2785 return put_user(head
, head_ptr
);
2794 * Process a futex-list entry, check whether it's owned by the
2795 * dying task, and do notification if so:
2797 int handle_futex_death(u32 __user
*uaddr
, struct task_struct
*curr
, int pi
)
2799 u32 uval
, uninitialized_var(nval
), mval
;
2802 if (get_user(uval
, uaddr
))
2805 if ((uval
& FUTEX_TID_MASK
) == task_pid_vnr(curr
)) {
2807 * Ok, this dying thread is truly holding a futex
2808 * of interest. Set the OWNER_DIED bit atomically
2809 * via cmpxchg, and if the value had FUTEX_WAITERS
2810 * set, wake up a waiter (if any). (We have to do a
2811 * futex_wake() even if OWNER_DIED is already set -
2812 * to handle the rare but possible case of recursive
2813 * thread-death.) The rest of the cleanup is done in
2816 mval
= (uval
& FUTEX_WAITERS
) | FUTEX_OWNER_DIED
;
2818 * We are not holding a lock here, but we want to have
2819 * the pagefault_disable/enable() protection because
2820 * we want to handle the fault gracefully. If the
2821 * access fails we try to fault in the futex with R/W
2822 * verification via get_user_pages. get_user() above
2823 * does not guarantee R/W access. If that fails we
2824 * give up and leave the futex locked.
2826 if (cmpxchg_futex_value_locked(&nval
, uaddr
, uval
, mval
)) {
2827 if (fault_in_user_writeable(uaddr
))
2835 * Wake robust non-PI futexes here. The wakeup of
2836 * PI futexes happens in exit_pi_state():
2838 if (!pi
&& (uval
& FUTEX_WAITERS
))
2839 futex_wake(uaddr
, 1, 1, FUTEX_BITSET_MATCH_ANY
);
2845 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
2847 static inline int fetch_robust_entry(struct robust_list __user
**entry
,
2848 struct robust_list __user
* __user
*head
,
2851 unsigned long uentry
;
2853 if (get_user(uentry
, (unsigned long __user
*)head
))
2856 *entry
= (void __user
*)(uentry
& ~1UL);
2863 * Walk curr->robust_list (very carefully, it's a userspace list!)
2864 * and mark any locks found there dead, and notify any waiters.
2866 * We silently return on any sign of list-walking problem.
2868 void exit_robust_list(struct task_struct
*curr
)
2870 struct robust_list_head __user
*head
= curr
->robust_list
;
2871 struct robust_list __user
*entry
, *next_entry
, *pending
;
2872 unsigned int limit
= ROBUST_LIST_LIMIT
, pi
, pip
;
2873 unsigned int uninitialized_var(next_pi
);
2874 unsigned long futex_offset
;
2877 if (!futex_cmpxchg_enabled
)
2881 * Fetch the list head (which was registered earlier, via
2882 * sys_set_robust_list()):
2884 if (fetch_robust_entry(&entry
, &head
->list
.next
, &pi
))
2887 * Fetch the relative futex offset:
2889 if (get_user(futex_offset
, &head
->futex_offset
))
2892 * Fetch any possibly pending lock-add first, and handle it
2895 if (fetch_robust_entry(&pending
, &head
->list_op_pending
, &pip
))
2898 next_entry
= NULL
; /* avoid warning with gcc */
2899 while (entry
!= &head
->list
) {
2901 * Fetch the next entry in the list before calling
2902 * handle_futex_death:
2904 rc
= fetch_robust_entry(&next_entry
, &entry
->next
, &next_pi
);
2906 * A pending lock might already be on the list, so
2907 * don't process it twice:
2909 if (entry
!= pending
)
2910 if (handle_futex_death((void __user
*)entry
+ futex_offset
,
2918 * Avoid excessively long or circular lists:
2927 handle_futex_death((void __user
*)pending
+ futex_offset
,
2931 long do_futex(u32 __user
*uaddr
, int op
, u32 val
, ktime_t
*timeout
,
2932 u32 __user
*uaddr2
, u32 val2
, u32 val3
)
2934 int cmd
= op
& FUTEX_CMD_MASK
;
2935 unsigned int flags
= 0;
2937 if (!(op
& FUTEX_PRIVATE_FLAG
))
2938 flags
|= FLAGS_SHARED
;
2940 if (op
& FUTEX_CLOCK_REALTIME
) {
2941 flags
|= FLAGS_CLOCKRT
;
2942 if (cmd
!= FUTEX_WAIT_BITSET
&& cmd
!= FUTEX_WAIT_REQUEUE_PI
)
2948 case FUTEX_UNLOCK_PI
:
2949 case FUTEX_TRYLOCK_PI
:
2950 case FUTEX_WAIT_REQUEUE_PI
:
2951 case FUTEX_CMP_REQUEUE_PI
:
2952 if (!futex_cmpxchg_enabled
)
2958 val3
= FUTEX_BITSET_MATCH_ANY
;
2959 case FUTEX_WAIT_BITSET
:
2960 return futex_wait(uaddr
, flags
, val
, timeout
, val3
);
2962 val3
= FUTEX_BITSET_MATCH_ANY
;
2963 case FUTEX_WAKE_BITSET
:
2964 return futex_wake(uaddr
, flags
, val
, val3
);
2966 return futex_requeue(uaddr
, flags
, uaddr2
, val
, val2
, NULL
, 0);
2967 case FUTEX_CMP_REQUEUE
:
2968 return futex_requeue(uaddr
, flags
, uaddr2
, val
, val2
, &val3
, 0);
2970 return futex_wake_op(uaddr
, flags
, uaddr2
, val
, val2
, val3
);
2972 return futex_lock_pi(uaddr
, flags
, val
, timeout
, 0);
2973 case FUTEX_UNLOCK_PI
:
2974 return futex_unlock_pi(uaddr
, flags
);
2975 case FUTEX_TRYLOCK_PI
:
2976 return futex_lock_pi(uaddr
, flags
, 0, timeout
, 1);
2977 case FUTEX_WAIT_REQUEUE_PI
:
2978 val3
= FUTEX_BITSET_MATCH_ANY
;
2979 return futex_wait_requeue_pi(uaddr
, flags
, val
, timeout
, val3
,
2981 case FUTEX_CMP_REQUEUE_PI
:
2982 return futex_requeue(uaddr
, flags
, uaddr2
, val
, val2
, &val3
, 1);
2988 SYSCALL_DEFINE6(futex
, u32 __user
*, uaddr
, int, op
, u32
, val
,
2989 struct timespec __user
*, utime
, u32 __user
*, uaddr2
,
2993 ktime_t t
, *tp
= NULL
;
2995 int cmd
= op
& FUTEX_CMD_MASK
;
2997 if (utime
&& (cmd
== FUTEX_WAIT
|| cmd
== FUTEX_LOCK_PI
||
2998 cmd
== FUTEX_WAIT_BITSET
||
2999 cmd
== FUTEX_WAIT_REQUEUE_PI
)) {
3000 if (copy_from_user(&ts
, utime
, sizeof(ts
)) != 0)
3002 if (!timespec_valid(&ts
))
3005 t
= timespec_to_ktime(ts
);
3006 if (cmd
== FUTEX_WAIT
)
3007 t
= ktime_add_safe(ktime_get(), t
);
3011 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
3012 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
3014 if (cmd
== FUTEX_REQUEUE
|| cmd
== FUTEX_CMP_REQUEUE
||
3015 cmd
== FUTEX_CMP_REQUEUE_PI
|| cmd
== FUTEX_WAKE_OP
)
3016 val2
= (u32
) (unsigned long) utime
;
3018 return do_futex(uaddr
, op
, val
, tp
, uaddr2
, val2
, val3
);
3021 static void __init
futex_detect_cmpxchg(void)
3023 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
3027 * This will fail and we want it. Some arch implementations do
3028 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3029 * functionality. We want to know that before we call in any
3030 * of the complex code paths. Also we want to prevent
3031 * registration of robust lists in that case. NULL is
3032 * guaranteed to fault and we get -EFAULT on functional
3033 * implementation, the non-functional ones will return
3036 if (cmpxchg_futex_value_locked(&curval
, NULL
, 0, 0) == -EFAULT
)
3037 futex_cmpxchg_enabled
= 1;
3041 static int __init
futex_init(void)
3043 unsigned int futex_shift
;
3046 #if CONFIG_BASE_SMALL
3047 futex_hashsize
= 16;
3049 futex_hashsize
= roundup_pow_of_two(256 * num_possible_cpus());
3052 futex_queues
= alloc_large_system_hash("futex", sizeof(*futex_queues
),
3054 futex_hashsize
< 256 ? HASH_SMALL
: 0,
3056 futex_hashsize
, futex_hashsize
);
3057 futex_hashsize
= 1UL << futex_shift
;
3059 futex_detect_cmpxchg();
3061 for (i
= 0; i
< futex_hashsize
; i
++) {
3062 atomic_set(&futex_queues
[i
].waiters
, 0);
3063 plist_head_init(&futex_queues
[i
].chain
);
3064 spin_lock_init(&futex_queues
[i
].lock
);
3069 __initcall(futex_init
);