net: ethernet: Fix memleak in ethoc_probe
[linux/fpc-iii.git] / kernel / futex.c
blob7123d9cab45681f4260218a322782cfcbe6b039b
1 /*
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>
49 #include <linux/fs.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>
67 #include <linux/fault-inject.h>
69 #include <asm/futex.h>
71 #include "locking/rtmutex_common.h"
74 * READ this before attempting to hack on futexes!
76 * Basic futex operation and ordering guarantees
77 * =============================================
79 * The waiter reads the futex value in user space and calls
80 * futex_wait(). This function computes the hash bucket and acquires
81 * the hash bucket lock. After that it reads the futex user space value
82 * again and verifies that the data has not changed. If it has not changed
83 * it enqueues itself into the hash bucket, releases the hash bucket lock
84 * and schedules.
86 * The waker side modifies the user space value of the futex and calls
87 * futex_wake(). This function computes the hash bucket and acquires the
88 * hash bucket lock. Then it looks for waiters on that futex in the hash
89 * bucket and wakes them.
91 * In futex wake up scenarios where no tasks are blocked on a futex, taking
92 * the hb spinlock can be avoided and simply return. In order for this
93 * optimization to work, ordering guarantees must exist so that the waiter
94 * being added to the list is acknowledged when the list is concurrently being
95 * checked by the waker, avoiding scenarios like the following:
97 * CPU 0 CPU 1
98 * val = *futex;
99 * sys_futex(WAIT, futex, val);
100 * futex_wait(futex, val);
101 * uval = *futex;
102 * *futex = newval;
103 * sys_futex(WAKE, futex);
104 * futex_wake(futex);
105 * if (queue_empty())
106 * return;
107 * if (uval == val)
108 * lock(hash_bucket(futex));
109 * queue();
110 * unlock(hash_bucket(futex));
111 * schedule();
113 * This would cause the waiter on CPU 0 to wait forever because it
114 * missed the transition of the user space value from val to newval
115 * and the waker did not find the waiter in the hash bucket queue.
117 * The correct serialization ensures that a waiter either observes
118 * the changed user space value before blocking or is woken by a
119 * concurrent waker:
121 * CPU 0 CPU 1
122 * val = *futex;
123 * sys_futex(WAIT, futex, val);
124 * futex_wait(futex, val);
126 * waiters++; (a)
127 * smp_mb(); (A) <-- paired with -.
129 * lock(hash_bucket(futex)); |
131 * uval = *futex; |
132 * | *futex = newval;
133 * | sys_futex(WAKE, futex);
134 * | futex_wake(futex);
136 * `--------> smp_mb(); (B)
137 * if (uval == val)
138 * queue();
139 * unlock(hash_bucket(futex));
140 * schedule(); if (waiters)
141 * lock(hash_bucket(futex));
142 * else wake_waiters(futex);
143 * waiters--; (b) unlock(hash_bucket(futex));
145 * Where (A) orders the waiters increment and the futex value read through
146 * atomic operations (see hb_waiters_inc) and where (B) orders the write
147 * to futex and the waiters read -- this is done by the barriers for both
148 * shared and private futexes in get_futex_key_refs().
150 * This yields the following case (where X:=waiters, Y:=futex):
152 * X = Y = 0
154 * w[X]=1 w[Y]=1
155 * MB MB
156 * r[Y]=y r[X]=x
158 * Which guarantees that x==0 && y==0 is impossible; which translates back into
159 * the guarantee that we cannot both miss the futex variable change and the
160 * enqueue.
162 * Note that a new waiter is accounted for in (a) even when it is possible that
163 * the wait call can return error, in which case we backtrack from it in (b).
164 * Refer to the comment in queue_lock().
166 * Similarly, in order to account for waiters being requeued on another
167 * address we always increment the waiters for the destination bucket before
168 * acquiring the lock. It then decrements them again after releasing it -
169 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
170 * will do the additional required waiter count housekeeping. This is done for
171 * double_lock_hb() and double_unlock_hb(), respectively.
174 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
175 int __read_mostly futex_cmpxchg_enabled;
176 #endif
179 * Futex flags used to encode options to functions and preserve them across
180 * restarts.
182 #ifdef CONFIG_MMU
183 # define FLAGS_SHARED 0x01
184 #else
186 * NOMMU does not have per process address space. Let the compiler optimize
187 * code away.
189 # define FLAGS_SHARED 0x00
190 #endif
191 #define FLAGS_CLOCKRT 0x02
192 #define FLAGS_HAS_TIMEOUT 0x04
195 * Priority Inheritance state:
197 struct futex_pi_state {
199 * list of 'owned' pi_state instances - these have to be
200 * cleaned up in do_exit() if the task exits prematurely:
202 struct list_head list;
205 * The PI object:
207 struct rt_mutex pi_mutex;
209 struct task_struct *owner;
210 atomic_t refcount;
212 union futex_key key;
216 * struct futex_q - The hashed futex queue entry, one per waiting task
217 * @list: priority-sorted list of tasks waiting on this futex
218 * @task: the task waiting on the futex
219 * @lock_ptr: the hash bucket lock
220 * @key: the key the futex is hashed on
221 * @pi_state: optional priority inheritance state
222 * @rt_waiter: rt_waiter storage for use with requeue_pi
223 * @requeue_pi_key: the requeue_pi target futex key
224 * @bitset: bitset for the optional bitmasked wakeup
226 * We use this hashed waitqueue, instead of a normal wait_queue_t, so
227 * we can wake only the relevant ones (hashed queues may be shared).
229 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
230 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
231 * The order of wakeup is always to make the first condition true, then
232 * the second.
234 * PI futexes are typically woken before they are removed from the hash list via
235 * the rt_mutex code. See unqueue_me_pi().
237 struct futex_q {
238 struct plist_node list;
240 struct task_struct *task;
241 spinlock_t *lock_ptr;
242 union futex_key key;
243 struct futex_pi_state *pi_state;
244 struct rt_mutex_waiter *rt_waiter;
245 union futex_key *requeue_pi_key;
246 u32 bitset;
249 static const struct futex_q futex_q_init = {
250 /* list gets initialized in queue_me()*/
251 .key = FUTEX_KEY_INIT,
252 .bitset = FUTEX_BITSET_MATCH_ANY
256 * Hash buckets are shared by all the futex_keys that hash to the same
257 * location. Each key may have multiple futex_q structures, one for each task
258 * waiting on a futex.
260 struct futex_hash_bucket {
261 atomic_t waiters;
262 spinlock_t lock;
263 struct plist_head chain;
264 } ____cacheline_aligned_in_smp;
267 * The base of the bucket array and its size are always used together
268 * (after initialization only in hash_futex()), so ensure that they
269 * reside in the same cacheline.
271 static struct {
272 struct futex_hash_bucket *queues;
273 unsigned long hashsize;
274 } __futex_data __read_mostly __aligned(2*sizeof(long));
275 #define futex_queues (__futex_data.queues)
276 #define futex_hashsize (__futex_data.hashsize)
280 * Fault injections for futexes.
282 #ifdef CONFIG_FAIL_FUTEX
284 static struct {
285 struct fault_attr attr;
287 bool ignore_private;
288 } fail_futex = {
289 .attr = FAULT_ATTR_INITIALIZER,
290 .ignore_private = false,
293 static int __init setup_fail_futex(char *str)
295 return setup_fault_attr(&fail_futex.attr, str);
297 __setup("fail_futex=", setup_fail_futex);
299 static bool should_fail_futex(bool fshared)
301 if (fail_futex.ignore_private && !fshared)
302 return false;
304 return should_fail(&fail_futex.attr, 1);
307 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
309 static int __init fail_futex_debugfs(void)
311 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
312 struct dentry *dir;
314 dir = fault_create_debugfs_attr("fail_futex", NULL,
315 &fail_futex.attr);
316 if (IS_ERR(dir))
317 return PTR_ERR(dir);
319 if (!debugfs_create_bool("ignore-private", mode, dir,
320 &fail_futex.ignore_private)) {
321 debugfs_remove_recursive(dir);
322 return -ENOMEM;
325 return 0;
328 late_initcall(fail_futex_debugfs);
330 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
332 #else
333 static inline bool should_fail_futex(bool fshared)
335 return false;
337 #endif /* CONFIG_FAIL_FUTEX */
339 static inline void futex_get_mm(union futex_key *key)
341 atomic_inc(&key->private.mm->mm_count);
343 * Ensure futex_get_mm() implies a full barrier such that
344 * get_futex_key() implies a full barrier. This is relied upon
345 * as smp_mb(); (B), see the ordering comment above.
347 smp_mb__after_atomic();
351 * Reflects a new waiter being added to the waitqueue.
353 static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
355 #ifdef CONFIG_SMP
356 atomic_inc(&hb->waiters);
358 * Full barrier (A), see the ordering comment above.
360 smp_mb__after_atomic();
361 #endif
365 * Reflects a waiter being removed from the waitqueue by wakeup
366 * paths.
368 static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
370 #ifdef CONFIG_SMP
371 atomic_dec(&hb->waiters);
372 #endif
375 static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
377 #ifdef CONFIG_SMP
378 return atomic_read(&hb->waiters);
379 #else
380 return 1;
381 #endif
385 * hash_futex - Return the hash bucket in the global hash
386 * @key: Pointer to the futex key for which the hash is calculated
388 * We hash on the keys returned from get_futex_key (see below) and return the
389 * corresponding hash bucket in the global hash.
391 static struct futex_hash_bucket *hash_futex(union futex_key *key)
393 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
394 key->both.offset);
396 return &futex_queues[hash & (futex_hashsize - 1)];
401 * match_futex - Check whether two futex keys are equal
402 * @key1: Pointer to key1
403 * @key2: Pointer to key2
405 * Return 1 if two futex_keys are equal, 0 otherwise.
407 static inline int match_futex(union futex_key *key1, union futex_key *key2)
409 return (key1 && key2
410 && key1->both.word == key2->both.word
411 && key1->both.ptr == key2->both.ptr
412 && key1->both.offset == key2->both.offset);
416 * Take a reference to the resource addressed by a key.
417 * Can be called while holding spinlocks.
420 static void get_futex_key_refs(union futex_key *key)
422 if (!key->both.ptr)
423 return;
426 * On MMU less systems futexes are always "private" as there is no per
427 * process address space. We need the smp wmb nevertheless - yes,
428 * arch/blackfin has MMU less SMP ...
430 if (!IS_ENABLED(CONFIG_MMU)) {
431 smp_mb(); /* explicit smp_mb(); (B) */
432 return;
435 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
436 case FUT_OFF_INODE:
437 smp_mb(); /* explicit smp_mb(); (B) */
438 break;
439 case FUT_OFF_MMSHARED:
440 futex_get_mm(key); /* implies smp_mb(); (B) */
441 break;
442 default:
444 * Private futexes do not hold reference on an inode or
445 * mm, therefore the only purpose of calling get_futex_key_refs
446 * is because we need the barrier for the lockless waiter check.
448 smp_mb(); /* explicit smp_mb(); (B) */
453 * Drop a reference to the resource addressed by a key.
454 * The hash bucket spinlock must not be held. This is
455 * a no-op for private futexes, see comment in the get
456 * counterpart.
458 static void drop_futex_key_refs(union futex_key *key)
460 if (!key->both.ptr) {
461 /* If we're here then we tried to put a key we failed to get */
462 WARN_ON_ONCE(1);
463 return;
466 if (!IS_ENABLED(CONFIG_MMU))
467 return;
469 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
470 case FUT_OFF_INODE:
471 break;
472 case FUT_OFF_MMSHARED:
473 mmdrop(key->private.mm);
474 break;
479 * Generate a machine wide unique identifier for this inode.
481 * This relies on u64 not wrapping in the life-time of the machine; which with
482 * 1ns resolution means almost 585 years.
484 * This further relies on the fact that a well formed program will not unmap
485 * the file while it has a (shared) futex waiting on it. This mapping will have
486 * a file reference which pins the mount and inode.
488 * If for some reason an inode gets evicted and read back in again, it will get
489 * a new sequence number and will _NOT_ match, even though it is the exact same
490 * file.
492 * It is important that match_futex() will never have a false-positive, esp.
493 * for PI futexes that can mess up the state. The above argues that false-negatives
494 * are only possible for malformed programs.
496 static u64 get_inode_sequence_number(struct inode *inode)
498 static atomic64_t i_seq;
499 u64 old;
501 /* Does the inode already have a sequence number? */
502 old = atomic64_read(&inode->i_sequence);
503 if (likely(old))
504 return old;
506 for (;;) {
507 u64 new = atomic64_add_return(1, &i_seq);
508 if (WARN_ON_ONCE(!new))
509 continue;
511 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
512 if (old)
513 return old;
514 return new;
519 * get_futex_key() - Get parameters which are the keys for a futex
520 * @uaddr: virtual address of the futex
521 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
522 * @key: address where result is stored.
523 * @rw: mapping needs to be read/write (values: VERIFY_READ,
524 * VERIFY_WRITE)
526 * Return: a negative error code or 0
528 * The key words are stored in *key on success.
530 * For shared mappings (when @fshared), the key is:
531 * ( inode->i_sequence, page->index, offset_within_page )
532 * [ also see get_inode_sequence_number() ]
534 * For private mappings (or when !@fshared), the key is:
535 * ( current->mm, address, 0 )
537 * This allows (cross process, where applicable) identification of the futex
538 * without keeping the page pinned for the duration of the FUTEX_WAIT.
540 * lock_page() might sleep, the caller should not hold a spinlock.
542 static int
543 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
545 unsigned long address = (unsigned long)uaddr;
546 struct mm_struct *mm = current->mm;
547 struct page *page, *tail;
548 struct address_space *mapping;
549 int err, ro = 0;
552 * The futex address must be "naturally" aligned.
554 key->both.offset = address % PAGE_SIZE;
555 if (unlikely((address % sizeof(u32)) != 0))
556 return -EINVAL;
557 address -= key->both.offset;
559 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
560 return -EFAULT;
562 if (unlikely(should_fail_futex(fshared)))
563 return -EFAULT;
566 * PROCESS_PRIVATE futexes are fast.
567 * As the mm cannot disappear under us and the 'key' only needs
568 * virtual address, we dont even have to find the underlying vma.
569 * Note : We do have to check 'uaddr' is a valid user address,
570 * but access_ok() should be faster than find_vma()
572 if (!fshared) {
573 key->private.mm = mm;
574 key->private.address = address;
575 get_futex_key_refs(key); /* implies smp_mb(); (B) */
576 return 0;
579 again:
580 /* Ignore any VERIFY_READ mapping (futex common case) */
581 if (unlikely(should_fail_futex(fshared)))
582 return -EFAULT;
584 err = get_user_pages_fast(address, 1, 1, &page);
586 * If write access is not required (eg. FUTEX_WAIT), try
587 * and get read-only access.
589 if (err == -EFAULT && rw == VERIFY_READ) {
590 err = get_user_pages_fast(address, 1, 0, &page);
591 ro = 1;
593 if (err < 0)
594 return err;
595 else
596 err = 0;
599 * The treatment of mapping from this point on is critical. The page
600 * lock protects many things but in this context the page lock
601 * stabilizes mapping, prevents inode freeing in the shared
602 * file-backed region case and guards against movement to swap cache.
604 * Strictly speaking the page lock is not needed in all cases being
605 * considered here and page lock forces unnecessarily serialization
606 * From this point on, mapping will be re-verified if necessary and
607 * page lock will be acquired only if it is unavoidable
609 * Mapping checks require the head page for any compound page so the
610 * head page and mapping is looked up now. For anonymous pages, it
611 * does not matter if the page splits in the future as the key is
612 * based on the address. For filesystem-backed pages, the tail is
613 * required as the index of the page determines the key. For
614 * base pages, there is no tail page and tail == page.
616 tail = page;
617 page = compound_head(page);
618 mapping = READ_ONCE(page->mapping);
621 * If page->mapping is NULL, then it cannot be a PageAnon
622 * page; but it might be the ZERO_PAGE or in the gate area or
623 * in a special mapping (all cases which we are happy to fail);
624 * or it may have been a good file page when get_user_pages_fast
625 * found it, but truncated or holepunched or subjected to
626 * invalidate_complete_page2 before we got the page lock (also
627 * cases which we are happy to fail). And we hold a reference,
628 * so refcount care in invalidate_complete_page's remove_mapping
629 * prevents drop_caches from setting mapping to NULL beneath us.
631 * The case we do have to guard against is when memory pressure made
632 * shmem_writepage move it from filecache to swapcache beneath us:
633 * an unlikely race, but we do need to retry for page->mapping.
635 if (unlikely(!mapping)) {
636 int shmem_swizzled;
639 * Page lock is required to identify which special case above
640 * applies. If this is really a shmem page then the page lock
641 * will prevent unexpected transitions.
643 lock_page(page);
644 shmem_swizzled = PageSwapCache(page) || page->mapping;
645 unlock_page(page);
646 put_page(page);
648 if (shmem_swizzled)
649 goto again;
651 return -EFAULT;
655 * Private mappings are handled in a simple way.
657 * If the futex key is stored on an anonymous page, then the associated
658 * object is the mm which is implicitly pinned by the calling process.
660 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
661 * it's a read-only handle, it's expected that futexes attach to
662 * the object not the particular process.
664 if (PageAnon(page)) {
666 * A RO anonymous page will never change and thus doesn't make
667 * sense for futex operations.
669 if (unlikely(should_fail_futex(fshared)) || ro) {
670 err = -EFAULT;
671 goto out;
674 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
675 key->private.mm = mm;
676 key->private.address = address;
678 } else {
679 struct inode *inode;
682 * The associated futex object in this case is the inode and
683 * the page->mapping must be traversed. Ordinarily this should
684 * be stabilised under page lock but it's not strictly
685 * necessary in this case as we just want to pin the inode, not
686 * update the radix tree or anything like that.
688 * The RCU read lock is taken as the inode is finally freed
689 * under RCU. If the mapping still matches expectations then the
690 * mapping->host can be safely accessed as being a valid inode.
692 rcu_read_lock();
694 if (READ_ONCE(page->mapping) != mapping) {
695 rcu_read_unlock();
696 put_page(page);
698 goto again;
701 inode = READ_ONCE(mapping->host);
702 if (!inode) {
703 rcu_read_unlock();
704 put_page(page);
706 goto again;
709 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
710 key->shared.i_seq = get_inode_sequence_number(inode);
711 key->shared.pgoff = basepage_index(tail);
712 rcu_read_unlock();
715 get_futex_key_refs(key); /* implies smp_mb(); (B) */
717 out:
718 put_page(page);
719 return err;
722 static inline void put_futex_key(union futex_key *key)
724 drop_futex_key_refs(key);
728 * fault_in_user_writeable() - Fault in user address and verify RW access
729 * @uaddr: pointer to faulting user space address
731 * Slow path to fixup the fault we just took in the atomic write
732 * access to @uaddr.
734 * We have no generic implementation of a non-destructive write to the
735 * user address. We know that we faulted in the atomic pagefault
736 * disabled section so we can as well avoid the #PF overhead by
737 * calling get_user_pages() right away.
739 static int fault_in_user_writeable(u32 __user *uaddr)
741 struct mm_struct *mm = current->mm;
742 int ret;
744 down_read(&mm->mmap_sem);
745 ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
746 FAULT_FLAG_WRITE, NULL);
747 up_read(&mm->mmap_sem);
749 return ret < 0 ? ret : 0;
753 * futex_top_waiter() - Return the highest priority waiter on a futex
754 * @hb: the hash bucket the futex_q's reside in
755 * @key: the futex key (to distinguish it from other futex futex_q's)
757 * Must be called with the hb lock held.
759 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
760 union futex_key *key)
762 struct futex_q *this;
764 plist_for_each_entry(this, &hb->chain, list) {
765 if (match_futex(&this->key, key))
766 return this;
768 return NULL;
771 static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
772 u32 uval, u32 newval)
774 int ret;
776 pagefault_disable();
777 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
778 pagefault_enable();
780 return ret;
783 static int get_futex_value_locked(u32 *dest, u32 __user *from)
785 int ret;
787 pagefault_disable();
788 ret = __get_user(*dest, from);
789 pagefault_enable();
791 return ret ? -EFAULT : 0;
796 * PI code:
798 static int refill_pi_state_cache(void)
800 struct futex_pi_state *pi_state;
802 if (likely(current->pi_state_cache))
803 return 0;
805 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
807 if (!pi_state)
808 return -ENOMEM;
810 INIT_LIST_HEAD(&pi_state->list);
811 /* pi_mutex gets initialized later */
812 pi_state->owner = NULL;
813 atomic_set(&pi_state->refcount, 1);
814 pi_state->key = FUTEX_KEY_INIT;
816 current->pi_state_cache = pi_state;
818 return 0;
821 static struct futex_pi_state * alloc_pi_state(void)
823 struct futex_pi_state *pi_state = current->pi_state_cache;
825 WARN_ON(!pi_state);
826 current->pi_state_cache = NULL;
828 return pi_state;
832 * Drops a reference to the pi_state object and frees or caches it
833 * when the last reference is gone.
835 * Must be called with the hb lock held.
837 static void put_pi_state(struct futex_pi_state *pi_state)
839 if (!pi_state)
840 return;
842 if (!atomic_dec_and_test(&pi_state->refcount))
843 return;
846 * If pi_state->owner is NULL, the owner is most probably dying
847 * and has cleaned up the pi_state already
849 if (pi_state->owner) {
850 raw_spin_lock_irq(&pi_state->owner->pi_lock);
851 list_del_init(&pi_state->list);
852 raw_spin_unlock_irq(&pi_state->owner->pi_lock);
854 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
857 if (current->pi_state_cache)
858 kfree(pi_state);
859 else {
861 * pi_state->list is already empty.
862 * clear pi_state->owner.
863 * refcount is at 0 - put it back to 1.
865 pi_state->owner = NULL;
866 atomic_set(&pi_state->refcount, 1);
867 current->pi_state_cache = pi_state;
872 * Look up the task based on what TID userspace gave us.
873 * We dont trust it.
875 static struct task_struct * futex_find_get_task(pid_t pid)
877 struct task_struct *p;
879 rcu_read_lock();
880 p = find_task_by_vpid(pid);
881 if (p)
882 get_task_struct(p);
884 rcu_read_unlock();
886 return p;
890 * This task is holding PI mutexes at exit time => bad.
891 * Kernel cleans up PI-state, but userspace is likely hosed.
892 * (Robust-futex cleanup is separate and might save the day for userspace.)
894 void exit_pi_state_list(struct task_struct *curr)
896 struct list_head *next, *head = &curr->pi_state_list;
897 struct futex_pi_state *pi_state;
898 struct futex_hash_bucket *hb;
899 union futex_key key = FUTEX_KEY_INIT;
901 if (!futex_cmpxchg_enabled)
902 return;
904 * We are a ZOMBIE and nobody can enqueue itself on
905 * pi_state_list anymore, but we have to be careful
906 * versus waiters unqueueing themselves:
908 raw_spin_lock_irq(&curr->pi_lock);
909 while (!list_empty(head)) {
911 next = head->next;
912 pi_state = list_entry(next, struct futex_pi_state, list);
913 key = pi_state->key;
914 hb = hash_futex(&key);
915 raw_spin_unlock_irq(&curr->pi_lock);
917 spin_lock(&hb->lock);
919 raw_spin_lock_irq(&curr->pi_lock);
921 * We dropped the pi-lock, so re-check whether this
922 * task still owns the PI-state:
924 if (head->next != next) {
925 spin_unlock(&hb->lock);
926 continue;
929 WARN_ON(pi_state->owner != curr);
930 WARN_ON(list_empty(&pi_state->list));
931 list_del_init(&pi_state->list);
932 pi_state->owner = NULL;
933 raw_spin_unlock_irq(&curr->pi_lock);
935 rt_mutex_unlock(&pi_state->pi_mutex);
937 spin_unlock(&hb->lock);
939 raw_spin_lock_irq(&curr->pi_lock);
941 raw_spin_unlock_irq(&curr->pi_lock);
945 * We need to check the following states:
947 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
949 * [1] NULL | --- | --- | 0 | 0/1 | Valid
950 * [2] NULL | --- | --- | >0 | 0/1 | Valid
952 * [3] Found | NULL | -- | Any | 0/1 | Invalid
954 * [4] Found | Found | NULL | 0 | 1 | Valid
955 * [5] Found | Found | NULL | >0 | 1 | Invalid
957 * [6] Found | Found | task | 0 | 1 | Valid
959 * [7] Found | Found | NULL | Any | 0 | Invalid
961 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
962 * [9] Found | Found | task | 0 | 0 | Invalid
963 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
965 * [1] Indicates that the kernel can acquire the futex atomically. We
966 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
968 * [2] Valid, if TID does not belong to a kernel thread. If no matching
969 * thread is found then it indicates that the owner TID has died.
971 * [3] Invalid. The waiter is queued on a non PI futex
973 * [4] Valid state after exit_robust_list(), which sets the user space
974 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
976 * [5] The user space value got manipulated between exit_robust_list()
977 * and exit_pi_state_list()
979 * [6] Valid state after exit_pi_state_list() which sets the new owner in
980 * the pi_state but cannot access the user space value.
982 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
984 * [8] Owner and user space value match
986 * [9] There is no transient state which sets the user space TID to 0
987 * except exit_robust_list(), but this is indicated by the
988 * FUTEX_OWNER_DIED bit. See [4]
990 * [10] There is no transient state which leaves owner and user space
991 * TID out of sync.
995 * Validate that the existing waiter has a pi_state and sanity check
996 * the pi_state against the user space value. If correct, attach to
997 * it.
999 static int attach_to_pi_state(u32 uval, struct futex_pi_state *pi_state,
1000 struct futex_pi_state **ps)
1002 pid_t pid = uval & FUTEX_TID_MASK;
1005 * Userspace might have messed up non-PI and PI futexes [3]
1007 if (unlikely(!pi_state))
1008 return -EINVAL;
1010 WARN_ON(!atomic_read(&pi_state->refcount));
1013 * Handle the owner died case:
1015 if (uval & FUTEX_OWNER_DIED) {
1017 * exit_pi_state_list sets owner to NULL and wakes the
1018 * topmost waiter. The task which acquires the
1019 * pi_state->rt_mutex will fixup owner.
1021 if (!pi_state->owner) {
1023 * No pi state owner, but the user space TID
1024 * is not 0. Inconsistent state. [5]
1026 if (pid)
1027 return -EINVAL;
1029 * Take a ref on the state and return success. [4]
1031 goto out_state;
1035 * If TID is 0, then either the dying owner has not
1036 * yet executed exit_pi_state_list() or some waiter
1037 * acquired the rtmutex in the pi state, but did not
1038 * yet fixup the TID in user space.
1040 * Take a ref on the state and return success. [6]
1042 if (!pid)
1043 goto out_state;
1044 } else {
1046 * If the owner died bit is not set, then the pi_state
1047 * must have an owner. [7]
1049 if (!pi_state->owner)
1050 return -EINVAL;
1054 * Bail out if user space manipulated the futex value. If pi
1055 * state exists then the owner TID must be the same as the
1056 * user space TID. [9/10]
1058 if (pid != task_pid_vnr(pi_state->owner))
1059 return -EINVAL;
1060 out_state:
1061 atomic_inc(&pi_state->refcount);
1062 *ps = pi_state;
1063 return 0;
1067 * Lookup the task for the TID provided from user space and attach to
1068 * it after doing proper sanity checks.
1070 static int attach_to_pi_owner(u32 uval, union futex_key *key,
1071 struct futex_pi_state **ps)
1073 pid_t pid = uval & FUTEX_TID_MASK;
1074 struct futex_pi_state *pi_state;
1075 struct task_struct *p;
1078 * We are the first waiter - try to look up the real owner and attach
1079 * the new pi_state to it, but bail out when TID = 0 [1]
1081 if (!pid)
1082 return -ESRCH;
1083 p = futex_find_get_task(pid);
1084 if (!p)
1085 return -ESRCH;
1087 if (unlikely(p->flags & PF_KTHREAD)) {
1088 put_task_struct(p);
1089 return -EPERM;
1093 * We need to look at the task state flags to figure out,
1094 * whether the task is exiting. To protect against the do_exit
1095 * change of the task flags, we do this protected by
1096 * p->pi_lock:
1098 raw_spin_lock_irq(&p->pi_lock);
1099 if (unlikely(p->flags & PF_EXITING)) {
1101 * The task is on the way out. When PF_EXITPIDONE is
1102 * set, we know that the task has finished the
1103 * cleanup:
1105 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
1107 raw_spin_unlock_irq(&p->pi_lock);
1108 put_task_struct(p);
1109 return ret;
1113 * No existing pi state. First waiter. [2]
1115 pi_state = alloc_pi_state();
1118 * Initialize the pi_mutex in locked state and make @p
1119 * the owner of it:
1121 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1123 /* Store the key for possible exit cleanups: */
1124 pi_state->key = *key;
1126 WARN_ON(!list_empty(&pi_state->list));
1127 list_add(&pi_state->list, &p->pi_state_list);
1128 pi_state->owner = p;
1129 raw_spin_unlock_irq(&p->pi_lock);
1131 put_task_struct(p);
1133 *ps = pi_state;
1135 return 0;
1138 static int lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
1139 union futex_key *key, struct futex_pi_state **ps)
1141 struct futex_q *match = futex_top_waiter(hb, key);
1144 * If there is a waiter on that futex, validate it and
1145 * attach to the pi_state when the validation succeeds.
1147 if (match)
1148 return attach_to_pi_state(uval, match->pi_state, ps);
1151 * We are the first waiter - try to look up the owner based on
1152 * @uval and attach to it.
1154 return attach_to_pi_owner(uval, key, ps);
1157 static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1159 u32 uninitialized_var(curval);
1161 if (unlikely(should_fail_futex(true)))
1162 return -EFAULT;
1164 if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
1165 return -EFAULT;
1167 /*If user space value changed, let the caller retry */
1168 return curval != uval ? -EAGAIN : 0;
1172 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
1173 * @uaddr: the pi futex user address
1174 * @hb: the pi futex hash bucket
1175 * @key: the futex key associated with uaddr and hb
1176 * @ps: the pi_state pointer where we store the result of the
1177 * lookup
1178 * @task: the task to perform the atomic lock work for. This will
1179 * be "current" except in the case of requeue pi.
1180 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1182 * Return:
1183 * 0 - ready to wait;
1184 * 1 - acquired the lock;
1185 * <0 - error
1187 * The hb->lock and futex_key refs shall be held by the caller.
1189 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1190 union futex_key *key,
1191 struct futex_pi_state **ps,
1192 struct task_struct *task, int set_waiters)
1194 u32 uval, newval, vpid = task_pid_vnr(task);
1195 struct futex_q *match;
1196 int ret;
1199 * Read the user space value first so we can validate a few
1200 * things before proceeding further.
1202 if (get_futex_value_locked(&uval, uaddr))
1203 return -EFAULT;
1205 if (unlikely(should_fail_futex(true)))
1206 return -EFAULT;
1209 * Detect deadlocks.
1211 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1212 return -EDEADLK;
1214 if ((unlikely(should_fail_futex(true))))
1215 return -EDEADLK;
1218 * Lookup existing state first. If it exists, try to attach to
1219 * its pi_state.
1221 match = futex_top_waiter(hb, key);
1222 if (match)
1223 return attach_to_pi_state(uval, match->pi_state, ps);
1226 * No waiter and user TID is 0. We are here because the
1227 * waiters or the owner died bit is set or called from
1228 * requeue_cmp_pi or for whatever reason something took the
1229 * syscall.
1231 if (!(uval & FUTEX_TID_MASK)) {
1233 * We take over the futex. No other waiters and the user space
1234 * TID is 0. We preserve the owner died bit.
1236 newval = uval & FUTEX_OWNER_DIED;
1237 newval |= vpid;
1239 /* The futex requeue_pi code can enforce the waiters bit */
1240 if (set_waiters)
1241 newval |= FUTEX_WAITERS;
1243 ret = lock_pi_update_atomic(uaddr, uval, newval);
1244 /* If the take over worked, return 1 */
1245 return ret < 0 ? ret : 1;
1249 * First waiter. Set the waiters bit before attaching ourself to
1250 * the owner. If owner tries to unlock, it will be forced into
1251 * the kernel and blocked on hb->lock.
1253 newval = uval | FUTEX_WAITERS;
1254 ret = lock_pi_update_atomic(uaddr, uval, newval);
1255 if (ret)
1256 return ret;
1258 * If the update of the user space value succeeded, we try to
1259 * attach to the owner. If that fails, no harm done, we only
1260 * set the FUTEX_WAITERS bit in the user space variable.
1262 return attach_to_pi_owner(uval, key, ps);
1266 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1267 * @q: The futex_q to unqueue
1269 * The q->lock_ptr must not be NULL and must be held by the caller.
1271 static void __unqueue_futex(struct futex_q *q)
1273 struct futex_hash_bucket *hb;
1275 if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
1276 || WARN_ON(plist_node_empty(&q->list)))
1277 return;
1279 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1280 plist_del(&q->list, &hb->chain);
1281 hb_waiters_dec(hb);
1285 * The hash bucket lock must be held when this is called.
1286 * Afterwards, the futex_q must not be accessed. Callers
1287 * must ensure to later call wake_up_q() for the actual
1288 * wakeups to occur.
1290 static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
1292 struct task_struct *p = q->task;
1294 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1295 return;
1298 * Queue the task for later wakeup for after we've released
1299 * the hb->lock. wake_q_add() grabs reference to p.
1301 wake_q_add(wake_q, p);
1302 __unqueue_futex(q);
1304 * The waiting task can free the futex_q as soon as
1305 * q->lock_ptr = NULL is written, without taking any locks. A
1306 * memory barrier is required here to prevent the following
1307 * store to lock_ptr from getting ahead of the plist_del.
1309 smp_wmb();
1310 q->lock_ptr = NULL;
1313 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this,
1314 struct futex_hash_bucket *hb)
1316 struct task_struct *new_owner;
1317 struct futex_pi_state *pi_state = this->pi_state;
1318 u32 uninitialized_var(curval), newval;
1319 WAKE_Q(wake_q);
1320 bool deboost;
1321 int ret = 0;
1323 if (!pi_state)
1324 return -EINVAL;
1327 * If current does not own the pi_state then the futex is
1328 * inconsistent and user space fiddled with the futex value.
1330 if (pi_state->owner != current)
1331 return -EINVAL;
1333 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1334 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
1337 * It is possible that the next waiter (the one that brought
1338 * this owner to the kernel) timed out and is no longer
1339 * waiting on the lock.
1341 if (!new_owner)
1342 new_owner = this->task;
1345 * We pass it to the next owner. The WAITERS bit is always
1346 * kept enabled while there is PI state around. We cleanup the
1347 * owner died bit, because we are the owner.
1349 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
1351 if (unlikely(should_fail_futex(true)))
1352 ret = -EFAULT;
1354 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)) {
1355 ret = -EFAULT;
1356 } else if (curval != uval) {
1358 * If a unconditional UNLOCK_PI operation (user space did not
1359 * try the TID->0 transition) raced with a waiter setting the
1360 * FUTEX_WAITERS flag between get_user() and locking the hash
1361 * bucket lock, retry the operation.
1363 if ((FUTEX_TID_MASK & curval) == uval)
1364 ret = -EAGAIN;
1365 else
1366 ret = -EINVAL;
1368 if (ret) {
1369 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1370 return ret;
1373 raw_spin_lock(&pi_state->owner->pi_lock);
1374 WARN_ON(list_empty(&pi_state->list));
1375 list_del_init(&pi_state->list);
1376 raw_spin_unlock(&pi_state->owner->pi_lock);
1378 raw_spin_lock(&new_owner->pi_lock);
1379 WARN_ON(!list_empty(&pi_state->list));
1380 list_add(&pi_state->list, &new_owner->pi_state_list);
1381 pi_state->owner = new_owner;
1382 raw_spin_unlock(&new_owner->pi_lock);
1384 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1386 deboost = rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
1389 * First unlock HB so the waiter does not spin on it once he got woken
1390 * up. Second wake up the waiter before the priority is adjusted. If we
1391 * deboost first (and lose our higher priority), then the task might get
1392 * scheduled away before the wake up can take place.
1394 spin_unlock(&hb->lock);
1395 wake_up_q(&wake_q);
1396 if (deboost)
1397 rt_mutex_adjust_prio(current);
1399 return 0;
1403 * Express the locking dependencies for lockdep:
1405 static inline void
1406 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1408 if (hb1 <= hb2) {
1409 spin_lock(&hb1->lock);
1410 if (hb1 < hb2)
1411 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1412 } else { /* hb1 > hb2 */
1413 spin_lock(&hb2->lock);
1414 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1418 static inline void
1419 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1421 spin_unlock(&hb1->lock);
1422 if (hb1 != hb2)
1423 spin_unlock(&hb2->lock);
1427 * Wake up waiters matching bitset queued on this futex (uaddr).
1429 static int
1430 futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1432 struct futex_hash_bucket *hb;
1433 struct futex_q *this, *next;
1434 union futex_key key = FUTEX_KEY_INIT;
1435 int ret;
1436 WAKE_Q(wake_q);
1438 if (!bitset)
1439 return -EINVAL;
1441 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
1442 if (unlikely(ret != 0))
1443 goto out;
1445 hb = hash_futex(&key);
1447 /* Make sure we really have tasks to wakeup */
1448 if (!hb_waiters_pending(hb))
1449 goto out_put_key;
1451 spin_lock(&hb->lock);
1453 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1454 if (match_futex (&this->key, &key)) {
1455 if (this->pi_state || this->rt_waiter) {
1456 ret = -EINVAL;
1457 break;
1460 /* Check if one of the bits is set in both bitsets */
1461 if (!(this->bitset & bitset))
1462 continue;
1464 mark_wake_futex(&wake_q, this);
1465 if (++ret >= nr_wake)
1466 break;
1470 spin_unlock(&hb->lock);
1471 wake_up_q(&wake_q);
1472 out_put_key:
1473 put_futex_key(&key);
1474 out:
1475 return ret;
1478 static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1480 unsigned int op = (encoded_op & 0x70000000) >> 28;
1481 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
1482 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1483 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
1484 int oldval, ret;
1486 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
1487 if (oparg < 0 || oparg > 31) {
1488 char comm[sizeof(current->comm)];
1490 * kill this print and return -EINVAL when userspace
1491 * is sane again
1493 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1494 get_task_comm(comm, current), oparg);
1495 oparg &= 31;
1497 oparg = 1 << oparg;
1500 if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))
1501 return -EFAULT;
1503 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
1504 if (ret)
1505 return ret;
1507 switch (cmp) {
1508 case FUTEX_OP_CMP_EQ:
1509 return oldval == cmparg;
1510 case FUTEX_OP_CMP_NE:
1511 return oldval != cmparg;
1512 case FUTEX_OP_CMP_LT:
1513 return oldval < cmparg;
1514 case FUTEX_OP_CMP_GE:
1515 return oldval >= cmparg;
1516 case FUTEX_OP_CMP_LE:
1517 return oldval <= cmparg;
1518 case FUTEX_OP_CMP_GT:
1519 return oldval > cmparg;
1520 default:
1521 return -ENOSYS;
1526 * Wake up all waiters hashed on the physical page that is mapped
1527 * to this virtual address:
1529 static int
1530 futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
1531 int nr_wake, int nr_wake2, int op)
1533 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1534 struct futex_hash_bucket *hb1, *hb2;
1535 struct futex_q *this, *next;
1536 int ret, op_ret;
1537 WAKE_Q(wake_q);
1539 retry:
1540 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
1541 if (unlikely(ret != 0))
1542 goto out;
1543 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
1544 if (unlikely(ret != 0))
1545 goto out_put_key1;
1547 hb1 = hash_futex(&key1);
1548 hb2 = hash_futex(&key2);
1550 retry_private:
1551 double_lock_hb(hb1, hb2);
1552 op_ret = futex_atomic_op_inuser(op, uaddr2);
1553 if (unlikely(op_ret < 0)) {
1555 double_unlock_hb(hb1, hb2);
1557 #ifndef CONFIG_MMU
1559 * we don't get EFAULT from MMU faults if we don't have an MMU,
1560 * but we might get them from range checking
1562 ret = op_ret;
1563 goto out_put_keys;
1564 #endif
1566 if (unlikely(op_ret != -EFAULT)) {
1567 ret = op_ret;
1568 goto out_put_keys;
1571 ret = fault_in_user_writeable(uaddr2);
1572 if (ret)
1573 goto out_put_keys;
1575 if (!(flags & FLAGS_SHARED))
1576 goto retry_private;
1578 put_futex_key(&key2);
1579 put_futex_key(&key1);
1580 goto retry;
1583 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
1584 if (match_futex (&this->key, &key1)) {
1585 if (this->pi_state || this->rt_waiter) {
1586 ret = -EINVAL;
1587 goto out_unlock;
1589 mark_wake_futex(&wake_q, this);
1590 if (++ret >= nr_wake)
1591 break;
1595 if (op_ret > 0) {
1596 op_ret = 0;
1597 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
1598 if (match_futex (&this->key, &key2)) {
1599 if (this->pi_state || this->rt_waiter) {
1600 ret = -EINVAL;
1601 goto out_unlock;
1603 mark_wake_futex(&wake_q, this);
1604 if (++op_ret >= nr_wake2)
1605 break;
1608 ret += op_ret;
1611 out_unlock:
1612 double_unlock_hb(hb1, hb2);
1613 wake_up_q(&wake_q);
1614 out_put_keys:
1615 put_futex_key(&key2);
1616 out_put_key1:
1617 put_futex_key(&key1);
1618 out:
1619 return ret;
1623 * requeue_futex() - Requeue a futex_q from one hb to another
1624 * @q: the futex_q to requeue
1625 * @hb1: the source hash_bucket
1626 * @hb2: the target hash_bucket
1627 * @key2: the new key for the requeued futex_q
1629 static inline
1630 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1631 struct futex_hash_bucket *hb2, union futex_key *key2)
1635 * If key1 and key2 hash to the same bucket, no need to
1636 * requeue.
1638 if (likely(&hb1->chain != &hb2->chain)) {
1639 plist_del(&q->list, &hb1->chain);
1640 hb_waiters_dec(hb1);
1641 hb_waiters_inc(hb2);
1642 plist_add(&q->list, &hb2->chain);
1643 q->lock_ptr = &hb2->lock;
1645 get_futex_key_refs(key2);
1646 q->key = *key2;
1650 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1651 * @q: the futex_q
1652 * @key: the key of the requeue target futex
1653 * @hb: the hash_bucket of the requeue target futex
1655 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1656 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1657 * to the requeue target futex so the waiter can detect the wakeup on the right
1658 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1659 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1660 * to protect access to the pi_state to fixup the owner later. Must be called
1661 * with both q->lock_ptr and hb->lock held.
1663 static inline
1664 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1665 struct futex_hash_bucket *hb)
1667 get_futex_key_refs(key);
1668 q->key = *key;
1670 __unqueue_futex(q);
1672 WARN_ON(!q->rt_waiter);
1673 q->rt_waiter = NULL;
1675 q->lock_ptr = &hb->lock;
1677 wake_up_state(q->task, TASK_NORMAL);
1681 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1682 * @pifutex: the user address of the to futex
1683 * @hb1: the from futex hash bucket, must be locked by the caller
1684 * @hb2: the to futex hash bucket, must be locked by the caller
1685 * @key1: the from futex key
1686 * @key2: the to futex key
1687 * @ps: address to store the pi_state pointer
1688 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1690 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1691 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1692 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1693 * hb1 and hb2 must be held by the caller.
1695 * Return:
1696 * 0 - failed to acquire the lock atomically;
1697 * >0 - acquired the lock, return value is vpid of the top_waiter
1698 * <0 - error
1700 static int futex_proxy_trylock_atomic(u32 __user *pifutex,
1701 struct futex_hash_bucket *hb1,
1702 struct futex_hash_bucket *hb2,
1703 union futex_key *key1, union futex_key *key2,
1704 struct futex_pi_state **ps, int set_waiters)
1706 struct futex_q *top_waiter = NULL;
1707 u32 curval;
1708 int ret, vpid;
1710 if (get_futex_value_locked(&curval, pifutex))
1711 return -EFAULT;
1713 if (unlikely(should_fail_futex(true)))
1714 return -EFAULT;
1717 * Find the top_waiter and determine if there are additional waiters.
1718 * If the caller intends to requeue more than 1 waiter to pifutex,
1719 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1720 * as we have means to handle the possible fault. If not, don't set
1721 * the bit unecessarily as it will force the subsequent unlock to enter
1722 * the kernel.
1724 top_waiter = futex_top_waiter(hb1, key1);
1726 /* There are no waiters, nothing for us to do. */
1727 if (!top_waiter)
1728 return 0;
1730 /* Ensure we requeue to the expected futex. */
1731 if (!match_futex(top_waiter->requeue_pi_key, key2))
1732 return -EINVAL;
1735 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1736 * the contended case or if set_waiters is 1. The pi_state is returned
1737 * in ps in contended cases.
1739 vpid = task_pid_vnr(top_waiter->task);
1740 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1741 set_waiters);
1742 if (ret == 1) {
1743 requeue_pi_wake_futex(top_waiter, key2, hb2);
1744 return vpid;
1746 return ret;
1750 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1751 * @uaddr1: source futex user address
1752 * @flags: futex flags (FLAGS_SHARED, etc.)
1753 * @uaddr2: target futex user address
1754 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1755 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1756 * @cmpval: @uaddr1 expected value (or %NULL)
1757 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
1758 * pi futex (pi to pi requeue is not supported)
1760 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1761 * uaddr2 atomically on behalf of the top waiter.
1763 * Return:
1764 * >=0 - on success, the number of tasks requeued or woken;
1765 * <0 - on error
1767 static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
1768 u32 __user *uaddr2, int nr_wake, int nr_requeue,
1769 u32 *cmpval, int requeue_pi)
1771 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1772 int drop_count = 0, task_count = 0, ret;
1773 struct futex_pi_state *pi_state = NULL;
1774 struct futex_hash_bucket *hb1, *hb2;
1775 struct futex_q *this, *next;
1776 WAKE_Q(wake_q);
1778 if (nr_wake < 0 || nr_requeue < 0)
1779 return -EINVAL;
1781 if (requeue_pi) {
1783 * Requeue PI only works on two distinct uaddrs. This
1784 * check is only valid for private futexes. See below.
1786 if (uaddr1 == uaddr2)
1787 return -EINVAL;
1790 * requeue_pi requires a pi_state, try to allocate it now
1791 * without any locks in case it fails.
1793 if (refill_pi_state_cache())
1794 return -ENOMEM;
1796 * requeue_pi must wake as many tasks as it can, up to nr_wake
1797 * + nr_requeue, since it acquires the rt_mutex prior to
1798 * returning to userspace, so as to not leave the rt_mutex with
1799 * waiters and no owner. However, second and third wake-ups
1800 * cannot be predicted as they involve race conditions with the
1801 * first wake and a fault while looking up the pi_state. Both
1802 * pthread_cond_signal() and pthread_cond_broadcast() should
1803 * use nr_wake=1.
1805 if (nr_wake != 1)
1806 return -EINVAL;
1809 retry:
1810 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
1811 if (unlikely(ret != 0))
1812 goto out;
1813 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
1814 requeue_pi ? VERIFY_WRITE : VERIFY_READ);
1815 if (unlikely(ret != 0))
1816 goto out_put_key1;
1819 * The check above which compares uaddrs is not sufficient for
1820 * shared futexes. We need to compare the keys:
1822 if (requeue_pi && match_futex(&key1, &key2)) {
1823 ret = -EINVAL;
1824 goto out_put_keys;
1827 hb1 = hash_futex(&key1);
1828 hb2 = hash_futex(&key2);
1830 retry_private:
1831 hb_waiters_inc(hb2);
1832 double_lock_hb(hb1, hb2);
1834 if (likely(cmpval != NULL)) {
1835 u32 curval;
1837 ret = get_futex_value_locked(&curval, uaddr1);
1839 if (unlikely(ret)) {
1840 double_unlock_hb(hb1, hb2);
1841 hb_waiters_dec(hb2);
1843 ret = get_user(curval, uaddr1);
1844 if (ret)
1845 goto out_put_keys;
1847 if (!(flags & FLAGS_SHARED))
1848 goto retry_private;
1850 put_futex_key(&key2);
1851 put_futex_key(&key1);
1852 goto retry;
1854 if (curval != *cmpval) {
1855 ret = -EAGAIN;
1856 goto out_unlock;
1860 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
1862 * Attempt to acquire uaddr2 and wake the top waiter. If we
1863 * intend to requeue waiters, force setting the FUTEX_WAITERS
1864 * bit. We force this here where we are able to easily handle
1865 * faults rather in the requeue loop below.
1867 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
1868 &key2, &pi_state, nr_requeue);
1871 * At this point the top_waiter has either taken uaddr2 or is
1872 * waiting on it. If the former, then the pi_state will not
1873 * exist yet, look it up one more time to ensure we have a
1874 * reference to it. If the lock was taken, ret contains the
1875 * vpid of the top waiter task.
1876 * If the lock was not taken, we have pi_state and an initial
1877 * refcount on it. In case of an error we have nothing.
1879 if (ret > 0) {
1880 WARN_ON(pi_state);
1881 drop_count++;
1882 task_count++;
1884 * If we acquired the lock, then the user space value
1885 * of uaddr2 should be vpid. It cannot be changed by
1886 * the top waiter as it is blocked on hb2 lock if it
1887 * tries to do so. If something fiddled with it behind
1888 * our back the pi state lookup might unearth it. So
1889 * we rather use the known value than rereading and
1890 * handing potential crap to lookup_pi_state.
1892 * If that call succeeds then we have pi_state and an
1893 * initial refcount on it.
1895 ret = lookup_pi_state(ret, hb2, &key2, &pi_state);
1898 switch (ret) {
1899 case 0:
1900 /* We hold a reference on the pi state. */
1901 break;
1903 /* If the above failed, then pi_state is NULL */
1904 case -EFAULT:
1905 double_unlock_hb(hb1, hb2);
1906 hb_waiters_dec(hb2);
1907 put_futex_key(&key2);
1908 put_futex_key(&key1);
1909 ret = fault_in_user_writeable(uaddr2);
1910 if (!ret)
1911 goto retry;
1912 goto out;
1913 case -EAGAIN:
1915 * Two reasons for this:
1916 * - Owner is exiting and we just wait for the
1917 * exit to complete.
1918 * - The user space value changed.
1920 double_unlock_hb(hb1, hb2);
1921 hb_waiters_dec(hb2);
1922 put_futex_key(&key2);
1923 put_futex_key(&key1);
1924 cond_resched();
1925 goto retry;
1926 default:
1927 goto out_unlock;
1931 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
1932 if (task_count - nr_wake >= nr_requeue)
1933 break;
1935 if (!match_futex(&this->key, &key1))
1936 continue;
1939 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
1940 * be paired with each other and no other futex ops.
1942 * We should never be requeueing a futex_q with a pi_state,
1943 * which is awaiting a futex_unlock_pi().
1945 if ((requeue_pi && !this->rt_waiter) ||
1946 (!requeue_pi && this->rt_waiter) ||
1947 this->pi_state) {
1948 ret = -EINVAL;
1949 break;
1953 * Wake nr_wake waiters. For requeue_pi, if we acquired the
1954 * lock, we already woke the top_waiter. If not, it will be
1955 * woken by futex_unlock_pi().
1957 if (++task_count <= nr_wake && !requeue_pi) {
1958 mark_wake_futex(&wake_q, this);
1959 continue;
1962 /* Ensure we requeue to the expected futex for requeue_pi. */
1963 if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
1964 ret = -EINVAL;
1965 break;
1969 * Requeue nr_requeue waiters and possibly one more in the case
1970 * of requeue_pi if we couldn't acquire the lock atomically.
1972 if (requeue_pi) {
1974 * Prepare the waiter to take the rt_mutex. Take a
1975 * refcount on the pi_state and store the pointer in
1976 * the futex_q object of the waiter.
1978 atomic_inc(&pi_state->refcount);
1979 this->pi_state = pi_state;
1980 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
1981 this->rt_waiter,
1982 this->task);
1983 if (ret == 1) {
1985 * We got the lock. We do neither drop the
1986 * refcount on pi_state nor clear
1987 * this->pi_state because the waiter needs the
1988 * pi_state for cleaning up the user space
1989 * value. It will drop the refcount after
1990 * doing so.
1992 requeue_pi_wake_futex(this, &key2, hb2);
1993 drop_count++;
1994 continue;
1995 } else if (ret) {
1997 * rt_mutex_start_proxy_lock() detected a
1998 * potential deadlock when we tried to queue
1999 * that waiter. Drop the pi_state reference
2000 * which we took above and remove the pointer
2001 * to the state from the waiters futex_q
2002 * object.
2004 this->pi_state = NULL;
2005 put_pi_state(pi_state);
2007 * We stop queueing more waiters and let user
2008 * space deal with the mess.
2010 break;
2013 requeue_futex(this, hb1, hb2, &key2);
2014 drop_count++;
2018 * We took an extra initial reference to the pi_state either
2019 * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
2020 * need to drop it here again.
2022 put_pi_state(pi_state);
2024 out_unlock:
2025 double_unlock_hb(hb1, hb2);
2026 wake_up_q(&wake_q);
2027 hb_waiters_dec(hb2);
2030 * drop_futex_key_refs() must be called outside the spinlocks. During
2031 * the requeue we moved futex_q's from the hash bucket at key1 to the
2032 * one at key2 and updated their key pointer. We no longer need to
2033 * hold the references to key1.
2035 while (--drop_count >= 0)
2036 drop_futex_key_refs(&key1);
2038 out_put_keys:
2039 put_futex_key(&key2);
2040 out_put_key1:
2041 put_futex_key(&key1);
2042 out:
2043 return ret ? ret : task_count;
2046 /* The key must be already stored in q->key. */
2047 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
2048 __acquires(&hb->lock)
2050 struct futex_hash_bucket *hb;
2052 hb = hash_futex(&q->key);
2055 * Increment the counter before taking the lock so that
2056 * a potential waker won't miss a to-be-slept task that is
2057 * waiting for the spinlock. This is safe as all queue_lock()
2058 * users end up calling queue_me(). Similarly, for housekeeping,
2059 * decrement the counter at queue_unlock() when some error has
2060 * occurred and we don't end up adding the task to the list.
2062 hb_waiters_inc(hb);
2064 q->lock_ptr = &hb->lock;
2066 spin_lock(&hb->lock); /* implies smp_mb(); (A) */
2067 return hb;
2070 static inline void
2071 queue_unlock(struct futex_hash_bucket *hb)
2072 __releases(&hb->lock)
2074 spin_unlock(&hb->lock);
2075 hb_waiters_dec(hb);
2079 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2080 * @q: The futex_q to enqueue
2081 * @hb: The destination hash bucket
2083 * The hb->lock must be held by the caller, and is released here. A call to
2084 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2085 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2086 * or nothing if the unqueue is done as part of the wake process and the unqueue
2087 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2088 * an example).
2090 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2091 __releases(&hb->lock)
2093 int prio;
2096 * The priority used to register this element is
2097 * - either the real thread-priority for the real-time threads
2098 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2099 * - or MAX_RT_PRIO for non-RT threads.
2100 * Thus, all RT-threads are woken first in priority order, and
2101 * the others are woken last, in FIFO order.
2103 prio = min(current->normal_prio, MAX_RT_PRIO);
2105 plist_node_init(&q->list, prio);
2106 plist_add(&q->list, &hb->chain);
2107 q->task = current;
2108 spin_unlock(&hb->lock);
2112 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2113 * @q: The futex_q to unqueue
2115 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2116 * be paired with exactly one earlier call to queue_me().
2118 * Return:
2119 * 1 - if the futex_q was still queued (and we removed unqueued it);
2120 * 0 - if the futex_q was already removed by the waking thread
2122 static int unqueue_me(struct futex_q *q)
2124 spinlock_t *lock_ptr;
2125 int ret = 0;
2127 /* In the common case we don't take the spinlock, which is nice. */
2128 retry:
2130 * q->lock_ptr can change between this read and the following spin_lock.
2131 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2132 * optimizing lock_ptr out of the logic below.
2134 lock_ptr = READ_ONCE(q->lock_ptr);
2135 if (lock_ptr != NULL) {
2136 spin_lock(lock_ptr);
2138 * q->lock_ptr can change between reading it and
2139 * spin_lock(), causing us to take the wrong lock. This
2140 * corrects the race condition.
2142 * Reasoning goes like this: if we have the wrong lock,
2143 * q->lock_ptr must have changed (maybe several times)
2144 * between reading it and the spin_lock(). It can
2145 * change again after the spin_lock() but only if it was
2146 * already changed before the spin_lock(). It cannot,
2147 * however, change back to the original value. Therefore
2148 * we can detect whether we acquired the correct lock.
2150 if (unlikely(lock_ptr != q->lock_ptr)) {
2151 spin_unlock(lock_ptr);
2152 goto retry;
2154 __unqueue_futex(q);
2156 BUG_ON(q->pi_state);
2158 spin_unlock(lock_ptr);
2159 ret = 1;
2162 drop_futex_key_refs(&q->key);
2163 return ret;
2167 * PI futexes can not be requeued and must remove themself from the
2168 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
2169 * and dropped here.
2171 static void unqueue_me_pi(struct futex_q *q)
2172 __releases(q->lock_ptr)
2174 __unqueue_futex(q);
2176 BUG_ON(!q->pi_state);
2177 put_pi_state(q->pi_state);
2178 q->pi_state = NULL;
2180 spin_unlock(q->lock_ptr);
2184 * Fixup the pi_state owner with the new owner.
2186 * Must be called with hash bucket lock held and mm->sem held for non
2187 * private futexes.
2189 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2190 struct task_struct *newowner)
2192 u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
2193 struct futex_pi_state *pi_state = q->pi_state;
2194 struct task_struct *oldowner = pi_state->owner;
2195 u32 uval, uninitialized_var(curval), newval;
2196 int ret;
2198 /* Owner died? */
2199 if (!pi_state->owner)
2200 newtid |= FUTEX_OWNER_DIED;
2203 * We are here either because we stole the rtmutex from the
2204 * previous highest priority waiter or we are the highest priority
2205 * waiter but failed to get the rtmutex the first time.
2206 * We have to replace the newowner TID in the user space variable.
2207 * This must be atomic as we have to preserve the owner died bit here.
2209 * Note: We write the user space value _before_ changing the pi_state
2210 * because we can fault here. Imagine swapped out pages or a fork
2211 * that marked all the anonymous memory readonly for cow.
2213 * Modifying pi_state _before_ the user space value would
2214 * leave the pi_state in an inconsistent state when we fault
2215 * here, because we need to drop the hash bucket lock to
2216 * handle the fault. This might be observed in the PID check
2217 * in lookup_pi_state.
2219 retry:
2220 if (get_futex_value_locked(&uval, uaddr))
2221 goto handle_fault;
2223 while (1) {
2224 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2226 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
2227 goto handle_fault;
2228 if (curval == uval)
2229 break;
2230 uval = curval;
2234 * We fixed up user space. Now we need to fix the pi_state
2235 * itself.
2237 if (pi_state->owner != NULL) {
2238 raw_spin_lock_irq(&pi_state->owner->pi_lock);
2239 WARN_ON(list_empty(&pi_state->list));
2240 list_del_init(&pi_state->list);
2241 raw_spin_unlock_irq(&pi_state->owner->pi_lock);
2244 pi_state->owner = newowner;
2246 raw_spin_lock_irq(&newowner->pi_lock);
2247 WARN_ON(!list_empty(&pi_state->list));
2248 list_add(&pi_state->list, &newowner->pi_state_list);
2249 raw_spin_unlock_irq(&newowner->pi_lock);
2250 return 0;
2253 * To handle the page fault we need to drop the hash bucket
2254 * lock here. That gives the other task (either the highest priority
2255 * waiter itself or the task which stole the rtmutex) the
2256 * chance to try the fixup of the pi_state. So once we are
2257 * back from handling the fault we need to check the pi_state
2258 * after reacquiring the hash bucket lock and before trying to
2259 * do another fixup. When the fixup has been done already we
2260 * simply return.
2262 handle_fault:
2263 spin_unlock(q->lock_ptr);
2265 ret = fault_in_user_writeable(uaddr);
2267 spin_lock(q->lock_ptr);
2270 * Check if someone else fixed it for us:
2272 if (pi_state->owner != oldowner)
2273 return 0;
2275 if (ret)
2276 return ret;
2278 goto retry;
2281 static long futex_wait_restart(struct restart_block *restart);
2284 * fixup_owner() - Post lock pi_state and corner case management
2285 * @uaddr: user address of the futex
2286 * @q: futex_q (contains pi_state and access to the rt_mutex)
2287 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2289 * After attempting to lock an rt_mutex, this function is called to cleanup
2290 * the pi_state owner as well as handle race conditions that may allow us to
2291 * acquire the lock. Must be called with the hb lock held.
2293 * Return:
2294 * 1 - success, lock taken;
2295 * 0 - success, lock not taken;
2296 * <0 - on error (-EFAULT)
2298 static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
2300 struct task_struct *owner;
2301 int ret = 0;
2303 if (locked) {
2305 * Got the lock. We might not be the anticipated owner if we
2306 * did a lock-steal - fix up the PI-state in that case:
2308 if (q->pi_state->owner != current)
2309 ret = fixup_pi_state_owner(uaddr, q, current);
2310 goto out;
2314 * Catch the rare case, where the lock was released when we were on the
2315 * way back before we locked the hash bucket.
2317 if (q->pi_state->owner == current) {
2319 * Try to get the rt_mutex now. This might fail as some other
2320 * task acquired the rt_mutex after we removed ourself from the
2321 * rt_mutex waiters list.
2323 if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
2324 locked = 1;
2325 goto out;
2329 * pi_state is incorrect, some other task did a lock steal and
2330 * we returned due to timeout or signal without taking the
2331 * rt_mutex. Too late.
2333 raw_spin_lock_irq(&q->pi_state->pi_mutex.wait_lock);
2334 owner = rt_mutex_owner(&q->pi_state->pi_mutex);
2335 if (!owner)
2336 owner = rt_mutex_next_owner(&q->pi_state->pi_mutex);
2337 raw_spin_unlock_irq(&q->pi_state->pi_mutex.wait_lock);
2338 ret = fixup_pi_state_owner(uaddr, q, owner);
2339 goto out;
2343 * Paranoia check. If we did not take the lock, then we should not be
2344 * the owner of the rt_mutex.
2346 if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
2347 printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
2348 "pi-state %p\n", ret,
2349 q->pi_state->pi_mutex.owner,
2350 q->pi_state->owner);
2352 out:
2353 return ret ? ret : locked;
2357 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2358 * @hb: the futex hash bucket, must be locked by the caller
2359 * @q: the futex_q to queue up on
2360 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
2362 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
2363 struct hrtimer_sleeper *timeout)
2366 * The task state is guaranteed to be set before another task can
2367 * wake it. set_current_state() is implemented using smp_store_mb() and
2368 * queue_me() calls spin_unlock() upon completion, both serializing
2369 * access to the hash list and forcing another memory barrier.
2371 set_current_state(TASK_INTERRUPTIBLE);
2372 queue_me(q, hb);
2374 /* Arm the timer */
2375 if (timeout)
2376 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
2379 * If we have been removed from the hash list, then another task
2380 * has tried to wake us, and we can skip the call to schedule().
2382 if (likely(!plist_node_empty(&q->list))) {
2384 * If the timer has already expired, current will already be
2385 * flagged for rescheduling. Only call schedule if there
2386 * is no timeout, or if it has yet to expire.
2388 if (!timeout || timeout->task)
2389 freezable_schedule();
2391 __set_current_state(TASK_RUNNING);
2395 * futex_wait_setup() - Prepare to wait on a futex
2396 * @uaddr: the futex userspace address
2397 * @val: the expected value
2398 * @flags: futex flags (FLAGS_SHARED, etc.)
2399 * @q: the associated futex_q
2400 * @hb: storage for hash_bucket pointer to be returned to caller
2402 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2403 * compare it with the expected value. Handle atomic faults internally.
2404 * Return with the hb lock held and a q.key reference on success, and unlocked
2405 * with no q.key reference on failure.
2407 * Return:
2408 * 0 - uaddr contains val and hb has been locked;
2409 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
2411 static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
2412 struct futex_q *q, struct futex_hash_bucket **hb)
2414 u32 uval;
2415 int ret;
2418 * Access the page AFTER the hash-bucket is locked.
2419 * Order is important:
2421 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2422 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2424 * The basic logical guarantee of a futex is that it blocks ONLY
2425 * if cond(var) is known to be true at the time of blocking, for
2426 * any cond. If we locked the hash-bucket after testing *uaddr, that
2427 * would open a race condition where we could block indefinitely with
2428 * cond(var) false, which would violate the guarantee.
2430 * On the other hand, we insert q and release the hash-bucket only
2431 * after testing *uaddr. This guarantees that futex_wait() will NOT
2432 * absorb a wakeup if *uaddr does not match the desired values
2433 * while the syscall executes.
2435 retry:
2436 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
2437 if (unlikely(ret != 0))
2438 return ret;
2440 retry_private:
2441 *hb = queue_lock(q);
2443 ret = get_futex_value_locked(&uval, uaddr);
2445 if (ret) {
2446 queue_unlock(*hb);
2448 ret = get_user(uval, uaddr);
2449 if (ret)
2450 goto out;
2452 if (!(flags & FLAGS_SHARED))
2453 goto retry_private;
2455 put_futex_key(&q->key);
2456 goto retry;
2459 if (uval != val) {
2460 queue_unlock(*hb);
2461 ret = -EWOULDBLOCK;
2464 out:
2465 if (ret)
2466 put_futex_key(&q->key);
2467 return ret;
2470 static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2471 ktime_t *abs_time, u32 bitset)
2473 struct hrtimer_sleeper timeout, *to = NULL;
2474 struct restart_block *restart;
2475 struct futex_hash_bucket *hb;
2476 struct futex_q q = futex_q_init;
2477 int ret;
2479 if (!bitset)
2480 return -EINVAL;
2481 q.bitset = bitset;
2483 if (abs_time) {
2484 to = &timeout;
2486 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2487 CLOCK_REALTIME : CLOCK_MONOTONIC,
2488 HRTIMER_MODE_ABS);
2489 hrtimer_init_sleeper(to, current);
2490 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2491 current->timer_slack_ns);
2494 retry:
2496 * Prepare to wait on uaddr. On success, holds hb lock and increments
2497 * q.key refs.
2499 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
2500 if (ret)
2501 goto out;
2503 /* queue_me and wait for wakeup, timeout, or a signal. */
2504 futex_wait_queue_me(hb, &q, to);
2506 /* If we were woken (and unqueued), we succeeded, whatever. */
2507 ret = 0;
2508 /* unqueue_me() drops q.key ref */
2509 if (!unqueue_me(&q))
2510 goto out;
2511 ret = -ETIMEDOUT;
2512 if (to && !to->task)
2513 goto out;
2516 * We expect signal_pending(current), but we might be the
2517 * victim of a spurious wakeup as well.
2519 if (!signal_pending(current))
2520 goto retry;
2522 ret = -ERESTARTSYS;
2523 if (!abs_time)
2524 goto out;
2526 restart = &current->restart_block;
2527 restart->fn = futex_wait_restart;
2528 restart->futex.uaddr = uaddr;
2529 restart->futex.val = val;
2530 restart->futex.time = abs_time->tv64;
2531 restart->futex.bitset = bitset;
2532 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
2534 ret = -ERESTART_RESTARTBLOCK;
2536 out:
2537 if (to) {
2538 hrtimer_cancel(&to->timer);
2539 destroy_hrtimer_on_stack(&to->timer);
2541 return ret;
2545 static long futex_wait_restart(struct restart_block *restart)
2547 u32 __user *uaddr = restart->futex.uaddr;
2548 ktime_t t, *tp = NULL;
2550 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2551 t.tv64 = restart->futex.time;
2552 tp = &t;
2554 restart->fn = do_no_restart_syscall;
2556 return (long)futex_wait(uaddr, restart->futex.flags,
2557 restart->futex.val, tp, restart->futex.bitset);
2562 * Userspace tried a 0 -> TID atomic transition of the futex value
2563 * and failed. The kernel side here does the whole locking operation:
2564 * if there are waiters then it will block as a consequence of relying
2565 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2566 * a 0 value of the futex too.).
2568 * Also serves as futex trylock_pi()'ing, and due semantics.
2570 static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
2571 ktime_t *time, int trylock)
2573 struct hrtimer_sleeper timeout, *to = NULL;
2574 struct futex_hash_bucket *hb;
2575 struct futex_q q = futex_q_init;
2576 int res, ret;
2578 if (refill_pi_state_cache())
2579 return -ENOMEM;
2581 if (time) {
2582 to = &timeout;
2583 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
2584 HRTIMER_MODE_ABS);
2585 hrtimer_init_sleeper(to, current);
2586 hrtimer_set_expires(&to->timer, *time);
2589 retry:
2590 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
2591 if (unlikely(ret != 0))
2592 goto out;
2594 retry_private:
2595 hb = queue_lock(&q);
2597 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
2598 if (unlikely(ret)) {
2600 * Atomic work succeeded and we got the lock,
2601 * or failed. Either way, we do _not_ block.
2603 switch (ret) {
2604 case 1:
2605 /* We got the lock. */
2606 ret = 0;
2607 goto out_unlock_put_key;
2608 case -EFAULT:
2609 goto uaddr_faulted;
2610 case -EAGAIN:
2612 * Two reasons for this:
2613 * - Task is exiting and we just wait for the
2614 * exit to complete.
2615 * - The user space value changed.
2617 queue_unlock(hb);
2618 put_futex_key(&q.key);
2619 cond_resched();
2620 goto retry;
2621 default:
2622 goto out_unlock_put_key;
2627 * Only actually queue now that the atomic ops are done:
2629 queue_me(&q, hb);
2631 WARN_ON(!q.pi_state);
2633 * Block on the PI mutex:
2635 if (!trylock) {
2636 ret = rt_mutex_timed_futex_lock(&q.pi_state->pi_mutex, to);
2637 } else {
2638 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
2639 /* Fixup the trylock return value: */
2640 ret = ret ? 0 : -EWOULDBLOCK;
2643 spin_lock(q.lock_ptr);
2645 * Fixup the pi_state owner and possibly acquire the lock if we
2646 * haven't already.
2648 res = fixup_owner(uaddr, &q, !ret);
2650 * If fixup_owner() returned an error, proprogate that. If it acquired
2651 * the lock, clear our -ETIMEDOUT or -EINTR.
2653 if (res)
2654 ret = (res < 0) ? res : 0;
2657 * If fixup_owner() faulted and was unable to handle the fault, unlock
2658 * it and return the fault to userspace.
2660 if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
2661 rt_mutex_unlock(&q.pi_state->pi_mutex);
2663 /* Unqueue and drop the lock */
2664 unqueue_me_pi(&q);
2666 goto out_put_key;
2668 out_unlock_put_key:
2669 queue_unlock(hb);
2671 out_put_key:
2672 put_futex_key(&q.key);
2673 out:
2674 if (to)
2675 destroy_hrtimer_on_stack(&to->timer);
2676 return ret != -EINTR ? ret : -ERESTARTNOINTR;
2678 uaddr_faulted:
2679 queue_unlock(hb);
2681 ret = fault_in_user_writeable(uaddr);
2682 if (ret)
2683 goto out_put_key;
2685 if (!(flags & FLAGS_SHARED))
2686 goto retry_private;
2688 put_futex_key(&q.key);
2689 goto retry;
2693 * Userspace attempted a TID -> 0 atomic transition, and failed.
2694 * This is the in-kernel slowpath: we look up the PI state (if any),
2695 * and do the rt-mutex unlock.
2697 static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
2699 u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
2700 union futex_key key = FUTEX_KEY_INIT;
2701 struct futex_hash_bucket *hb;
2702 struct futex_q *match;
2703 int ret;
2705 retry:
2706 if (get_user(uval, uaddr))
2707 return -EFAULT;
2709 * We release only a lock we actually own:
2711 if ((uval & FUTEX_TID_MASK) != vpid)
2712 return -EPERM;
2714 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
2715 if (ret)
2716 return ret;
2718 hb = hash_futex(&key);
2719 spin_lock(&hb->lock);
2722 * Check waiters first. We do not trust user space values at
2723 * all and we at least want to know if user space fiddled
2724 * with the futex value instead of blindly unlocking.
2726 match = futex_top_waiter(hb, &key);
2727 if (match) {
2728 ret = wake_futex_pi(uaddr, uval, match, hb);
2730 * In case of success wake_futex_pi dropped the hash
2731 * bucket lock.
2733 if (!ret)
2734 goto out_putkey;
2736 * The atomic access to the futex value generated a
2737 * pagefault, so retry the user-access and the wakeup:
2739 if (ret == -EFAULT)
2740 goto pi_faulted;
2742 * A unconditional UNLOCK_PI op raced against a waiter
2743 * setting the FUTEX_WAITERS bit. Try again.
2745 if (ret == -EAGAIN) {
2746 spin_unlock(&hb->lock);
2747 put_futex_key(&key);
2748 goto retry;
2751 * wake_futex_pi has detected invalid state. Tell user
2752 * space.
2754 goto out_unlock;
2758 * We have no kernel internal state, i.e. no waiters in the
2759 * kernel. Waiters which are about to queue themselves are stuck
2760 * on hb->lock. So we can safely ignore them. We do neither
2761 * preserve the WAITERS bit not the OWNER_DIED one. We are the
2762 * owner.
2764 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))
2765 goto pi_faulted;
2768 * If uval has changed, let user space handle it.
2770 ret = (curval == uval) ? 0 : -EAGAIN;
2772 out_unlock:
2773 spin_unlock(&hb->lock);
2774 out_putkey:
2775 put_futex_key(&key);
2776 return ret;
2778 pi_faulted:
2779 spin_unlock(&hb->lock);
2780 put_futex_key(&key);
2782 ret = fault_in_user_writeable(uaddr);
2783 if (!ret)
2784 goto retry;
2786 return ret;
2790 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
2791 * @hb: the hash_bucket futex_q was original enqueued on
2792 * @q: the futex_q woken while waiting to be requeued
2793 * @key2: the futex_key of the requeue target futex
2794 * @timeout: the timeout associated with the wait (NULL if none)
2796 * Detect if the task was woken on the initial futex as opposed to the requeue
2797 * target futex. If so, determine if it was a timeout or a signal that caused
2798 * the wakeup and return the appropriate error code to the caller. Must be
2799 * called with the hb lock held.
2801 * Return:
2802 * 0 = no early wakeup detected;
2803 * <0 = -ETIMEDOUT or -ERESTARTNOINTR
2805 static inline
2806 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
2807 struct futex_q *q, union futex_key *key2,
2808 struct hrtimer_sleeper *timeout)
2810 int ret = 0;
2813 * With the hb lock held, we avoid races while we process the wakeup.
2814 * We only need to hold hb (and not hb2) to ensure atomicity as the
2815 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
2816 * It can't be requeued from uaddr2 to something else since we don't
2817 * support a PI aware source futex for requeue.
2819 if (!match_futex(&q->key, key2)) {
2820 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
2822 * We were woken prior to requeue by a timeout or a signal.
2823 * Unqueue the futex_q and determine which it was.
2825 plist_del(&q->list, &hb->chain);
2826 hb_waiters_dec(hb);
2828 /* Handle spurious wakeups gracefully */
2829 ret = -EWOULDBLOCK;
2830 if (timeout && !timeout->task)
2831 ret = -ETIMEDOUT;
2832 else if (signal_pending(current))
2833 ret = -ERESTARTNOINTR;
2835 return ret;
2839 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
2840 * @uaddr: the futex we initially wait on (non-pi)
2841 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
2842 * the same type, no requeueing from private to shared, etc.
2843 * @val: the expected value of uaddr
2844 * @abs_time: absolute timeout
2845 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
2846 * @uaddr2: the pi futex we will take prior to returning to user-space
2848 * The caller will wait on uaddr and will be requeued by futex_requeue() to
2849 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
2850 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
2851 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
2852 * without one, the pi logic would not know which task to boost/deboost, if
2853 * there was a need to.
2855 * We call schedule in futex_wait_queue_me() when we enqueue and return there
2856 * via the following--
2857 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
2858 * 2) wakeup on uaddr2 after a requeue
2859 * 3) signal
2860 * 4) timeout
2862 * If 3, cleanup and return -ERESTARTNOINTR.
2864 * If 2, we may then block on trying to take the rt_mutex and return via:
2865 * 5) successful lock
2866 * 6) signal
2867 * 7) timeout
2868 * 8) other lock acquisition failure
2870 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
2872 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
2874 * Return:
2875 * 0 - On success;
2876 * <0 - On error
2878 static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
2879 u32 val, ktime_t *abs_time, u32 bitset,
2880 u32 __user *uaddr2)
2882 struct hrtimer_sleeper timeout, *to = NULL;
2883 struct rt_mutex_waiter rt_waiter;
2884 struct futex_hash_bucket *hb;
2885 union futex_key key2 = FUTEX_KEY_INIT;
2886 struct futex_q q = futex_q_init;
2887 int res, ret;
2889 if (uaddr == uaddr2)
2890 return -EINVAL;
2892 if (!bitset)
2893 return -EINVAL;
2895 if (abs_time) {
2896 to = &timeout;
2897 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2898 CLOCK_REALTIME : CLOCK_MONOTONIC,
2899 HRTIMER_MODE_ABS);
2900 hrtimer_init_sleeper(to, current);
2901 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2902 current->timer_slack_ns);
2906 * The waiter is allocated on our stack, manipulated by the requeue
2907 * code while we sleep on uaddr.
2909 debug_rt_mutex_init_waiter(&rt_waiter);
2910 RB_CLEAR_NODE(&rt_waiter.pi_tree_entry);
2911 RB_CLEAR_NODE(&rt_waiter.tree_entry);
2912 rt_waiter.task = NULL;
2914 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
2915 if (unlikely(ret != 0))
2916 goto out;
2918 q.bitset = bitset;
2919 q.rt_waiter = &rt_waiter;
2920 q.requeue_pi_key = &key2;
2923 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
2924 * count.
2926 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
2927 if (ret)
2928 goto out_key2;
2931 * The check above which compares uaddrs is not sufficient for
2932 * shared futexes. We need to compare the keys:
2934 if (match_futex(&q.key, &key2)) {
2935 queue_unlock(hb);
2936 ret = -EINVAL;
2937 goto out_put_keys;
2940 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
2941 futex_wait_queue_me(hb, &q, to);
2943 spin_lock(&hb->lock);
2944 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
2945 spin_unlock(&hb->lock);
2946 if (ret)
2947 goto out_put_keys;
2950 * In order for us to be here, we know our q.key == key2, and since
2951 * we took the hb->lock above, we also know that futex_requeue() has
2952 * completed and we no longer have to concern ourselves with a wakeup
2953 * race with the atomic proxy lock acquisition by the requeue code. The
2954 * futex_requeue dropped our key1 reference and incremented our key2
2955 * reference count.
2958 /* Check if the requeue code acquired the second futex for us. */
2959 if (!q.rt_waiter) {
2961 * Got the lock. We might not be the anticipated owner if we
2962 * did a lock-steal - fix up the PI-state in that case.
2964 if (q.pi_state && (q.pi_state->owner != current)) {
2965 spin_lock(q.lock_ptr);
2966 ret = fixup_pi_state_owner(uaddr2, &q, current);
2967 if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current)
2968 rt_mutex_unlock(&q.pi_state->pi_mutex);
2970 * Drop the reference to the pi state which
2971 * the requeue_pi() code acquired for us.
2973 put_pi_state(q.pi_state);
2974 spin_unlock(q.lock_ptr);
2976 } else {
2977 struct rt_mutex *pi_mutex;
2980 * We have been woken up by futex_unlock_pi(), a timeout, or a
2981 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
2982 * the pi_state.
2984 WARN_ON(!q.pi_state);
2985 pi_mutex = &q.pi_state->pi_mutex;
2986 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
2988 spin_lock(q.lock_ptr);
2989 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
2990 ret = 0;
2992 debug_rt_mutex_free_waiter(&rt_waiter);
2994 * Fixup the pi_state owner and possibly acquire the lock if we
2995 * haven't already.
2997 res = fixup_owner(uaddr2, &q, !ret);
2999 * If fixup_owner() returned an error, proprogate that. If it
3000 * acquired the lock, clear -ETIMEDOUT or -EINTR.
3002 if (res)
3003 ret = (res < 0) ? res : 0;
3006 * If fixup_pi_state_owner() faulted and was unable to handle
3007 * the fault, unlock the rt_mutex and return the fault to
3008 * userspace.
3010 if (ret && rt_mutex_owner(pi_mutex) == current)
3011 rt_mutex_unlock(pi_mutex);
3013 /* Unqueue and drop the lock. */
3014 unqueue_me_pi(&q);
3017 if (ret == -EINTR) {
3019 * We've already been requeued, but cannot restart by calling
3020 * futex_lock_pi() directly. We could restart this syscall, but
3021 * it would detect that the user space "val" changed and return
3022 * -EWOULDBLOCK. Save the overhead of the restart and return
3023 * -EWOULDBLOCK directly.
3025 ret = -EWOULDBLOCK;
3028 out_put_keys:
3029 put_futex_key(&q.key);
3030 out_key2:
3031 put_futex_key(&key2);
3033 out:
3034 if (to) {
3035 hrtimer_cancel(&to->timer);
3036 destroy_hrtimer_on_stack(&to->timer);
3038 return ret;
3042 * Support for robust futexes: the kernel cleans up held futexes at
3043 * thread exit time.
3045 * Implementation: user-space maintains a per-thread list of locks it
3046 * is holding. Upon do_exit(), the kernel carefully walks this list,
3047 * and marks all locks that are owned by this thread with the
3048 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
3049 * always manipulated with the lock held, so the list is private and
3050 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
3051 * field, to allow the kernel to clean up if the thread dies after
3052 * acquiring the lock, but just before it could have added itself to
3053 * the list. There can only be one such pending lock.
3057 * sys_set_robust_list() - Set the robust-futex list head of a task
3058 * @head: pointer to the list-head
3059 * @len: length of the list-head, as userspace expects
3061 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
3062 size_t, len)
3064 if (!futex_cmpxchg_enabled)
3065 return -ENOSYS;
3067 * The kernel knows only one size for now:
3069 if (unlikely(len != sizeof(*head)))
3070 return -EINVAL;
3072 current->robust_list = head;
3074 return 0;
3078 * sys_get_robust_list() - Get the robust-futex list head of a task
3079 * @pid: pid of the process [zero for current task]
3080 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
3081 * @len_ptr: pointer to a length field, the kernel fills in the header size
3083 SYSCALL_DEFINE3(get_robust_list, int, pid,
3084 struct robust_list_head __user * __user *, head_ptr,
3085 size_t __user *, len_ptr)
3087 struct robust_list_head __user *head;
3088 unsigned long ret;
3089 struct task_struct *p;
3091 if (!futex_cmpxchg_enabled)
3092 return -ENOSYS;
3094 rcu_read_lock();
3096 ret = -ESRCH;
3097 if (!pid)
3098 p = current;
3099 else {
3100 p = find_task_by_vpid(pid);
3101 if (!p)
3102 goto err_unlock;
3105 ret = -EPERM;
3106 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3107 goto err_unlock;
3109 head = p->robust_list;
3110 rcu_read_unlock();
3112 if (put_user(sizeof(*head), len_ptr))
3113 return -EFAULT;
3114 return put_user(head, head_ptr);
3116 err_unlock:
3117 rcu_read_unlock();
3119 return ret;
3123 * Process a futex-list entry, check whether it's owned by the
3124 * dying task, and do notification if so:
3126 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
3128 u32 uval, uninitialized_var(nval), mval;
3130 /* Futex address must be 32bit aligned */
3131 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3132 return -1;
3134 retry:
3135 if (get_user(uval, uaddr))
3136 return -1;
3138 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
3140 * Ok, this dying thread is truly holding a futex
3141 * of interest. Set the OWNER_DIED bit atomically
3142 * via cmpxchg, and if the value had FUTEX_WAITERS
3143 * set, wake up a waiter (if any). (We have to do a
3144 * futex_wake() even if OWNER_DIED is already set -
3145 * to handle the rare but possible case of recursive
3146 * thread-death.) The rest of the cleanup is done in
3147 * userspace.
3149 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3151 * We are not holding a lock here, but we want to have
3152 * the pagefault_disable/enable() protection because
3153 * we want to handle the fault gracefully. If the
3154 * access fails we try to fault in the futex with R/W
3155 * verification via get_user_pages. get_user() above
3156 * does not guarantee R/W access. If that fails we
3157 * give up and leave the futex locked.
3159 if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
3160 if (fault_in_user_writeable(uaddr))
3161 return -1;
3162 goto retry;
3164 if (nval != uval)
3165 goto retry;
3168 * Wake robust non-PI futexes here. The wakeup of
3169 * PI futexes happens in exit_pi_state():
3171 if (!pi && (uval & FUTEX_WAITERS))
3172 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3174 return 0;
3178 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3180 static inline int fetch_robust_entry(struct robust_list __user **entry,
3181 struct robust_list __user * __user *head,
3182 unsigned int *pi)
3184 unsigned long uentry;
3186 if (get_user(uentry, (unsigned long __user *)head))
3187 return -EFAULT;
3189 *entry = (void __user *)(uentry & ~1UL);
3190 *pi = uentry & 1;
3192 return 0;
3196 * Walk curr->robust_list (very carefully, it's a userspace list!)
3197 * and mark any locks found there dead, and notify any waiters.
3199 * We silently return on any sign of list-walking problem.
3201 void exit_robust_list(struct task_struct *curr)
3203 struct robust_list_head __user *head = curr->robust_list;
3204 struct robust_list __user *entry, *next_entry, *pending;
3205 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3206 unsigned int uninitialized_var(next_pi);
3207 unsigned long futex_offset;
3208 int rc;
3210 if (!futex_cmpxchg_enabled)
3211 return;
3214 * Fetch the list head (which was registered earlier, via
3215 * sys_set_robust_list()):
3217 if (fetch_robust_entry(&entry, &head->list.next, &pi))
3218 return;
3220 * Fetch the relative futex offset:
3222 if (get_user(futex_offset, &head->futex_offset))
3223 return;
3225 * Fetch any possibly pending lock-add first, and handle it
3226 * if it exists:
3228 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
3229 return;
3231 next_entry = NULL; /* avoid warning with gcc */
3232 while (entry != &head->list) {
3234 * Fetch the next entry in the list before calling
3235 * handle_futex_death:
3237 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
3239 * A pending lock might already be on the list, so
3240 * don't process it twice:
3242 if (entry != pending)
3243 if (handle_futex_death((void __user *)entry + futex_offset,
3244 curr, pi))
3245 return;
3246 if (rc)
3247 return;
3248 entry = next_entry;
3249 pi = next_pi;
3251 * Avoid excessively long or circular lists:
3253 if (!--limit)
3254 break;
3256 cond_resched();
3259 if (pending)
3260 handle_futex_death((void __user *)pending + futex_offset,
3261 curr, pip);
3264 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
3265 u32 __user *uaddr2, u32 val2, u32 val3)
3267 int cmd = op & FUTEX_CMD_MASK;
3268 unsigned int flags = 0;
3270 if (!(op & FUTEX_PRIVATE_FLAG))
3271 flags |= FLAGS_SHARED;
3273 if (op & FUTEX_CLOCK_REALTIME) {
3274 flags |= FLAGS_CLOCKRT;
3275 if (cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET && \
3276 cmd != FUTEX_WAIT_REQUEUE_PI)
3277 return -ENOSYS;
3280 switch (cmd) {
3281 case FUTEX_LOCK_PI:
3282 case FUTEX_UNLOCK_PI:
3283 case FUTEX_TRYLOCK_PI:
3284 case FUTEX_WAIT_REQUEUE_PI:
3285 case FUTEX_CMP_REQUEUE_PI:
3286 if (!futex_cmpxchg_enabled)
3287 return -ENOSYS;
3290 switch (cmd) {
3291 case FUTEX_WAIT:
3292 val3 = FUTEX_BITSET_MATCH_ANY;
3293 case FUTEX_WAIT_BITSET:
3294 return futex_wait(uaddr, flags, val, timeout, val3);
3295 case FUTEX_WAKE:
3296 val3 = FUTEX_BITSET_MATCH_ANY;
3297 case FUTEX_WAKE_BITSET:
3298 return futex_wake(uaddr, flags, val, val3);
3299 case FUTEX_REQUEUE:
3300 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
3301 case FUTEX_CMP_REQUEUE:
3302 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
3303 case FUTEX_WAKE_OP:
3304 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
3305 case FUTEX_LOCK_PI:
3306 return futex_lock_pi(uaddr, flags, timeout, 0);
3307 case FUTEX_UNLOCK_PI:
3308 return futex_unlock_pi(uaddr, flags);
3309 case FUTEX_TRYLOCK_PI:
3310 return futex_lock_pi(uaddr, flags, NULL, 1);
3311 case FUTEX_WAIT_REQUEUE_PI:
3312 val3 = FUTEX_BITSET_MATCH_ANY;
3313 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3314 uaddr2);
3315 case FUTEX_CMP_REQUEUE_PI:
3316 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
3318 return -ENOSYS;
3322 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3323 struct timespec __user *, utime, u32 __user *, uaddr2,
3324 u32, val3)
3326 struct timespec ts;
3327 ktime_t t, *tp = NULL;
3328 u32 val2 = 0;
3329 int cmd = op & FUTEX_CMD_MASK;
3331 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
3332 cmd == FUTEX_WAIT_BITSET ||
3333 cmd == FUTEX_WAIT_REQUEUE_PI)) {
3334 if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
3335 return -EFAULT;
3336 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
3337 return -EFAULT;
3338 if (!timespec_valid(&ts))
3339 return -EINVAL;
3341 t = timespec_to_ktime(ts);
3342 if (cmd == FUTEX_WAIT)
3343 t = ktime_add_safe(ktime_get(), t);
3344 tp = &t;
3347 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
3348 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
3350 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
3351 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
3352 val2 = (u32) (unsigned long) utime;
3354 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
3357 static void __init futex_detect_cmpxchg(void)
3359 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
3360 u32 curval;
3363 * This will fail and we want it. Some arch implementations do
3364 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3365 * functionality. We want to know that before we call in any
3366 * of the complex code paths. Also we want to prevent
3367 * registration of robust lists in that case. NULL is
3368 * guaranteed to fault and we get -EFAULT on functional
3369 * implementation, the non-functional ones will return
3370 * -ENOSYS.
3372 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
3373 futex_cmpxchg_enabled = 1;
3374 #endif
3377 static int __init futex_init(void)
3379 unsigned int futex_shift;
3380 unsigned long i;
3382 #if CONFIG_BASE_SMALL
3383 futex_hashsize = 16;
3384 #else
3385 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
3386 #endif
3388 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
3389 futex_hashsize, 0,
3390 futex_hashsize < 256 ? HASH_SMALL : 0,
3391 &futex_shift, NULL,
3392 futex_hashsize, futex_hashsize);
3393 futex_hashsize = 1UL << futex_shift;
3395 futex_detect_cmpxchg();
3397 for (i = 0; i < futex_hashsize; i++) {
3398 atomic_set(&futex_queues[i].waiters, 0);
3399 plist_head_init(&futex_queues[i].chain);
3400 spin_lock_init(&futex_queues[i].lock);
3403 return 0;
3405 core_initcall(futex_init);