]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - kernel/futex.c
x86/speculation: Provide IBPB always command line options
[thirdparty/kernel/stable.git] / kernel / futex.c
CommitLineData
1da177e4
LT
1/*
2 * Fast Userspace Mutexes (which I call "Futexes!").
3 * (C) Rusty Russell, IBM 2002
4 *
5 * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
6 * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
7 *
8 * Removed page pinning, fix privately mapped COW pages and other cleanups
9 * (C) Copyright 2003, 2004 Jamie Lokier
10 *
0771dfef
IM
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.
14 *
c87e2837
IM
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>
18 *
34f01cc1
ED
19 * PRIVATE futexes by Eric Dumazet
20 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
21 *
52400ba9
DH
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.
25 *
1da177e4
LT
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.
29 *
30 * "The futexes are also cursed."
31 * "But they come in a choice of three flavours!"
32 *
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.
37 *
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.
42 *
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
46 */
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>
7ed20e1a 57#include <linux/signal.h>
9984de1a 58#include <linux/export.h>
fd5eea42 59#include <linux/magic.h>
b488893a
PE
60#include <linux/pid.h>
61#include <linux/nsproxy.h>
bdbb776f 62#include <linux/ptrace.h>
8bd75c77 63#include <linux/sched/rt.h>
13d60f4b 64#include <linux/hugetlb.h>
88c8004f 65#include <linux/freezer.h>
a52b89eb 66#include <linux/bootmem.h>
b488893a 67
4732efbe 68#include <asm/futex.h>
1da177e4 69
1696a8be 70#include "locking/rtmutex_common.h"
c87e2837 71
99b60ce6 72/*
d7e8af1a
DB
73 * READ this before attempting to hack on futexes!
74 *
75 * Basic futex operation and ordering guarantees
76 * =============================================
99b60ce6
TG
77 *
78 * The waiter reads the futex value in user space and calls
79 * futex_wait(). This function computes the hash bucket and acquires
80 * the hash bucket lock. After that it reads the futex user space value
b0c29f79
DB
81 * again and verifies that the data has not changed. If it has not changed
82 * it enqueues itself into the hash bucket, releases the hash bucket lock
83 * and schedules.
99b60ce6
TG
84 *
85 * The waker side modifies the user space value of the futex and calls
b0c29f79
DB
86 * futex_wake(). This function computes the hash bucket and acquires the
87 * hash bucket lock. Then it looks for waiters on that futex in the hash
88 * bucket and wakes them.
99b60ce6 89 *
b0c29f79
DB
90 * In futex wake up scenarios where no tasks are blocked on a futex, taking
91 * the hb spinlock can be avoided and simply return. In order for this
92 * optimization to work, ordering guarantees must exist so that the waiter
93 * being added to the list is acknowledged when the list is concurrently being
94 * checked by the waker, avoiding scenarios like the following:
99b60ce6
TG
95 *
96 * CPU 0 CPU 1
97 * val = *futex;
98 * sys_futex(WAIT, futex, val);
99 * futex_wait(futex, val);
100 * uval = *futex;
101 * *futex = newval;
102 * sys_futex(WAKE, futex);
103 * futex_wake(futex);
104 * if (queue_empty())
105 * return;
106 * if (uval == val)
107 * lock(hash_bucket(futex));
108 * queue();
109 * unlock(hash_bucket(futex));
110 * schedule();
111 *
112 * This would cause the waiter on CPU 0 to wait forever because it
113 * missed the transition of the user space value from val to newval
114 * and the waker did not find the waiter in the hash bucket queue.
99b60ce6 115 *
b0c29f79
DB
116 * The correct serialization ensures that a waiter either observes
117 * the changed user space value before blocking or is woken by a
118 * concurrent waker:
119 *
120 * CPU 0 CPU 1
99b60ce6
TG
121 * val = *futex;
122 * sys_futex(WAIT, futex, val);
123 * futex_wait(futex, val);
b0c29f79 124 *
d7e8af1a 125 * waiters++; (a)
b0c29f79
DB
126 * mb(); (A) <-- paired with -.
127 * |
128 * lock(hash_bucket(futex)); |
129 * |
130 * uval = *futex; |
131 * | *futex = newval;
132 * | sys_futex(WAKE, futex);
133 * | futex_wake(futex);
134 * |
135 * `-------> mb(); (B)
99b60ce6 136 * if (uval == val)
b0c29f79 137 * queue();
99b60ce6 138 * unlock(hash_bucket(futex));
b0c29f79
DB
139 * schedule(); if (waiters)
140 * lock(hash_bucket(futex));
d7e8af1a
DB
141 * else wake_waiters(futex);
142 * waiters--; (b) unlock(hash_bucket(futex));
b0c29f79 143 *
d7e8af1a
DB
144 * Where (A) orders the waiters increment and the futex value read through
145 * atomic operations (see hb_waiters_inc) and where (B) orders the write
146 * to futex and the waiters read -- this is done by the barriers in
147 * get_futex_key_refs(), through either ihold or atomic_inc, depending on the
148 * futex type.
b0c29f79
DB
149 *
150 * This yields the following case (where X:=waiters, Y:=futex):
151 *
152 * X = Y = 0
153 *
154 * w[X]=1 w[Y]=1
155 * MB MB
156 * r[Y]=y r[X]=x
157 *
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.
d7e8af1a
DB
161 *
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().
165 *
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.
99b60ce6
TG
172 */
173
03b8c7b6 174#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
a0c1e907 175int __read_mostly futex_cmpxchg_enabled;
03b8c7b6 176#endif
a0c1e907 177
b41277dc
DH
178/*
179 * Futex flags used to encode options to functions and preserve them across
180 * restarts.
181 */
182#define FLAGS_SHARED 0x01
183#define FLAGS_CLOCKRT 0x02
184#define FLAGS_HAS_TIMEOUT 0x04
185
c87e2837
IM
186/*
187 * Priority Inheritance state:
188 */
189struct futex_pi_state {
190 /*
191 * list of 'owned' pi_state instances - these have to be
192 * cleaned up in do_exit() if the task exits prematurely:
193 */
194 struct list_head list;
195
196 /*
197 * The PI object:
198 */
199 struct rt_mutex pi_mutex;
200
201 struct task_struct *owner;
202 atomic_t refcount;
203
204 union futex_key key;
205};
206
d8d88fbb
DH
207/**
208 * struct futex_q - The hashed futex queue entry, one per waiting task
fb62db2b 209 * @list: priority-sorted list of tasks waiting on this futex
d8d88fbb
DH
210 * @task: the task waiting on the futex
211 * @lock_ptr: the hash bucket lock
212 * @key: the key the futex is hashed on
213 * @pi_state: optional priority inheritance state
214 * @rt_waiter: rt_waiter storage for use with requeue_pi
215 * @requeue_pi_key: the requeue_pi target futex key
216 * @bitset: bitset for the optional bitmasked wakeup
217 *
218 * We use this hashed waitqueue, instead of a normal wait_queue_t, so
1da177e4
LT
219 * we can wake only the relevant ones (hashed queues may be shared).
220 *
221 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
ec92d082 222 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
fb62db2b 223 * The order of wakeup is always to make the first condition true, then
d8d88fbb
DH
224 * the second.
225 *
226 * PI futexes are typically woken before they are removed from the hash list via
227 * the rt_mutex code. See unqueue_me_pi().
1da177e4
LT
228 */
229struct futex_q {
ec92d082 230 struct plist_node list;
1da177e4 231
d8d88fbb 232 struct task_struct *task;
1da177e4 233 spinlock_t *lock_ptr;
1da177e4 234 union futex_key key;
c87e2837 235 struct futex_pi_state *pi_state;
52400ba9 236 struct rt_mutex_waiter *rt_waiter;
84bc4af5 237 union futex_key *requeue_pi_key;
cd689985 238 u32 bitset;
1da177e4
LT
239};
240
5bdb05f9
DH
241static const struct futex_q futex_q_init = {
242 /* list gets initialized in queue_me()*/
243 .key = FUTEX_KEY_INIT,
244 .bitset = FUTEX_BITSET_MATCH_ANY
245};
246
1da177e4 247/*
b2d0994b
DH
248 * Hash buckets are shared by all the futex_keys that hash to the same
249 * location. Each key may have multiple futex_q structures, one for each task
250 * waiting on a futex.
1da177e4
LT
251 */
252struct futex_hash_bucket {
11d4616b 253 atomic_t waiters;
ec92d082
PP
254 spinlock_t lock;
255 struct plist_head chain;
a52b89eb 256} ____cacheline_aligned_in_smp;
1da177e4 257
a52b89eb
DB
258static unsigned long __read_mostly futex_hashsize;
259
260static struct futex_hash_bucket *futex_queues;
1da177e4 261
b0c29f79
DB
262static inline void futex_get_mm(union futex_key *key)
263{
264 atomic_inc(&key->private.mm->mm_count);
265 /*
266 * Ensure futex_get_mm() implies a full barrier such that
267 * get_futex_key() implies a full barrier. This is relied upon
268 * as full barrier (B), see the ordering comment above.
269 */
4e857c58 270 smp_mb__after_atomic();
b0c29f79
DB
271}
272
11d4616b
LT
273/*
274 * Reflects a new waiter being added to the waitqueue.
275 */
276static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
b0c29f79
DB
277{
278#ifdef CONFIG_SMP
11d4616b 279 atomic_inc(&hb->waiters);
b0c29f79 280 /*
11d4616b 281 * Full barrier (A), see the ordering comment above.
b0c29f79 282 */
4e857c58 283 smp_mb__after_atomic();
11d4616b
LT
284#endif
285}
286
287/*
288 * Reflects a waiter being removed from the waitqueue by wakeup
289 * paths.
290 */
291static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
292{
293#ifdef CONFIG_SMP
294 atomic_dec(&hb->waiters);
295#endif
296}
b0c29f79 297
11d4616b
LT
298static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
299{
300#ifdef CONFIG_SMP
301 return atomic_read(&hb->waiters);
b0c29f79 302#else
11d4616b 303 return 1;
b0c29f79
DB
304#endif
305}
306
1da177e4
LT
307/*
308 * We hash on the keys returned from get_futex_key (see below).
309 */
310static struct futex_hash_bucket *hash_futex(union futex_key *key)
311{
312 u32 hash = jhash2((u32*)&key->both.word,
313 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
314 key->both.offset);
a52b89eb 315 return &futex_queues[hash & (futex_hashsize - 1)];
1da177e4
LT
316}
317
318/*
319 * Return 1 if two futex_keys are equal, 0 otherwise.
320 */
321static inline int match_futex(union futex_key *key1, union futex_key *key2)
322{
2bc87203
DH
323 return (key1 && key2
324 && key1->both.word == key2->both.word
1da177e4
LT
325 && key1->both.ptr == key2->both.ptr
326 && key1->both.offset == key2->both.offset);
327}
328
38d47c1b
PZ
329/*
330 * Take a reference to the resource addressed by a key.
331 * Can be called while holding spinlocks.
332 *
333 */
334static void get_futex_key_refs(union futex_key *key)
335{
336 if (!key->both.ptr)
337 return;
338
339 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
340 case FUT_OFF_INODE:
b0c29f79 341 ihold(key->shared.inode); /* implies MB (B) */
38d47c1b
PZ
342 break;
343 case FUT_OFF_MMSHARED:
b0c29f79 344 futex_get_mm(key); /* implies MB (B) */
38d47c1b 345 break;
b8981499
CM
346 default:
347 smp_mb(); /* explicit MB (B) */
38d47c1b
PZ
348 }
349}
350
351/*
352 * Drop a reference to the resource addressed by a key.
353 * The hash bucket spinlock must not be held.
354 */
355static void drop_futex_key_refs(union futex_key *key)
356{
90621c40
DH
357 if (!key->both.ptr) {
358 /* If we're here then we tried to put a key we failed to get */
359 WARN_ON_ONCE(1);
38d47c1b 360 return;
90621c40 361 }
38d47c1b
PZ
362
363 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
364 case FUT_OFF_INODE:
365 iput(key->shared.inode);
366 break;
367 case FUT_OFF_MMSHARED:
368 mmdrop(key->private.mm);
369 break;
370 }
371}
372
34f01cc1 373/**
d96ee56c
DH
374 * get_futex_key() - Get parameters which are the keys for a futex
375 * @uaddr: virtual address of the futex
376 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
377 * @key: address where result is stored.
9ea71503
SB
378 * @rw: mapping needs to be read/write (values: VERIFY_READ,
379 * VERIFY_WRITE)
34f01cc1 380 *
6c23cbbd
RD
381 * Return: a negative error code or 0
382 *
34f01cc1 383 * The key words are stored in *key on success.
1da177e4 384 *
6131ffaa 385 * For shared mappings, it's (page->index, file_inode(vma->vm_file),
1da177e4
LT
386 * offset_within_page). For private mappings, it's (uaddr, current->mm).
387 * We can usually work out the index without swapping in the page.
388 *
b2d0994b 389 * lock_page() might sleep, the caller should not hold a spinlock.
1da177e4 390 */
64d1304a 391static int
9ea71503 392get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
1da177e4 393{
e2970f2f 394 unsigned long address = (unsigned long)uaddr;
1da177e4 395 struct mm_struct *mm = current->mm;
a5b338f2 396 struct page *page, *page_head;
862b19bc 397 struct address_space *mapping;
9ea71503 398 int err, ro = 0;
1da177e4
LT
399
400 /*
401 * The futex address must be "naturally" aligned.
402 */
e2970f2f 403 key->both.offset = address % PAGE_SIZE;
34f01cc1 404 if (unlikely((address % sizeof(u32)) != 0))
1da177e4 405 return -EINVAL;
e2970f2f 406 address -= key->both.offset;
1da177e4 407
5cdec2d8
LT
408 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
409 return -EFAULT;
410
34f01cc1
ED
411 /*
412 * PROCESS_PRIVATE futexes are fast.
413 * As the mm cannot disappear under us and the 'key' only needs
414 * virtual address, we dont even have to find the underlying vma.
415 * Note : We do have to check 'uaddr' is a valid user address,
416 * but access_ok() should be faster than find_vma()
417 */
418 if (!fshared) {
34f01cc1
ED
419 key->private.mm = mm;
420 key->private.address = address;
b0c29f79 421 get_futex_key_refs(key); /* implies MB (B) */
34f01cc1
ED
422 return 0;
423 }
1da177e4 424
38d47c1b 425again:
7485d0d3 426 err = get_user_pages_fast(address, 1, 1, &page);
9ea71503
SB
427 /*
428 * If write access is not required (eg. FUTEX_WAIT), try
429 * and get read-only access.
430 */
431 if (err == -EFAULT && rw == VERIFY_READ) {
432 err = get_user_pages_fast(address, 1, 0, &page);
433 ro = 1;
434 }
38d47c1b
PZ
435 if (err < 0)
436 return err;
9ea71503
SB
437 else
438 err = 0;
38d47c1b 439
a5b338f2
AA
440#ifdef CONFIG_TRANSPARENT_HUGEPAGE
441 page_head = page;
442 if (unlikely(PageTail(page))) {
38d47c1b 443 put_page(page);
a5b338f2
AA
444 /* serialize against __split_huge_page_splitting() */
445 local_irq_disable();
f12d5bfc 446 if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) {
a5b338f2
AA
447 page_head = compound_head(page);
448 /*
449 * page_head is valid pointer but we must pin
450 * it before taking the PG_lock and/or
451 * PG_compound_lock. The moment we re-enable
452 * irqs __split_huge_page_splitting() can
453 * return and the head page can be freed from
454 * under us. We can't take the PG_lock and/or
455 * PG_compound_lock on a page that could be
456 * freed from under us.
457 */
458 if (page != page_head) {
459 get_page(page_head);
460 put_page(page);
461 }
462 local_irq_enable();
463 } else {
464 local_irq_enable();
465 goto again;
466 }
467 }
468#else
469 page_head = compound_head(page);
470 if (page != page_head) {
471 get_page(page_head);
472 put_page(page);
473 }
474#endif
475
862b19bc
MG
476 /*
477 * The treatment of mapping from this point on is critical. The page
478 * lock protects many things but in this context the page lock
479 * stabilizes mapping, prevents inode freeing in the shared
480 * file-backed region case and guards against movement to swap cache.
481 *
482 * Strictly speaking the page lock is not needed in all cases being
483 * considered here and page lock forces unnecessarily serialization
484 * From this point on, mapping will be re-verified if necessary and
485 * page lock will be acquired only if it is unavoidable
486 */
487
488 mapping = ACCESS_ONCE(page_head->mapping);
e6780f72
HD
489
490 /*
491 * If page_head->mapping is NULL, then it cannot be a PageAnon
492 * page; but it might be the ZERO_PAGE or in the gate area or
493 * in a special mapping (all cases which we are happy to fail);
494 * or it may have been a good file page when get_user_pages_fast
495 * found it, but truncated or holepunched or subjected to
496 * invalidate_complete_page2 before we got the page lock (also
497 * cases which we are happy to fail). And we hold a reference,
498 * so refcount care in invalidate_complete_page's remove_mapping
499 * prevents drop_caches from setting mapping to NULL beneath us.
500 *
501 * The case we do have to guard against is when memory pressure made
502 * shmem_writepage move it from filecache to swapcache beneath us:
503 * an unlikely race, but we do need to retry for page_head->mapping.
504 */
862b19bc
MG
505 if (unlikely(!mapping)) {
506 int shmem_swizzled;
507
508 /*
509 * Page lock is required to identify which special case above
510 * applies. If this is really a shmem page then the page lock
511 * will prevent unexpected transitions.
512 */
513 lock_page(page);
514 shmem_swizzled = PageSwapCache(page) || page->mapping;
a5b338f2
AA
515 unlock_page(page_head);
516 put_page(page_head);
862b19bc 517
e6780f72
HD
518 if (shmem_swizzled)
519 goto again;
862b19bc 520
e6780f72 521 return -EFAULT;
38d47c1b 522 }
1da177e4
LT
523
524 /*
525 * Private mappings are handled in a simple way.
526 *
862b19bc
MG
527 * If the futex key is stored on an anonymous page, then the associated
528 * object is the mm which is implicitly pinned by the calling process.
529 *
1da177e4
LT
530 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
531 * it's a read-only handle, it's expected that futexes attach to
38d47c1b 532 * the object not the particular process.
1da177e4 533 */
a5b338f2 534 if (PageAnon(page_head)) {
9ea71503
SB
535 /*
536 * A RO anonymous page will never change and thus doesn't make
537 * sense for futex operations.
538 */
539 if (ro) {
540 err = -EFAULT;
541 goto out;
542 }
543
38d47c1b 544 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
1da177e4 545 key->private.mm = mm;
e2970f2f 546 key->private.address = address;
862b19bc
MG
547
548 get_futex_key_refs(key); /* implies smp_mb(); (B) */
549
38d47c1b 550 } else {
862b19bc
MG
551 struct inode *inode;
552
553 /*
554 * The associated futex object in this case is the inode and
555 * the page->mapping must be traversed. Ordinarily this should
556 * be stabilised under page lock but it's not strictly
557 * necessary in this case as we just want to pin the inode, not
558 * update the radix tree or anything like that.
559 *
560 * The RCU read lock is taken as the inode is finally freed
561 * under RCU. If the mapping still matches expectations then the
562 * mapping->host can be safely accessed as being a valid inode.
563 */
564 rcu_read_lock();
565
566 if (ACCESS_ONCE(page_head->mapping) != mapping) {
567 rcu_read_unlock();
568 put_page(page_head);
569
570 goto again;
571 }
572
573 inode = ACCESS_ONCE(mapping->host);
574 if (!inode) {
575 rcu_read_unlock();
576 put_page(page_head);
577
578 goto again;
579 }
580
581 /*
582 * Take a reference unless it is about to be freed. Previously
583 * this reference was taken by ihold under the page lock
584 * pinning the inode in place so i_lock was unnecessary. The
585 * only way for this check to fail is if the inode was
3887a9ac
MG
586 * truncated in parallel which is almost certainly an
587 * application bug. In such a case, just retry.
862b19bc
MG
588 *
589 * We are not calling into get_futex_key_refs() in file-backed
590 * cases, therefore a successful atomic_inc return below will
591 * guarantee that get_futex_key() will still imply smp_mb(); (B).
592 */
3887a9ac 593 if (!atomic_inc_not_zero(&inode->i_count)) {
862b19bc
MG
594 rcu_read_unlock();
595 put_page(page_head);
596
597 goto again;
598 }
599
600 /* Should be impossible but lets be paranoid for now */
601 if (WARN_ON_ONCE(inode->i_mapping != mapping)) {
602 err = -EFAULT;
603 rcu_read_unlock();
604 iput(inode);
605
606 goto out;
607 }
608
38d47c1b 609 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
862b19bc 610 key->shared.inode = inode;
13d60f4b 611 key->shared.pgoff = basepage_index(page);
862b19bc 612 rcu_read_unlock();
1da177e4
LT
613 }
614
9ea71503 615out:
a5b338f2 616 put_page(page_head);
9ea71503 617 return err;
1da177e4
LT
618}
619
ae791a2d 620static inline void put_futex_key(union futex_key *key)
1da177e4 621{
38d47c1b 622 drop_futex_key_refs(key);
1da177e4
LT
623}
624
d96ee56c
DH
625/**
626 * fault_in_user_writeable() - Fault in user address and verify RW access
d0725992
TG
627 * @uaddr: pointer to faulting user space address
628 *
629 * Slow path to fixup the fault we just took in the atomic write
630 * access to @uaddr.
631 *
fb62db2b 632 * We have no generic implementation of a non-destructive write to the
d0725992
TG
633 * user address. We know that we faulted in the atomic pagefault
634 * disabled section so we can as well avoid the #PF overhead by
635 * calling get_user_pages() right away.
636 */
637static int fault_in_user_writeable(u32 __user *uaddr)
638{
722d0172
AK
639 struct mm_struct *mm = current->mm;
640 int ret;
641
642 down_read(&mm->mmap_sem);
2efaca92
BH
643 ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
644 FAULT_FLAG_WRITE);
722d0172
AK
645 up_read(&mm->mmap_sem);
646
d0725992
TG
647 return ret < 0 ? ret : 0;
648}
649
4b1c486b
DH
650/**
651 * futex_top_waiter() - Return the highest priority waiter on a futex
d96ee56c
DH
652 * @hb: the hash bucket the futex_q's reside in
653 * @key: the futex key (to distinguish it from other futex futex_q's)
4b1c486b
DH
654 *
655 * Must be called with the hb lock held.
656 */
657static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
658 union futex_key *key)
659{
660 struct futex_q *this;
661
662 plist_for_each_entry(this, &hb->chain, list) {
663 if (match_futex(&this->key, key))
664 return this;
665 }
666 return NULL;
667}
668
37a9d912
ML
669static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
670 u32 uval, u32 newval)
36cf3b5c 671{
37a9d912 672 int ret;
36cf3b5c
TG
673
674 pagefault_disable();
37a9d912 675 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
36cf3b5c
TG
676 pagefault_enable();
677
37a9d912 678 return ret;
36cf3b5c
TG
679}
680
681static int get_futex_value_locked(u32 *dest, u32 __user *from)
1da177e4
LT
682{
683 int ret;
684
a866374a 685 pagefault_disable();
e2970f2f 686 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
a866374a 687 pagefault_enable();
1da177e4
LT
688
689 return ret ? -EFAULT : 0;
690}
691
c87e2837
IM
692
693/*
694 * PI code:
695 */
696static int refill_pi_state_cache(void)
697{
698 struct futex_pi_state *pi_state;
699
700 if (likely(current->pi_state_cache))
701 return 0;
702
4668edc3 703 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
c87e2837
IM
704
705 if (!pi_state)
706 return -ENOMEM;
707
c87e2837
IM
708 INIT_LIST_HEAD(&pi_state->list);
709 /* pi_mutex gets initialized later */
710 pi_state->owner = NULL;
711 atomic_set(&pi_state->refcount, 1);
38d47c1b 712 pi_state->key = FUTEX_KEY_INIT;
c87e2837
IM
713
714 current->pi_state_cache = pi_state;
715
716 return 0;
717}
718
719static struct futex_pi_state * alloc_pi_state(void)
720{
721 struct futex_pi_state *pi_state = current->pi_state_cache;
722
723 WARN_ON(!pi_state);
724 current->pi_state_cache = NULL;
725
726 return pi_state;
727}
728
6af5729d
BS
729/*
730 * Must be called with the hb lock held.
731 */
c87e2837
IM
732static void free_pi_state(struct futex_pi_state *pi_state)
733{
6af5729d
BS
734 if (!pi_state)
735 return;
736
c87e2837
IM
737 if (!atomic_dec_and_test(&pi_state->refcount))
738 return;
739
740 /*
741 * If pi_state->owner is NULL, the owner is most probably dying
742 * and has cleaned up the pi_state already
743 */
744 if (pi_state->owner) {
1d615482 745 raw_spin_lock_irq(&pi_state->owner->pi_lock);
c87e2837 746 list_del_init(&pi_state->list);
1d615482 747 raw_spin_unlock_irq(&pi_state->owner->pi_lock);
c87e2837
IM
748
749 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
750 }
751
752 if (current->pi_state_cache)
753 kfree(pi_state);
754 else {
755 /*
756 * pi_state->list is already empty.
757 * clear pi_state->owner.
758 * refcount is at 0 - put it back to 1.
759 */
760 pi_state->owner = NULL;
761 atomic_set(&pi_state->refcount, 1);
762 current->pi_state_cache = pi_state;
763 }
764}
765
766/*
767 * Look up the task based on what TID userspace gave us.
768 * We dont trust it.
769 */
770static struct task_struct * futex_find_get_task(pid_t pid)
771{
772 struct task_struct *p;
773
d359b549 774 rcu_read_lock();
228ebcbe 775 p = find_task_by_vpid(pid);
7a0ea09a
MH
776 if (p)
777 get_task_struct(p);
a06381fe 778
d359b549 779 rcu_read_unlock();
c87e2837
IM
780
781 return p;
782}
783
784/*
785 * This task is holding PI mutexes at exit time => bad.
786 * Kernel cleans up PI-state, but userspace is likely hosed.
787 * (Robust-futex cleanup is separate and might save the day for userspace.)
788 */
789void exit_pi_state_list(struct task_struct *curr)
790{
c87e2837
IM
791 struct list_head *next, *head = &curr->pi_state_list;
792 struct futex_pi_state *pi_state;
627371d7 793 struct futex_hash_bucket *hb;
38d47c1b 794 union futex_key key = FUTEX_KEY_INIT;
c87e2837 795
a0c1e907
TG
796 if (!futex_cmpxchg_enabled)
797 return;
c87e2837
IM
798 /*
799 * We are a ZOMBIE and nobody can enqueue itself on
800 * pi_state_list anymore, but we have to be careful
627371d7 801 * versus waiters unqueueing themselves:
c87e2837 802 */
1d615482 803 raw_spin_lock_irq(&curr->pi_lock);
c87e2837
IM
804 while (!list_empty(head)) {
805
806 next = head->next;
807 pi_state = list_entry(next, struct futex_pi_state, list);
808 key = pi_state->key;
627371d7 809 hb = hash_futex(&key);
1d615482 810 raw_spin_unlock_irq(&curr->pi_lock);
c87e2837 811
c87e2837
IM
812 spin_lock(&hb->lock);
813
1d615482 814 raw_spin_lock_irq(&curr->pi_lock);
627371d7
IM
815 /*
816 * We dropped the pi-lock, so re-check whether this
817 * task still owns the PI-state:
818 */
c87e2837
IM
819 if (head->next != next) {
820 spin_unlock(&hb->lock);
821 continue;
822 }
823
c87e2837 824 WARN_ON(pi_state->owner != curr);
627371d7
IM
825 WARN_ON(list_empty(&pi_state->list));
826 list_del_init(&pi_state->list);
c87e2837 827 pi_state->owner = NULL;
1d615482 828 raw_spin_unlock_irq(&curr->pi_lock);
c87e2837
IM
829
830 rt_mutex_unlock(&pi_state->pi_mutex);
831
832 spin_unlock(&hb->lock);
833
1d615482 834 raw_spin_lock_irq(&curr->pi_lock);
c87e2837 835 }
1d615482 836 raw_spin_unlock_irq(&curr->pi_lock);
c87e2837
IM
837}
838
54a21788
TG
839/*
840 * We need to check the following states:
841 *
842 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
843 *
844 * [1] NULL | --- | --- | 0 | 0/1 | Valid
845 * [2] NULL | --- | --- | >0 | 0/1 | Valid
846 *
847 * [3] Found | NULL | -- | Any | 0/1 | Invalid
848 *
849 * [4] Found | Found | NULL | 0 | 1 | Valid
850 * [5] Found | Found | NULL | >0 | 1 | Invalid
851 *
852 * [6] Found | Found | task | 0 | 1 | Valid
853 *
854 * [7] Found | Found | NULL | Any | 0 | Invalid
855 *
856 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
857 * [9] Found | Found | task | 0 | 0 | Invalid
858 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
859 *
860 * [1] Indicates that the kernel can acquire the futex atomically. We
861 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
862 *
863 * [2] Valid, if TID does not belong to a kernel thread. If no matching
864 * thread is found then it indicates that the owner TID has died.
865 *
866 * [3] Invalid. The waiter is queued on a non PI futex
867 *
868 * [4] Valid state after exit_robust_list(), which sets the user space
869 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
870 *
871 * [5] The user space value got manipulated between exit_robust_list()
872 * and exit_pi_state_list()
873 *
874 * [6] Valid state after exit_pi_state_list() which sets the new owner in
875 * the pi_state but cannot access the user space value.
876 *
877 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
878 *
879 * [8] Owner and user space value match
880 *
881 * [9] There is no transient state which sets the user space TID to 0
882 * except exit_robust_list(), but this is indicated by the
883 * FUTEX_OWNER_DIED bit. See [4]
884 *
885 * [10] There is no transient state which leaves owner and user space
886 * TID out of sync.
887 */
c87e2837 888static int
d0aa7a70 889lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
54a21788 890 union futex_key *key, struct futex_pi_state **ps)
c87e2837
IM
891{
892 struct futex_pi_state *pi_state = NULL;
893 struct futex_q *this, *next;
c87e2837 894 struct task_struct *p;
778e9a9c 895 pid_t pid = uval & FUTEX_TID_MASK;
c87e2837 896
0d00c7b2 897 plist_for_each_entry_safe(this, next, &hb->chain, list) {
d0aa7a70 898 if (match_futex(&this->key, key)) {
c87e2837 899 /*
54a21788
TG
900 * Sanity check the waiter before increasing
901 * the refcount and attaching to it.
c87e2837
IM
902 */
903 pi_state = this->pi_state;
06a9ec29 904 /*
54a21788
TG
905 * Userspace might have messed up non-PI and
906 * PI futexes [3]
06a9ec29
TG
907 */
908 if (unlikely(!pi_state))
909 return -EINVAL;
910
627371d7 911 WARN_ON(!atomic_read(&pi_state->refcount));
59647b6a
TG
912
913 /*
54a21788 914 * Handle the owner died case:
59647b6a 915 */
54a21788 916 if (uval & FUTEX_OWNER_DIED) {
59647b6a 917 /*
54a21788
TG
918 * exit_pi_state_list sets owner to NULL and
919 * wakes the topmost waiter. The task which
920 * acquires the pi_state->rt_mutex will fixup
921 * owner.
59647b6a 922 */
54a21788
TG
923 if (!pi_state->owner) {
924 /*
925 * No pi state owner, but the user
926 * space TID is not 0. Inconsistent
927 * state. [5]
928 */
929 if (pid)
930 return -EINVAL;
931 /*
932 * Take a ref on the state and
933 * return. [4]
934 */
935 goto out_state;
936 }
937
938 /*
939 * If TID is 0, then either the dying owner
940 * has not yet executed exit_pi_state_list()
941 * or some waiter acquired the rtmutex in the
942 * pi state, but did not yet fixup the TID in
943 * user space.
944 *
945 * Take a ref on the state and return. [6]
946 */
947 if (!pid)
948 goto out_state;
949 } else {
950 /*
951 * If the owner died bit is not set,
952 * then the pi_state must have an
953 * owner. [7]
954 */
955 if (!pi_state->owner)
59647b6a
TG
956 return -EINVAL;
957 }
627371d7 958
866293ee 959 /*
54a21788
TG
960 * Bail out if user space manipulated the
961 * futex value. If pi state exists then the
962 * owner TID must be the same as the user
963 * space TID. [9/10]
866293ee 964 */
54a21788
TG
965 if (pid != task_pid_vnr(pi_state->owner))
966 return -EINVAL;
866293ee 967
54a21788 968 out_state:
c87e2837 969 atomic_inc(&pi_state->refcount);
d0aa7a70 970 *ps = pi_state;
c87e2837
IM
971 return 0;
972 }
973 }
974
975 /*
e3f2ddea 976 * We are the first waiter - try to look up the real owner and attach
54a21788 977 * the new pi_state to it, but bail out when TID = 0 [1]
c87e2837 978 */
778e9a9c 979 if (!pid)
e3f2ddea 980 return -ESRCH;
c87e2837 981 p = futex_find_get_task(pid);
7a0ea09a
MH
982 if (!p)
983 return -ESRCH;
778e9a9c 984
f0d71b3d
TG
985 if (!p->mm) {
986 put_task_struct(p);
987 return -EPERM;
988 }
989
778e9a9c
AK
990 /*
991 * We need to look at the task state flags to figure out,
992 * whether the task is exiting. To protect against the do_exit
993 * change of the task flags, we do this protected by
994 * p->pi_lock:
995 */
1d615482 996 raw_spin_lock_irq(&p->pi_lock);
778e9a9c
AK
997 if (unlikely(p->flags & PF_EXITING)) {
998 /*
999 * The task is on the way out. When PF_EXITPIDONE is
1000 * set, we know that the task has finished the
1001 * cleanup:
1002 */
1003 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
1004
1d615482 1005 raw_spin_unlock_irq(&p->pi_lock);
778e9a9c
AK
1006 put_task_struct(p);
1007 return ret;
1008 }
c87e2837 1009
54a21788
TG
1010 /*
1011 * No existing pi state. First waiter. [2]
1012 */
c87e2837
IM
1013 pi_state = alloc_pi_state();
1014
1015 /*
1016 * Initialize the pi_mutex in locked state and make 'p'
1017 * the owner of it:
1018 */
1019 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1020
1021 /* Store the key for possible exit cleanups: */
d0aa7a70 1022 pi_state->key = *key;
c87e2837 1023
627371d7 1024 WARN_ON(!list_empty(&pi_state->list));
c87e2837
IM
1025 list_add(&pi_state->list, &p->pi_state_list);
1026 pi_state->owner = p;
1d615482 1027 raw_spin_unlock_irq(&p->pi_lock);
c87e2837
IM
1028
1029 put_task_struct(p);
1030
d0aa7a70 1031 *ps = pi_state;
c87e2837
IM
1032
1033 return 0;
1034}
1035
1a52084d 1036/**
d96ee56c 1037 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
bab5bc9e
DH
1038 * @uaddr: the pi futex user address
1039 * @hb: the pi futex hash bucket
1040 * @key: the futex key associated with uaddr and hb
1041 * @ps: the pi_state pointer where we store the result of the
1042 * lookup
1043 * @task: the task to perform the atomic lock work for. This will
1044 * be "current" except in the case of requeue pi.
1045 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1a52084d 1046 *
6c23cbbd
RD
1047 * Return:
1048 * 0 - ready to wait;
1049 * 1 - acquired the lock;
1a52084d
DH
1050 * <0 - error
1051 *
1052 * The hb->lock and futex_key refs shall be held by the caller.
1053 */
1054static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1055 union futex_key *key,
1056 struct futex_pi_state **ps,
bab5bc9e 1057 struct task_struct *task, int set_waiters)
1a52084d 1058{
59fa6245 1059 int lock_taken, ret, force_take = 0;
c0c9ed15 1060 u32 uval, newval, curval, vpid = task_pid_vnr(task);
1a52084d
DH
1061
1062retry:
1063 ret = lock_taken = 0;
1064
1065 /*
1066 * To avoid races, we attempt to take the lock here again
1067 * (by doing a 0 -> TID atomic cmpxchg), while holding all
1068 * the locks. It will most likely not succeed.
1069 */
c0c9ed15 1070 newval = vpid;
bab5bc9e
DH
1071 if (set_waiters)
1072 newval |= FUTEX_WAITERS;
1a52084d 1073
37a9d912 1074 if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, 0, newval)))
1a52084d
DH
1075 return -EFAULT;
1076
1077 /*
1078 * Detect deadlocks.
1079 */
c0c9ed15 1080 if ((unlikely((curval & FUTEX_TID_MASK) == vpid)))
1a52084d
DH
1081 return -EDEADLK;
1082
1083 /*
b3eaa9fc 1084 * Surprise - we got the lock, but we do not trust user space at all.
1a52084d 1085 */
b3eaa9fc
TG
1086 if (unlikely(!curval)) {
1087 /*
1088 * We verify whether there is kernel state for this
1089 * futex. If not, we can safely assume, that the 0 ->
1090 * TID transition is correct. If state exists, we do
1091 * not bother to fixup the user space state as it was
1092 * corrupted already.
1093 */
1094 return futex_top_waiter(hb, key) ? -EINVAL : 1;
1095 }
1a52084d
DH
1096
1097 uval = curval;
1098
1099 /*
1100 * Set the FUTEX_WAITERS flag, so the owner will know it has someone
1101 * to wake at the next unlock.
1102 */
1103 newval = curval | FUTEX_WAITERS;
1104
1105 /*
59fa6245 1106 * Should we force take the futex? See below.
1a52084d 1107 */
59fa6245
TG
1108 if (unlikely(force_take)) {
1109 /*
1110 * Keep the OWNER_DIED and the WAITERS bit and set the
1111 * new TID value.
1112 */
c0c9ed15 1113 newval = (curval & ~FUTEX_TID_MASK) | vpid;
59fa6245 1114 force_take = 0;
1a52084d
DH
1115 lock_taken = 1;
1116 }
1117
37a9d912 1118 if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
1a52084d
DH
1119 return -EFAULT;
1120 if (unlikely(curval != uval))
1121 goto retry;
1122
1123 /*
59fa6245 1124 * We took the lock due to forced take over.
1a52084d
DH
1125 */
1126 if (unlikely(lock_taken))
1127 return 1;
1128
1129 /*
1130 * We dont have the lock. Look up the PI state (or create it if
1131 * we are the first waiter):
1132 */
54a21788 1133 ret = lookup_pi_state(uval, hb, key, ps);
1a52084d
DH
1134
1135 if (unlikely(ret)) {
1136 switch (ret) {
1137 case -ESRCH:
1138 /*
59fa6245
TG
1139 * We failed to find an owner for this
1140 * futex. So we have no pi_state to block
1141 * on. This can happen in two cases:
1142 *
1143 * 1) The owner died
1144 * 2) A stale FUTEX_WAITERS bit
1145 *
1146 * Re-read the futex value.
1a52084d
DH
1147 */
1148 if (get_futex_value_locked(&curval, uaddr))
1149 return -EFAULT;
1150
1151 /*
59fa6245
TG
1152 * If the owner died or we have a stale
1153 * WAITERS bit the owner TID in the user space
1154 * futex is 0.
1a52084d 1155 */
59fa6245
TG
1156 if (!(curval & FUTEX_TID_MASK)) {
1157 force_take = 1;
1a52084d
DH
1158 goto retry;
1159 }
1160 default:
1161 break;
1162 }
1163 }
1164
1165 return ret;
1166}
1167
2e12978a
LJ
1168/**
1169 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1170 * @q: The futex_q to unqueue
1171 *
1172 * The q->lock_ptr must not be NULL and must be held by the caller.
1173 */
1174static void __unqueue_futex(struct futex_q *q)
1175{
1176 struct futex_hash_bucket *hb;
1177
29096202
SR
1178 if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
1179 || WARN_ON(plist_node_empty(&q->list)))
2e12978a
LJ
1180 return;
1181
1182 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1183 plist_del(&q->list, &hb->chain);
11d4616b 1184 hb_waiters_dec(hb);
2e12978a
LJ
1185}
1186
1da177e4
LT
1187/*
1188 * The hash bucket lock must be held when this is called.
1189 * Afterwards, the futex_q must not be accessed.
1190 */
1191static void wake_futex(struct futex_q *q)
1192{
f1a11e05
TG
1193 struct task_struct *p = q->task;
1194
aa10990e
DH
1195 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1196 return;
1197
1da177e4 1198 /*
f1a11e05 1199 * We set q->lock_ptr = NULL _before_ we wake up the task. If
fb62db2b
RD
1200 * a non-futex wake up happens on another CPU then the task
1201 * might exit and p would dereference a non-existing task
f1a11e05
TG
1202 * struct. Prevent this by holding a reference on p across the
1203 * wake up.
1da177e4 1204 */
f1a11e05
TG
1205 get_task_struct(p);
1206
2e12978a 1207 __unqueue_futex(q);
1da177e4 1208 /*
f1a11e05
TG
1209 * The waiting task can free the futex_q as soon as
1210 * q->lock_ptr = NULL is written, without taking any locks. A
1211 * memory barrier is required here to prevent the following
1212 * store to lock_ptr from getting ahead of the plist_del.
1da177e4 1213 */
ccdea2f8 1214 smp_wmb();
1da177e4 1215 q->lock_ptr = NULL;
f1a11e05
TG
1216
1217 wake_up_state(p, TASK_NORMAL);
1218 put_task_struct(p);
1da177e4
LT
1219}
1220
c87e2837
IM
1221static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
1222{
1223 struct task_struct *new_owner;
1224 struct futex_pi_state *pi_state = this->pi_state;
7cfdaf38 1225 u32 uninitialized_var(curval), newval;
13fbca4c 1226 int ret = 0;
c87e2837
IM
1227
1228 if (!pi_state)
1229 return -EINVAL;
1230
51246bfd
TG
1231 /*
1232 * If current does not own the pi_state then the futex is
1233 * inconsistent and user space fiddled with the futex value.
1234 */
1235 if (pi_state->owner != current)
1236 return -EINVAL;
1237
d209d74d 1238 raw_spin_lock(&pi_state->pi_mutex.wait_lock);
c87e2837
IM
1239 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
1240
1241 /*
f123c98e
SR
1242 * It is possible that the next waiter (the one that brought
1243 * this owner to the kernel) timed out and is no longer
1244 * waiting on the lock.
c87e2837
IM
1245 */
1246 if (!new_owner)
1247 new_owner = this->task;
1248
1249 /*
13fbca4c
TG
1250 * We pass it to the next owner. The WAITERS bit is always
1251 * kept enabled while there is PI state around. We cleanup the
1252 * owner died bit, because we are the owner.
c87e2837 1253 */
13fbca4c 1254 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
e3f2ddea 1255
13fbca4c
TG
1256 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
1257 ret = -EFAULT;
1258 else if (curval != uval)
1259 ret = -EINVAL;
1260 if (ret) {
1261 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
1262 return ret;
e3f2ddea 1263 }
c87e2837 1264
1d615482 1265 raw_spin_lock_irq(&pi_state->owner->pi_lock);
627371d7
IM
1266 WARN_ON(list_empty(&pi_state->list));
1267 list_del_init(&pi_state->list);
1d615482 1268 raw_spin_unlock_irq(&pi_state->owner->pi_lock);
627371d7 1269
1d615482 1270 raw_spin_lock_irq(&new_owner->pi_lock);
627371d7 1271 WARN_ON(!list_empty(&pi_state->list));
c87e2837
IM
1272 list_add(&pi_state->list, &new_owner->pi_state_list);
1273 pi_state->owner = new_owner;
1d615482 1274 raw_spin_unlock_irq(&new_owner->pi_lock);
627371d7 1275
d209d74d 1276 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
c87e2837
IM
1277 rt_mutex_unlock(&pi_state->pi_mutex);
1278
1279 return 0;
1280}
1281
1282static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
1283{
7cfdaf38 1284 u32 uninitialized_var(oldval);
c87e2837
IM
1285
1286 /*
1287 * There is no waiter, so we unlock the futex. The owner died
1288 * bit has not to be preserved here. We are the owner:
1289 */
37a9d912
ML
1290 if (cmpxchg_futex_value_locked(&oldval, uaddr, uval, 0))
1291 return -EFAULT;
c87e2837
IM
1292 if (oldval != uval)
1293 return -EAGAIN;
1294
1295 return 0;
1296}
1297
8b8f319f
IM
1298/*
1299 * Express the locking dependencies for lockdep:
1300 */
1301static inline void
1302double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1303{
1304 if (hb1 <= hb2) {
1305 spin_lock(&hb1->lock);
1306 if (hb1 < hb2)
1307 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1308 } else { /* hb1 > hb2 */
1309 spin_lock(&hb2->lock);
1310 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1311 }
1312}
1313
5eb3dc62
DH
1314static inline void
1315double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1316{
f061d351 1317 spin_unlock(&hb1->lock);
88f502fe
IM
1318 if (hb1 != hb2)
1319 spin_unlock(&hb2->lock);
5eb3dc62
DH
1320}
1321
1da177e4 1322/*
b2d0994b 1323 * Wake up waiters matching bitset queued on this futex (uaddr).
1da177e4 1324 */
b41277dc
DH
1325static int
1326futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1da177e4 1327{
e2970f2f 1328 struct futex_hash_bucket *hb;
1da177e4 1329 struct futex_q *this, *next;
38d47c1b 1330 union futex_key key = FUTEX_KEY_INIT;
1da177e4
LT
1331 int ret;
1332
cd689985
TG
1333 if (!bitset)
1334 return -EINVAL;
1335
9ea71503 1336 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
1da177e4
LT
1337 if (unlikely(ret != 0))
1338 goto out;
1339
e2970f2f 1340 hb = hash_futex(&key);
b0c29f79
DB
1341
1342 /* Make sure we really have tasks to wakeup */
1343 if (!hb_waiters_pending(hb))
1344 goto out_put_key;
1345
e2970f2f 1346 spin_lock(&hb->lock);
1da177e4 1347
0d00c7b2 1348 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1da177e4 1349 if (match_futex (&this->key, &key)) {
52400ba9 1350 if (this->pi_state || this->rt_waiter) {
ed6f7b10
IM
1351 ret = -EINVAL;
1352 break;
1353 }
cd689985
TG
1354
1355 /* Check if one of the bits is set in both bitsets */
1356 if (!(this->bitset & bitset))
1357 continue;
1358
1da177e4
LT
1359 wake_futex(this);
1360 if (++ret >= nr_wake)
1361 break;
1362 }
1363 }
1364
e2970f2f 1365 spin_unlock(&hb->lock);
b0c29f79 1366out_put_key:
ae791a2d 1367 put_futex_key(&key);
42d35d48 1368out:
1da177e4
LT
1369 return ret;
1370}
1371
4732efbe
JJ
1372/*
1373 * Wake up all waiters hashed on the physical page that is mapped
1374 * to this virtual address:
1375 */
e2970f2f 1376static int
b41277dc 1377futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
e2970f2f 1378 int nr_wake, int nr_wake2, int op)
4732efbe 1379{
38d47c1b 1380 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
e2970f2f 1381 struct futex_hash_bucket *hb1, *hb2;
4732efbe 1382 struct futex_q *this, *next;
e4dc5b7a 1383 int ret, op_ret;
4732efbe 1384
e4dc5b7a 1385retry:
9ea71503 1386 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
4732efbe
JJ
1387 if (unlikely(ret != 0))
1388 goto out;
9ea71503 1389 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
4732efbe 1390 if (unlikely(ret != 0))
42d35d48 1391 goto out_put_key1;
4732efbe 1392
e2970f2f
IM
1393 hb1 = hash_futex(&key1);
1394 hb2 = hash_futex(&key2);
4732efbe 1395
e4dc5b7a 1396retry_private:
eaaea803 1397 double_lock_hb(hb1, hb2);
e2970f2f 1398 op_ret = futex_atomic_op_inuser(op, uaddr2);
4732efbe 1399 if (unlikely(op_ret < 0)) {
4732efbe 1400
5eb3dc62 1401 double_unlock_hb(hb1, hb2);
4732efbe 1402
7ee1dd3f 1403#ifndef CONFIG_MMU
e2970f2f
IM
1404 /*
1405 * we don't get EFAULT from MMU faults if we don't have an MMU,
1406 * but we might get them from range checking
1407 */
7ee1dd3f 1408 ret = op_ret;
42d35d48 1409 goto out_put_keys;
7ee1dd3f
DH
1410#endif
1411
796f8d9b
DG
1412 if (unlikely(op_ret != -EFAULT)) {
1413 ret = op_ret;
42d35d48 1414 goto out_put_keys;
796f8d9b
DG
1415 }
1416
d0725992 1417 ret = fault_in_user_writeable(uaddr2);
4732efbe 1418 if (ret)
de87fcc1 1419 goto out_put_keys;
4732efbe 1420
b41277dc 1421 if (!(flags & FLAGS_SHARED))
e4dc5b7a
DH
1422 goto retry_private;
1423
ae791a2d
TG
1424 put_futex_key(&key2);
1425 put_futex_key(&key1);
e4dc5b7a 1426 goto retry;
4732efbe
JJ
1427 }
1428
0d00c7b2 1429 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
4732efbe 1430 if (match_futex (&this->key, &key1)) {
aa10990e
DH
1431 if (this->pi_state || this->rt_waiter) {
1432 ret = -EINVAL;
1433 goto out_unlock;
1434 }
4732efbe
JJ
1435 wake_futex(this);
1436 if (++ret >= nr_wake)
1437 break;
1438 }
1439 }
1440
1441 if (op_ret > 0) {
4732efbe 1442 op_ret = 0;
0d00c7b2 1443 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
4732efbe 1444 if (match_futex (&this->key, &key2)) {
aa10990e
DH
1445 if (this->pi_state || this->rt_waiter) {
1446 ret = -EINVAL;
1447 goto out_unlock;
1448 }
4732efbe
JJ
1449 wake_futex(this);
1450 if (++op_ret >= nr_wake2)
1451 break;
1452 }
1453 }
1454 ret += op_ret;
1455 }
1456
aa10990e 1457out_unlock:
5eb3dc62 1458 double_unlock_hb(hb1, hb2);
42d35d48 1459out_put_keys:
ae791a2d 1460 put_futex_key(&key2);
42d35d48 1461out_put_key1:
ae791a2d 1462 put_futex_key(&key1);
42d35d48 1463out:
4732efbe
JJ
1464 return ret;
1465}
1466
9121e478
DH
1467/**
1468 * requeue_futex() - Requeue a futex_q from one hb to another
1469 * @q: the futex_q to requeue
1470 * @hb1: the source hash_bucket
1471 * @hb2: the target hash_bucket
1472 * @key2: the new key for the requeued futex_q
1473 */
1474static inline
1475void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1476 struct futex_hash_bucket *hb2, union futex_key *key2)
1477{
1478
1479 /*
1480 * If key1 and key2 hash to the same bucket, no need to
1481 * requeue.
1482 */
1483 if (likely(&hb1->chain != &hb2->chain)) {
1484 plist_del(&q->list, &hb1->chain);
11d4616b 1485 hb_waiters_dec(hb1);
11d4616b 1486 hb_waiters_inc(hb2);
0fbf8e13 1487 plist_add(&q->list, &hb2->chain);
9121e478 1488 q->lock_ptr = &hb2->lock;
9121e478
DH
1489 }
1490 get_futex_key_refs(key2);
1491 q->key = *key2;
1492}
1493
52400ba9
DH
1494/**
1495 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
d96ee56c
DH
1496 * @q: the futex_q
1497 * @key: the key of the requeue target futex
1498 * @hb: the hash_bucket of the requeue target futex
52400ba9
DH
1499 *
1500 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1501 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1502 * to the requeue target futex so the waiter can detect the wakeup on the right
1503 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
beda2c7e
DH
1504 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1505 * to protect access to the pi_state to fixup the owner later. Must be called
1506 * with both q->lock_ptr and hb->lock held.
52400ba9
DH
1507 */
1508static inline
beda2c7e
DH
1509void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1510 struct futex_hash_bucket *hb)
52400ba9 1511{
52400ba9
DH
1512 get_futex_key_refs(key);
1513 q->key = *key;
1514
2e12978a 1515 __unqueue_futex(q);
52400ba9
DH
1516
1517 WARN_ON(!q->rt_waiter);
1518 q->rt_waiter = NULL;
1519
beda2c7e 1520 q->lock_ptr = &hb->lock;
beda2c7e 1521
f1a11e05 1522 wake_up_state(q->task, TASK_NORMAL);
52400ba9
DH
1523}
1524
1525/**
1526 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
bab5bc9e
DH
1527 * @pifutex: the user address of the to futex
1528 * @hb1: the from futex hash bucket, must be locked by the caller
1529 * @hb2: the to futex hash bucket, must be locked by the caller
1530 * @key1: the from futex key
1531 * @key2: the to futex key
1532 * @ps: address to store the pi_state pointer
1533 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
52400ba9
DH
1534 *
1535 * Try and get the lock on behalf of the top waiter if we can do it atomically.
bab5bc9e
DH
1536 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1537 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1538 * hb1 and hb2 must be held by the caller.
52400ba9 1539 *
6c23cbbd
RD
1540 * Return:
1541 * 0 - failed to acquire the lock atomically;
866293ee 1542 * >0 - acquired the lock, return value is vpid of the top_waiter
52400ba9
DH
1543 * <0 - error
1544 */
1545static int futex_proxy_trylock_atomic(u32 __user *pifutex,
1546 struct futex_hash_bucket *hb1,
1547 struct futex_hash_bucket *hb2,
1548 union futex_key *key1, union futex_key *key2,
bab5bc9e 1549 struct futex_pi_state **ps, int set_waiters)
52400ba9 1550{
bab5bc9e 1551 struct futex_q *top_waiter = NULL;
52400ba9 1552 u32 curval;
866293ee 1553 int ret, vpid;
52400ba9
DH
1554
1555 if (get_futex_value_locked(&curval, pifutex))
1556 return -EFAULT;
1557
bab5bc9e
DH
1558 /*
1559 * Find the top_waiter and determine if there are additional waiters.
1560 * If the caller intends to requeue more than 1 waiter to pifutex,
1561 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1562 * as we have means to handle the possible fault. If not, don't set
1563 * the bit unecessarily as it will force the subsequent unlock to enter
1564 * the kernel.
1565 */
52400ba9
DH
1566 top_waiter = futex_top_waiter(hb1, key1);
1567
1568 /* There are no waiters, nothing for us to do. */
1569 if (!top_waiter)
1570 return 0;
1571
84bc4af5
DH
1572 /* Ensure we requeue to the expected futex. */
1573 if (!match_futex(top_waiter->requeue_pi_key, key2))
1574 return -EINVAL;
1575
52400ba9 1576 /*
bab5bc9e
DH
1577 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1578 * the contended case or if set_waiters is 1. The pi_state is returned
1579 * in ps in contended cases.
52400ba9 1580 */
866293ee 1581 vpid = task_pid_vnr(top_waiter->task);
bab5bc9e
DH
1582 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1583 set_waiters);
866293ee 1584 if (ret == 1) {
beda2c7e 1585 requeue_pi_wake_futex(top_waiter, key2, hb2);
866293ee
TG
1586 return vpid;
1587 }
52400ba9
DH
1588 return ret;
1589}
1590
1591/**
1592 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
fb62db2b 1593 * @uaddr1: source futex user address
b41277dc 1594 * @flags: futex flags (FLAGS_SHARED, etc.)
fb62db2b
RD
1595 * @uaddr2: target futex user address
1596 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1597 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1598 * @cmpval: @uaddr1 expected value (or %NULL)
1599 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
b41277dc 1600 * pi futex (pi to pi requeue is not supported)
52400ba9
DH
1601 *
1602 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1603 * uaddr2 atomically on behalf of the top waiter.
1604 *
6c23cbbd
RD
1605 * Return:
1606 * >=0 - on success, the number of tasks requeued or woken;
52400ba9 1607 * <0 - on error
1da177e4 1608 */
b41277dc
DH
1609static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
1610 u32 __user *uaddr2, int nr_wake, int nr_requeue,
1611 u32 *cmpval, int requeue_pi)
1da177e4 1612{
38d47c1b 1613 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
52400ba9
DH
1614 int drop_count = 0, task_count = 0, ret;
1615 struct futex_pi_state *pi_state = NULL;
e2970f2f 1616 struct futex_hash_bucket *hb1, *hb2;
1da177e4 1617 struct futex_q *this, *next;
52400ba9 1618
762c02e6
LJ
1619 if (nr_wake < 0 || nr_requeue < 0)
1620 return -EINVAL;
1621
52400ba9 1622 if (requeue_pi) {
e9c243a5
TG
1623 /*
1624 * Requeue PI only works on two distinct uaddrs. This
1625 * check is only valid for private futexes. See below.
1626 */
1627 if (uaddr1 == uaddr2)
1628 return -EINVAL;
1629
52400ba9
DH
1630 /*
1631 * requeue_pi requires a pi_state, try to allocate it now
1632 * without any locks in case it fails.
1633 */
1634 if (refill_pi_state_cache())
1635 return -ENOMEM;
1636 /*
1637 * requeue_pi must wake as many tasks as it can, up to nr_wake
1638 * + nr_requeue, since it acquires the rt_mutex prior to
1639 * returning to userspace, so as to not leave the rt_mutex with
1640 * waiters and no owner. However, second and third wake-ups
1641 * cannot be predicted as they involve race conditions with the
1642 * first wake and a fault while looking up the pi_state. Both
1643 * pthread_cond_signal() and pthread_cond_broadcast() should
1644 * use nr_wake=1.
1645 */
1646 if (nr_wake != 1)
1647 return -EINVAL;
1648 }
1da177e4 1649
42d35d48 1650retry:
9ea71503 1651 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
1da177e4
LT
1652 if (unlikely(ret != 0))
1653 goto out;
9ea71503
SB
1654 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
1655 requeue_pi ? VERIFY_WRITE : VERIFY_READ);
1da177e4 1656 if (unlikely(ret != 0))
42d35d48 1657 goto out_put_key1;
1da177e4 1658
e9c243a5
TG
1659 /*
1660 * The check above which compares uaddrs is not sufficient for
1661 * shared futexes. We need to compare the keys:
1662 */
1663 if (requeue_pi && match_futex(&key1, &key2)) {
1664 ret = -EINVAL;
1665 goto out_put_keys;
1666 }
1667
e2970f2f
IM
1668 hb1 = hash_futex(&key1);
1669 hb2 = hash_futex(&key2);
1da177e4 1670
e4dc5b7a 1671retry_private:
69cd9eba 1672 hb_waiters_inc(hb2);
8b8f319f 1673 double_lock_hb(hb1, hb2);
1da177e4 1674
e2970f2f
IM
1675 if (likely(cmpval != NULL)) {
1676 u32 curval;
1da177e4 1677
e2970f2f 1678 ret = get_futex_value_locked(&curval, uaddr1);
1da177e4
LT
1679
1680 if (unlikely(ret)) {
5eb3dc62 1681 double_unlock_hb(hb1, hb2);
69cd9eba 1682 hb_waiters_dec(hb2);
1da177e4 1683
e2970f2f 1684 ret = get_user(curval, uaddr1);
e4dc5b7a
DH
1685 if (ret)
1686 goto out_put_keys;
1da177e4 1687
b41277dc 1688 if (!(flags & FLAGS_SHARED))
e4dc5b7a 1689 goto retry_private;
1da177e4 1690
ae791a2d
TG
1691 put_futex_key(&key2);
1692 put_futex_key(&key1);
e4dc5b7a 1693 goto retry;
1da177e4 1694 }
e2970f2f 1695 if (curval != *cmpval) {
1da177e4
LT
1696 ret = -EAGAIN;
1697 goto out_unlock;
1698 }
1699 }
1700
52400ba9 1701 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
bab5bc9e
DH
1702 /*
1703 * Attempt to acquire uaddr2 and wake the top waiter. If we
1704 * intend to requeue waiters, force setting the FUTEX_WAITERS
1705 * bit. We force this here where we are able to easily handle
1706 * faults rather in the requeue loop below.
1707 */
52400ba9 1708 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
bab5bc9e 1709 &key2, &pi_state, nr_requeue);
52400ba9
DH
1710
1711 /*
1712 * At this point the top_waiter has either taken uaddr2 or is
1713 * waiting on it. If the former, then the pi_state will not
1714 * exist yet, look it up one more time to ensure we have a
866293ee
TG
1715 * reference to it. If the lock was taken, ret contains the
1716 * vpid of the top waiter task.
52400ba9 1717 */
866293ee 1718 if (ret > 0) {
52400ba9 1719 WARN_ON(pi_state);
89061d3d 1720 drop_count++;
52400ba9 1721 task_count++;
866293ee
TG
1722 /*
1723 * If we acquired the lock, then the user
1724 * space value of uaddr2 should be vpid. It
1725 * cannot be changed by the top waiter as it
1726 * is blocked on hb2 lock if it tries to do
1727 * so. If something fiddled with it behind our
1728 * back the pi state lookup might unearth
1729 * it. So we rather use the known value than
1730 * rereading and handing potential crap to
1731 * lookup_pi_state.
1732 */
54a21788 1733 ret = lookup_pi_state(ret, hb2, &key2, &pi_state);
52400ba9
DH
1734 }
1735
1736 switch (ret) {
1737 case 0:
1738 break;
1739 case -EFAULT:
6af5729d
BS
1740 free_pi_state(pi_state);
1741 pi_state = NULL;
52400ba9 1742 double_unlock_hb(hb1, hb2);
69cd9eba 1743 hb_waiters_dec(hb2);
ae791a2d
TG
1744 put_futex_key(&key2);
1745 put_futex_key(&key1);
d0725992 1746 ret = fault_in_user_writeable(uaddr2);
52400ba9
DH
1747 if (!ret)
1748 goto retry;
1749 goto out;
1750 case -EAGAIN:
1751 /* The owner was exiting, try again. */
6af5729d
BS
1752 free_pi_state(pi_state);
1753 pi_state = NULL;
52400ba9 1754 double_unlock_hb(hb1, hb2);
69cd9eba 1755 hb_waiters_dec(hb2);
ae791a2d
TG
1756 put_futex_key(&key2);
1757 put_futex_key(&key1);
52400ba9
DH
1758 cond_resched();
1759 goto retry;
1760 default:
1761 goto out_unlock;
1762 }
1763 }
1764
0d00c7b2 1765 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
52400ba9
DH
1766 if (task_count - nr_wake >= nr_requeue)
1767 break;
1768
1769 if (!match_futex(&this->key, &key1))
1da177e4 1770 continue;
52400ba9 1771
392741e0
DH
1772 /*
1773 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
1774 * be paired with each other and no other futex ops.
aa10990e
DH
1775 *
1776 * We should never be requeueing a futex_q with a pi_state,
1777 * which is awaiting a futex_unlock_pi().
392741e0
DH
1778 */
1779 if ((requeue_pi && !this->rt_waiter) ||
aa10990e
DH
1780 (!requeue_pi && this->rt_waiter) ||
1781 this->pi_state) {
392741e0
DH
1782 ret = -EINVAL;
1783 break;
1784 }
52400ba9
DH
1785
1786 /*
1787 * Wake nr_wake waiters. For requeue_pi, if we acquired the
1788 * lock, we already woke the top_waiter. If not, it will be
1789 * woken by futex_unlock_pi().
1790 */
1791 if (++task_count <= nr_wake && !requeue_pi) {
1da177e4 1792 wake_futex(this);
52400ba9
DH
1793 continue;
1794 }
1da177e4 1795
84bc4af5
DH
1796 /* Ensure we requeue to the expected futex for requeue_pi. */
1797 if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
1798 ret = -EINVAL;
1799 break;
1800 }
1801
52400ba9
DH
1802 /*
1803 * Requeue nr_requeue waiters and possibly one more in the case
1804 * of requeue_pi if we couldn't acquire the lock atomically.
1805 */
1806 if (requeue_pi) {
1807 /* Prepare the waiter to take the rt_mutex. */
1808 atomic_inc(&pi_state->refcount);
1809 this->pi_state = pi_state;
1810 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
1811 this->rt_waiter,
1812 this->task, 1);
1813 if (ret == 1) {
1814 /* We got the lock. */
beda2c7e 1815 requeue_pi_wake_futex(this, &key2, hb2);
89061d3d 1816 drop_count++;
52400ba9
DH
1817 continue;
1818 } else if (ret) {
1819 /* -EDEADLK */
1820 this->pi_state = NULL;
1821 free_pi_state(pi_state);
1822 goto out_unlock;
1823 }
1da177e4 1824 }
52400ba9
DH
1825 requeue_futex(this, hb1, hb2, &key2);
1826 drop_count++;
1da177e4
LT
1827 }
1828
1829out_unlock:
6af5729d 1830 free_pi_state(pi_state);
5eb3dc62 1831 double_unlock_hb(hb1, hb2);
69cd9eba 1832 hb_waiters_dec(hb2);
1da177e4 1833
cd84a42f
DH
1834 /*
1835 * drop_futex_key_refs() must be called outside the spinlocks. During
1836 * the requeue we moved futex_q's from the hash bucket at key1 to the
1837 * one at key2 and updated their key pointer. We no longer need to
1838 * hold the references to key1.
1839 */
1da177e4 1840 while (--drop_count >= 0)
9adef58b 1841 drop_futex_key_refs(&key1);
1da177e4 1842
42d35d48 1843out_put_keys:
ae791a2d 1844 put_futex_key(&key2);
42d35d48 1845out_put_key1:
ae791a2d 1846 put_futex_key(&key1);
42d35d48 1847out:
52400ba9 1848 return ret ? ret : task_count;
1da177e4
LT
1849}
1850
1851/* The key must be already stored in q->key. */
82af7aca 1852static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
15e408cd 1853 __acquires(&hb->lock)
1da177e4 1854{
e2970f2f 1855 struct futex_hash_bucket *hb;
1da177e4 1856
e2970f2f 1857 hb = hash_futex(&q->key);
11d4616b
LT
1858
1859 /*
1860 * Increment the counter before taking the lock so that
1861 * a potential waker won't miss a to-be-slept task that is
1862 * waiting for the spinlock. This is safe as all queue_lock()
1863 * users end up calling queue_me(). Similarly, for housekeeping,
1864 * decrement the counter at queue_unlock() when some error has
1865 * occurred and we don't end up adding the task to the list.
1866 */
1867 hb_waiters_inc(hb);
1868
e2970f2f 1869 q->lock_ptr = &hb->lock;
1da177e4 1870
b0c29f79 1871 spin_lock(&hb->lock); /* implies MB (A) */
e2970f2f 1872 return hb;
1da177e4
LT
1873}
1874
d40d65c8 1875static inline void
0d00c7b2 1876queue_unlock(struct futex_hash_bucket *hb)
15e408cd 1877 __releases(&hb->lock)
d40d65c8
DH
1878{
1879 spin_unlock(&hb->lock);
11d4616b 1880 hb_waiters_dec(hb);
d40d65c8
DH
1881}
1882
1883/**
1884 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
1885 * @q: The futex_q to enqueue
1886 * @hb: The destination hash bucket
1887 *
1888 * The hb->lock must be held by the caller, and is released here. A call to
1889 * queue_me() is typically paired with exactly one call to unqueue_me(). The
1890 * exceptions involve the PI related operations, which may use unqueue_me_pi()
1891 * or nothing if the unqueue is done as part of the wake process and the unqueue
1892 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
1893 * an example).
1894 */
82af7aca 1895static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
15e408cd 1896 __releases(&hb->lock)
1da177e4 1897{
ec92d082
PP
1898 int prio;
1899
1900 /*
1901 * The priority used to register this element is
1902 * - either the real thread-priority for the real-time threads
1903 * (i.e. threads with a priority lower than MAX_RT_PRIO)
1904 * - or MAX_RT_PRIO for non-RT threads.
1905 * Thus, all RT-threads are woken first in priority order, and
1906 * the others are woken last, in FIFO order.
1907 */
1908 prio = min(current->normal_prio, MAX_RT_PRIO);
1909
1910 plist_node_init(&q->list, prio);
ec92d082 1911 plist_add(&q->list, &hb->chain);
c87e2837 1912 q->task = current;
e2970f2f 1913 spin_unlock(&hb->lock);
1da177e4
LT
1914}
1915
d40d65c8
DH
1916/**
1917 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
1918 * @q: The futex_q to unqueue
1919 *
1920 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
1921 * be paired with exactly one earlier call to queue_me().
1922 *
6c23cbbd
RD
1923 * Return:
1924 * 1 - if the futex_q was still queued (and we removed unqueued it);
d40d65c8 1925 * 0 - if the futex_q was already removed by the waking thread
1da177e4 1926 */
1da177e4
LT
1927static int unqueue_me(struct futex_q *q)
1928{
1da177e4 1929 spinlock_t *lock_ptr;
e2970f2f 1930 int ret = 0;
1da177e4
LT
1931
1932 /* In the common case we don't take the spinlock, which is nice. */
42d35d48 1933retry:
1da177e4 1934 lock_ptr = q->lock_ptr;
e91467ec 1935 barrier();
c80544dc 1936 if (lock_ptr != NULL) {
1da177e4
LT
1937 spin_lock(lock_ptr);
1938 /*
1939 * q->lock_ptr can change between reading it and
1940 * spin_lock(), causing us to take the wrong lock. This
1941 * corrects the race condition.
1942 *
1943 * Reasoning goes like this: if we have the wrong lock,
1944 * q->lock_ptr must have changed (maybe several times)
1945 * between reading it and the spin_lock(). It can
1946 * change again after the spin_lock() but only if it was
1947 * already changed before the spin_lock(). It cannot,
1948 * however, change back to the original value. Therefore
1949 * we can detect whether we acquired the correct lock.
1950 */
1951 if (unlikely(lock_ptr != q->lock_ptr)) {
1952 spin_unlock(lock_ptr);
1953 goto retry;
1954 }
2e12978a 1955 __unqueue_futex(q);
c87e2837
IM
1956
1957 BUG_ON(q->pi_state);
1958
1da177e4
LT
1959 spin_unlock(lock_ptr);
1960 ret = 1;
1961 }
1962
9adef58b 1963 drop_futex_key_refs(&q->key);
1da177e4
LT
1964 return ret;
1965}
1966
c87e2837
IM
1967/*
1968 * PI futexes can not be requeued and must remove themself from the
d0aa7a70
PP
1969 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1970 * and dropped here.
c87e2837 1971 */
d0aa7a70 1972static void unqueue_me_pi(struct futex_q *q)
15e408cd 1973 __releases(q->lock_ptr)
c87e2837 1974{
2e12978a 1975 __unqueue_futex(q);
c87e2837
IM
1976
1977 BUG_ON(!q->pi_state);
1978 free_pi_state(q->pi_state);
1979 q->pi_state = NULL;
1980
d0aa7a70 1981 spin_unlock(q->lock_ptr);
c87e2837
IM
1982}
1983
d0aa7a70 1984/*
cdf71a10 1985 * Fixup the pi_state owner with the new owner.
d0aa7a70 1986 *
778e9a9c
AK
1987 * Must be called with hash bucket lock held and mm->sem held for non
1988 * private futexes.
d0aa7a70 1989 */
778e9a9c 1990static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
ae791a2d 1991 struct task_struct *newowner)
d0aa7a70 1992{
cdf71a10 1993 u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
d0aa7a70 1994 struct futex_pi_state *pi_state = q->pi_state;
1b7558e4 1995 struct task_struct *oldowner = pi_state->owner;
7cfdaf38 1996 u32 uval, uninitialized_var(curval), newval;
e4dc5b7a 1997 int ret;
d0aa7a70
PP
1998
1999 /* Owner died? */
1b7558e4
TG
2000 if (!pi_state->owner)
2001 newtid |= FUTEX_OWNER_DIED;
2002
2003 /*
2004 * We are here either because we stole the rtmutex from the
8161239a
LJ
2005 * previous highest priority waiter or we are the highest priority
2006 * waiter but failed to get the rtmutex the first time.
2007 * We have to replace the newowner TID in the user space variable.
2008 * This must be atomic as we have to preserve the owner died bit here.
1b7558e4 2009 *
b2d0994b
DH
2010 * Note: We write the user space value _before_ changing the pi_state
2011 * because we can fault here. Imagine swapped out pages or a fork
2012 * that marked all the anonymous memory readonly for cow.
1b7558e4
TG
2013 *
2014 * Modifying pi_state _before_ the user space value would
2015 * leave the pi_state in an inconsistent state when we fault
2016 * here, because we need to drop the hash bucket lock to
2017 * handle the fault. This might be observed in the PID check
2018 * in lookup_pi_state.
2019 */
2020retry:
2021 if (get_futex_value_locked(&uval, uaddr))
2022 goto handle_fault;
2023
2024 while (1) {
2025 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2026
37a9d912 2027 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
1b7558e4
TG
2028 goto handle_fault;
2029 if (curval == uval)
2030 break;
2031 uval = curval;
2032 }
2033
2034 /*
2035 * We fixed up user space. Now we need to fix the pi_state
2036 * itself.
2037 */
d0aa7a70 2038 if (pi_state->owner != NULL) {
1d615482 2039 raw_spin_lock_irq(&pi_state->owner->pi_lock);
d0aa7a70
PP
2040 WARN_ON(list_empty(&pi_state->list));
2041 list_del_init(&pi_state->list);
1d615482 2042 raw_spin_unlock_irq(&pi_state->owner->pi_lock);
1b7558e4 2043 }
d0aa7a70 2044
cdf71a10 2045 pi_state->owner = newowner;
d0aa7a70 2046
1d615482 2047 raw_spin_lock_irq(&newowner->pi_lock);
d0aa7a70 2048 WARN_ON(!list_empty(&pi_state->list));
cdf71a10 2049 list_add(&pi_state->list, &newowner->pi_state_list);
1d615482 2050 raw_spin_unlock_irq(&newowner->pi_lock);
1b7558e4 2051 return 0;
d0aa7a70 2052
d0aa7a70 2053 /*
1b7558e4 2054 * To handle the page fault we need to drop the hash bucket
8161239a
LJ
2055 * lock here. That gives the other task (either the highest priority
2056 * waiter itself or the task which stole the rtmutex) the
1b7558e4
TG
2057 * chance to try the fixup of the pi_state. So once we are
2058 * back from handling the fault we need to check the pi_state
2059 * after reacquiring the hash bucket lock and before trying to
2060 * do another fixup. When the fixup has been done already we
2061 * simply return.
d0aa7a70 2062 */
1b7558e4
TG
2063handle_fault:
2064 spin_unlock(q->lock_ptr);
778e9a9c 2065
d0725992 2066 ret = fault_in_user_writeable(uaddr);
778e9a9c 2067
1b7558e4 2068 spin_lock(q->lock_ptr);
778e9a9c 2069
1b7558e4
TG
2070 /*
2071 * Check if someone else fixed it for us:
2072 */
2073 if (pi_state->owner != oldowner)
2074 return 0;
2075
2076 if (ret)
2077 return ret;
2078
2079 goto retry;
d0aa7a70
PP
2080}
2081
72c1bbf3 2082static long futex_wait_restart(struct restart_block *restart);
36cf3b5c 2083
dd973998
DH
2084/**
2085 * fixup_owner() - Post lock pi_state and corner case management
2086 * @uaddr: user address of the futex
dd973998
DH
2087 * @q: futex_q (contains pi_state and access to the rt_mutex)
2088 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2089 *
2090 * After attempting to lock an rt_mutex, this function is called to cleanup
2091 * the pi_state owner as well as handle race conditions that may allow us to
2092 * acquire the lock. Must be called with the hb lock held.
2093 *
6c23cbbd
RD
2094 * Return:
2095 * 1 - success, lock taken;
2096 * 0 - success, lock not taken;
dd973998
DH
2097 * <0 - on error (-EFAULT)
2098 */
ae791a2d 2099static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
dd973998
DH
2100{
2101 struct task_struct *owner;
2102 int ret = 0;
2103
2104 if (locked) {
2105 /*
2106 * Got the lock. We might not be the anticipated owner if we
2107 * did a lock-steal - fix up the PI-state in that case:
2108 */
2109 if (q->pi_state->owner != current)
ae791a2d 2110 ret = fixup_pi_state_owner(uaddr, q, current);
dd973998
DH
2111 goto out;
2112 }
2113
2114 /*
2115 * Catch the rare case, where the lock was released when we were on the
2116 * way back before we locked the hash bucket.
2117 */
2118 if (q->pi_state->owner == current) {
2119 /*
2120 * Try to get the rt_mutex now. This might fail as some other
2121 * task acquired the rt_mutex after we removed ourself from the
2122 * rt_mutex waiters list.
2123 */
2124 if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
2125 locked = 1;
2126 goto out;
2127 }
2128
2129 /*
2130 * pi_state is incorrect, some other task did a lock steal and
2131 * we returned due to timeout or signal without taking the
8161239a 2132 * rt_mutex. Too late.
dd973998 2133 */
8161239a 2134 raw_spin_lock(&q->pi_state->pi_mutex.wait_lock);
dd973998 2135 owner = rt_mutex_owner(&q->pi_state->pi_mutex);
8161239a
LJ
2136 if (!owner)
2137 owner = rt_mutex_next_owner(&q->pi_state->pi_mutex);
2138 raw_spin_unlock(&q->pi_state->pi_mutex.wait_lock);
ae791a2d 2139 ret = fixup_pi_state_owner(uaddr, q, owner);
dd973998
DH
2140 goto out;
2141 }
2142
2143 /*
2144 * Paranoia check. If we did not take the lock, then we should not be
8161239a 2145 * the owner of the rt_mutex.
dd973998
DH
2146 */
2147 if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
2148 printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
2149 "pi-state %p\n", ret,
2150 q->pi_state->pi_mutex.owner,
2151 q->pi_state->owner);
2152
2153out:
2154 return ret ? ret : locked;
2155}
2156
ca5f9524
DH
2157/**
2158 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2159 * @hb: the futex hash bucket, must be locked by the caller
2160 * @q: the futex_q to queue up on
2161 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
ca5f9524
DH
2162 */
2163static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
f1a11e05 2164 struct hrtimer_sleeper *timeout)
ca5f9524 2165{
9beba3c5
DH
2166 /*
2167 * The task state is guaranteed to be set before another task can
2168 * wake it. set_current_state() is implemented using set_mb() and
2169 * queue_me() calls spin_unlock() upon completion, both serializing
2170 * access to the hash list and forcing another memory barrier.
2171 */
f1a11e05 2172 set_current_state(TASK_INTERRUPTIBLE);
0729e196 2173 queue_me(q, hb);
ca5f9524
DH
2174
2175 /* Arm the timer */
2176 if (timeout) {
2177 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
2178 if (!hrtimer_active(&timeout->timer))
2179 timeout->task = NULL;
2180 }
2181
2182 /*
0729e196
DH
2183 * If we have been removed from the hash list, then another task
2184 * has tried to wake us, and we can skip the call to schedule().
ca5f9524
DH
2185 */
2186 if (likely(!plist_node_empty(&q->list))) {
2187 /*
2188 * If the timer has already expired, current will already be
2189 * flagged for rescheduling. Only call schedule if there
2190 * is no timeout, or if it has yet to expire.
2191 */
2192 if (!timeout || timeout->task)
88c8004f 2193 freezable_schedule();
ca5f9524
DH
2194 }
2195 __set_current_state(TASK_RUNNING);
2196}
2197
f801073f
DH
2198/**
2199 * futex_wait_setup() - Prepare to wait on a futex
2200 * @uaddr: the futex userspace address
2201 * @val: the expected value
b41277dc 2202 * @flags: futex flags (FLAGS_SHARED, etc.)
f801073f
DH
2203 * @q: the associated futex_q
2204 * @hb: storage for hash_bucket pointer to be returned to caller
2205 *
2206 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2207 * compare it with the expected value. Handle atomic faults internally.
2208 * Return with the hb lock held and a q.key reference on success, and unlocked
2209 * with no q.key reference on failure.
2210 *
6c23cbbd
RD
2211 * Return:
2212 * 0 - uaddr contains val and hb has been locked;
ca4a04cf 2213 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
f801073f 2214 */
b41277dc 2215static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
f801073f 2216 struct futex_q *q, struct futex_hash_bucket **hb)
1da177e4 2217{
e2970f2f
IM
2218 u32 uval;
2219 int ret;
1da177e4 2220
1da177e4 2221 /*
b2d0994b 2222 * Access the page AFTER the hash-bucket is locked.
1da177e4
LT
2223 * Order is important:
2224 *
2225 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2226 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2227 *
2228 * The basic logical guarantee of a futex is that it blocks ONLY
2229 * if cond(var) is known to be true at the time of blocking, for
8fe8f545
ML
2230 * any cond. If we locked the hash-bucket after testing *uaddr, that
2231 * would open a race condition where we could block indefinitely with
1da177e4
LT
2232 * cond(var) false, which would violate the guarantee.
2233 *
8fe8f545
ML
2234 * On the other hand, we insert q and release the hash-bucket only
2235 * after testing *uaddr. This guarantees that futex_wait() will NOT
2236 * absorb a wakeup if *uaddr does not match the desired values
2237 * while the syscall executes.
1da177e4 2238 */
f801073f 2239retry:
9ea71503 2240 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
f801073f 2241 if (unlikely(ret != 0))
a5a2a0c7 2242 return ret;
f801073f
DH
2243
2244retry_private:
2245 *hb = queue_lock(q);
2246
e2970f2f 2247 ret = get_futex_value_locked(&uval, uaddr);
1da177e4 2248
f801073f 2249 if (ret) {
0d00c7b2 2250 queue_unlock(*hb);
1da177e4 2251
e2970f2f 2252 ret = get_user(uval, uaddr);
e4dc5b7a 2253 if (ret)
f801073f 2254 goto out;
1da177e4 2255
b41277dc 2256 if (!(flags & FLAGS_SHARED))
e4dc5b7a
DH
2257 goto retry_private;
2258
ae791a2d 2259 put_futex_key(&q->key);
e4dc5b7a 2260 goto retry;
1da177e4 2261 }
ca5f9524 2262
f801073f 2263 if (uval != val) {
0d00c7b2 2264 queue_unlock(*hb);
f801073f 2265 ret = -EWOULDBLOCK;
2fff78c7 2266 }
1da177e4 2267
f801073f
DH
2268out:
2269 if (ret)
ae791a2d 2270 put_futex_key(&q->key);
f801073f
DH
2271 return ret;
2272}
2273
b41277dc
DH
2274static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2275 ktime_t *abs_time, u32 bitset)
f801073f
DH
2276{
2277 struct hrtimer_sleeper timeout, *to = NULL;
f801073f
DH
2278 struct restart_block *restart;
2279 struct futex_hash_bucket *hb;
5bdb05f9 2280 struct futex_q q = futex_q_init;
f801073f
DH
2281 int ret;
2282
2283 if (!bitset)
2284 return -EINVAL;
f801073f
DH
2285 q.bitset = bitset;
2286
2287 if (abs_time) {
2288 to = &timeout;
2289
b41277dc
DH
2290 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2291 CLOCK_REALTIME : CLOCK_MONOTONIC,
2292 HRTIMER_MODE_ABS);
f801073f
DH
2293 hrtimer_init_sleeper(to, current);
2294 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2295 current->timer_slack_ns);
2296 }
2297
d58e6576 2298retry:
7ada876a
DH
2299 /*
2300 * Prepare to wait on uaddr. On success, holds hb lock and increments
2301 * q.key refs.
2302 */
b41277dc 2303 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
f801073f
DH
2304 if (ret)
2305 goto out;
2306
ca5f9524 2307 /* queue_me and wait for wakeup, timeout, or a signal. */
f1a11e05 2308 futex_wait_queue_me(hb, &q, to);
1da177e4
LT
2309
2310 /* If we were woken (and unqueued), we succeeded, whatever. */
2fff78c7 2311 ret = 0;
7ada876a 2312 /* unqueue_me() drops q.key ref */
1da177e4 2313 if (!unqueue_me(&q))
7ada876a 2314 goto out;
2fff78c7 2315 ret = -ETIMEDOUT;
ca5f9524 2316 if (to && !to->task)
7ada876a 2317 goto out;
72c1bbf3 2318
e2970f2f 2319 /*
d58e6576
TG
2320 * We expect signal_pending(current), but we might be the
2321 * victim of a spurious wakeup as well.
e2970f2f 2322 */
7ada876a 2323 if (!signal_pending(current))
d58e6576 2324 goto retry;
d58e6576 2325
2fff78c7 2326 ret = -ERESTARTSYS;
c19384b5 2327 if (!abs_time)
7ada876a 2328 goto out;
1da177e4 2329
2fff78c7
PZ
2330 restart = &current_thread_info()->restart_block;
2331 restart->fn = futex_wait_restart;
a3c74c52 2332 restart->futex.uaddr = uaddr;
2fff78c7
PZ
2333 restart->futex.val = val;
2334 restart->futex.time = abs_time->tv64;
2335 restart->futex.bitset = bitset;
0cd9c649 2336 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
42d35d48 2337
2fff78c7
PZ
2338 ret = -ERESTART_RESTARTBLOCK;
2339
42d35d48 2340out:
ca5f9524
DH
2341 if (to) {
2342 hrtimer_cancel(&to->timer);
2343 destroy_hrtimer_on_stack(&to->timer);
2344 }
c87e2837
IM
2345 return ret;
2346}
2347
72c1bbf3
NP
2348
2349static long futex_wait_restart(struct restart_block *restart)
2350{
a3c74c52 2351 u32 __user *uaddr = restart->futex.uaddr;
a72188d8 2352 ktime_t t, *tp = NULL;
72c1bbf3 2353
a72188d8
DH
2354 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2355 t.tv64 = restart->futex.time;
2356 tp = &t;
2357 }
72c1bbf3 2358 restart->fn = do_no_restart_syscall;
b41277dc
DH
2359
2360 return (long)futex_wait(uaddr, restart->futex.flags,
2361 restart->futex.val, tp, restart->futex.bitset);
72c1bbf3
NP
2362}
2363
2364
c87e2837
IM
2365/*
2366 * Userspace tried a 0 -> TID atomic transition of the futex value
2367 * and failed. The kernel side here does the whole locking operation:
2368 * if there are waiters then it will block, it does PI, etc. (Due to
2369 * races the kernel might see a 0 value of the futex too.)
2370 */
b41277dc
DH
2371static int futex_lock_pi(u32 __user *uaddr, unsigned int flags, int detect,
2372 ktime_t *time, int trylock)
c87e2837 2373{
c5780e97 2374 struct hrtimer_sleeper timeout, *to = NULL;
c87e2837 2375 struct futex_hash_bucket *hb;
5bdb05f9 2376 struct futex_q q = futex_q_init;
dd973998 2377 int res, ret;
c87e2837
IM
2378
2379 if (refill_pi_state_cache())
2380 return -ENOMEM;
2381
c19384b5 2382 if (time) {
c5780e97 2383 to = &timeout;
237fc6e7
TG
2384 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
2385 HRTIMER_MODE_ABS);
c5780e97 2386 hrtimer_init_sleeper(to, current);
cc584b21 2387 hrtimer_set_expires(&to->timer, *time);
c5780e97
TG
2388 }
2389
42d35d48 2390retry:
9ea71503 2391 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
c87e2837 2392 if (unlikely(ret != 0))
42d35d48 2393 goto out;
c87e2837 2394
e4dc5b7a 2395retry_private:
82af7aca 2396 hb = queue_lock(&q);
c87e2837 2397
bab5bc9e 2398 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
c87e2837 2399 if (unlikely(ret)) {
778e9a9c 2400 switch (ret) {
1a52084d
DH
2401 case 1:
2402 /* We got the lock. */
2403 ret = 0;
2404 goto out_unlock_put_key;
2405 case -EFAULT:
2406 goto uaddr_faulted;
778e9a9c
AK
2407 case -EAGAIN:
2408 /*
2409 * Task is exiting and we just wait for the
2410 * exit to complete.
2411 */
0d00c7b2 2412 queue_unlock(hb);
ae791a2d 2413 put_futex_key(&q.key);
778e9a9c
AK
2414 cond_resched();
2415 goto retry;
778e9a9c 2416 default:
42d35d48 2417 goto out_unlock_put_key;
c87e2837 2418 }
c87e2837
IM
2419 }
2420
2421 /*
2422 * Only actually queue now that the atomic ops are done:
2423 */
82af7aca 2424 queue_me(&q, hb);
c87e2837 2425
c87e2837
IM
2426 WARN_ON(!q.pi_state);
2427 /*
2428 * Block on the PI mutex:
2429 */
2430 if (!trylock)
2431 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
2432 else {
2433 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
2434 /* Fixup the trylock return value: */
2435 ret = ret ? 0 : -EWOULDBLOCK;
2436 }
2437
a99e4e41 2438 spin_lock(q.lock_ptr);
dd973998
DH
2439 /*
2440 * Fixup the pi_state owner and possibly acquire the lock if we
2441 * haven't already.
2442 */
ae791a2d 2443 res = fixup_owner(uaddr, &q, !ret);
dd973998
DH
2444 /*
2445 * If fixup_owner() returned an error, proprogate that. If it acquired
2446 * the lock, clear our -ETIMEDOUT or -EINTR.
2447 */
2448 if (res)
2449 ret = (res < 0) ? res : 0;
c87e2837 2450
e8f6386c 2451 /*
dd973998
DH
2452 * If fixup_owner() faulted and was unable to handle the fault, unlock
2453 * it and return the fault to userspace.
e8f6386c
DH
2454 */
2455 if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
2456 rt_mutex_unlock(&q.pi_state->pi_mutex);
2457
778e9a9c
AK
2458 /* Unqueue and drop the lock */
2459 unqueue_me_pi(&q);
c87e2837 2460
5ecb01cf 2461 goto out_put_key;
c87e2837 2462
42d35d48 2463out_unlock_put_key:
0d00c7b2 2464 queue_unlock(hb);
c87e2837 2465
42d35d48 2466out_put_key:
ae791a2d 2467 put_futex_key(&q.key);
42d35d48 2468out:
237fc6e7
TG
2469 if (to)
2470 destroy_hrtimer_on_stack(&to->timer);
dd973998 2471 return ret != -EINTR ? ret : -ERESTARTNOINTR;
c87e2837 2472
42d35d48 2473uaddr_faulted:
0d00c7b2 2474 queue_unlock(hb);
778e9a9c 2475
d0725992 2476 ret = fault_in_user_writeable(uaddr);
e4dc5b7a
DH
2477 if (ret)
2478 goto out_put_key;
c87e2837 2479
b41277dc 2480 if (!(flags & FLAGS_SHARED))
e4dc5b7a
DH
2481 goto retry_private;
2482
ae791a2d 2483 put_futex_key(&q.key);
e4dc5b7a 2484 goto retry;
c87e2837
IM
2485}
2486
c87e2837
IM
2487/*
2488 * Userspace attempted a TID -> 0 atomic transition, and failed.
2489 * This is the in-kernel slowpath: we look up the PI state (if any),
2490 * and do the rt-mutex unlock.
2491 */
b41277dc 2492static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
c87e2837
IM
2493{
2494 struct futex_hash_bucket *hb;
2495 struct futex_q *this, *next;
38d47c1b 2496 union futex_key key = FUTEX_KEY_INIT;
c0c9ed15 2497 u32 uval, vpid = task_pid_vnr(current);
e4dc5b7a 2498 int ret;
c87e2837
IM
2499
2500retry:
2501 if (get_user(uval, uaddr))
2502 return -EFAULT;
2503 /*
2504 * We release only a lock we actually own:
2505 */
c0c9ed15 2506 if ((uval & FUTEX_TID_MASK) != vpid)
c87e2837 2507 return -EPERM;
c87e2837 2508
9ea71503 2509 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
c87e2837
IM
2510 if (unlikely(ret != 0))
2511 goto out;
2512
2513 hb = hash_futex(&key);
2514 spin_lock(&hb->lock);
2515
c87e2837
IM
2516 /*
2517 * To avoid races, try to do the TID -> 0 atomic transition
2518 * again. If it succeeds then we can return without waking
13fbca4c
TG
2519 * anyone else up. We only try this if neither the waiters nor
2520 * the owner died bit are set.
c87e2837 2521 */
13fbca4c 2522 if (!(uval & ~FUTEX_TID_MASK) &&
37a9d912 2523 cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0))
c87e2837
IM
2524 goto pi_faulted;
2525 /*
2526 * Rare case: we managed to release the lock atomically,
2527 * no need to wake anyone else up:
2528 */
c0c9ed15 2529 if (unlikely(uval == vpid))
c87e2837
IM
2530 goto out_unlock;
2531
2532 /*
2533 * Ok, other tasks may need to be woken up - check waiters
2534 * and do the wakeup if necessary:
2535 */
0d00c7b2 2536 plist_for_each_entry_safe(this, next, &hb->chain, list) {
c87e2837
IM
2537 if (!match_futex (&this->key, &key))
2538 continue;
2539 ret = wake_futex_pi(uaddr, uval, this);
2540 /*
2541 * The atomic access to the futex value
2542 * generated a pagefault, so retry the
2543 * user-access and the wakeup:
2544 */
2545 if (ret == -EFAULT)
2546 goto pi_faulted;
2547 goto out_unlock;
2548 }
2549 /*
2550 * No waiters - kernel unlocks the futex:
2551 */
13fbca4c
TG
2552 ret = unlock_futex_pi(uaddr, uval);
2553 if (ret == -EFAULT)
2554 goto pi_faulted;
c87e2837
IM
2555
2556out_unlock:
2557 spin_unlock(&hb->lock);
ae791a2d 2558 put_futex_key(&key);
c87e2837 2559
42d35d48 2560out:
c87e2837
IM
2561 return ret;
2562
2563pi_faulted:
778e9a9c 2564 spin_unlock(&hb->lock);
ae791a2d 2565 put_futex_key(&key);
c87e2837 2566
d0725992 2567 ret = fault_in_user_writeable(uaddr);
b5686363 2568 if (!ret)
c87e2837
IM
2569 goto retry;
2570
1da177e4
LT
2571 return ret;
2572}
2573
52400ba9
DH
2574/**
2575 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
2576 * @hb: the hash_bucket futex_q was original enqueued on
2577 * @q: the futex_q woken while waiting to be requeued
2578 * @key2: the futex_key of the requeue target futex
2579 * @timeout: the timeout associated with the wait (NULL if none)
2580 *
2581 * Detect if the task was woken on the initial futex as opposed to the requeue
2582 * target futex. If so, determine if it was a timeout or a signal that caused
2583 * the wakeup and return the appropriate error code to the caller. Must be
2584 * called with the hb lock held.
2585 *
6c23cbbd
RD
2586 * Return:
2587 * 0 = no early wakeup detected;
2588 * <0 = -ETIMEDOUT or -ERESTARTNOINTR
52400ba9
DH
2589 */
2590static inline
2591int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
2592 struct futex_q *q, union futex_key *key2,
2593 struct hrtimer_sleeper *timeout)
2594{
2595 int ret = 0;
2596
2597 /*
2598 * With the hb lock held, we avoid races while we process the wakeup.
2599 * We only need to hold hb (and not hb2) to ensure atomicity as the
2600 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
2601 * It can't be requeued from uaddr2 to something else since we don't
2602 * support a PI aware source futex for requeue.
2603 */
2604 if (!match_futex(&q->key, key2)) {
2605 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
2606 /*
2607 * We were woken prior to requeue by a timeout or a signal.
2608 * Unqueue the futex_q and determine which it was.
2609 */
2e12978a 2610 plist_del(&q->list, &hb->chain);
11d4616b 2611 hb_waiters_dec(hb);
52400ba9 2612
d58e6576 2613 /* Handle spurious wakeups gracefully */
11df6ddd 2614 ret = -EWOULDBLOCK;
52400ba9
DH
2615 if (timeout && !timeout->task)
2616 ret = -ETIMEDOUT;
d58e6576 2617 else if (signal_pending(current))
1c840c14 2618 ret = -ERESTARTNOINTR;
52400ba9
DH
2619 }
2620 return ret;
2621}
2622
2623/**
2624 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
56ec1607 2625 * @uaddr: the futex we initially wait on (non-pi)
b41277dc 2626 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
52400ba9
DH
2627 * the same type, no requeueing from private to shared, etc.
2628 * @val: the expected value of uaddr
2629 * @abs_time: absolute timeout
56ec1607 2630 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
52400ba9
DH
2631 * @uaddr2: the pi futex we will take prior to returning to user-space
2632 *
2633 * The caller will wait on uaddr and will be requeued by futex_requeue() to
6f7b0a2a
DH
2634 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
2635 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
2636 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
2637 * without one, the pi logic would not know which task to boost/deboost, if
2638 * there was a need to.
52400ba9
DH
2639 *
2640 * We call schedule in futex_wait_queue_me() when we enqueue and return there
6c23cbbd 2641 * via the following--
52400ba9 2642 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
cc6db4e6
DH
2643 * 2) wakeup on uaddr2 after a requeue
2644 * 3) signal
2645 * 4) timeout
52400ba9 2646 *
cc6db4e6 2647 * If 3, cleanup and return -ERESTARTNOINTR.
52400ba9
DH
2648 *
2649 * If 2, we may then block on trying to take the rt_mutex and return via:
2650 * 5) successful lock
2651 * 6) signal
2652 * 7) timeout
2653 * 8) other lock acquisition failure
2654 *
cc6db4e6 2655 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
52400ba9
DH
2656 *
2657 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
2658 *
6c23cbbd
RD
2659 * Return:
2660 * 0 - On success;
52400ba9
DH
2661 * <0 - On error
2662 */
b41277dc 2663static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
52400ba9 2664 u32 val, ktime_t *abs_time, u32 bitset,
b41277dc 2665 u32 __user *uaddr2)
52400ba9
DH
2666{
2667 struct hrtimer_sleeper timeout, *to = NULL;
2668 struct rt_mutex_waiter rt_waiter;
52400ba9 2669 struct futex_hash_bucket *hb;
5bdb05f9
DH
2670 union futex_key key2 = FUTEX_KEY_INIT;
2671 struct futex_q q = futex_q_init;
52400ba9 2672 int res, ret;
52400ba9 2673
6f7b0a2a
DH
2674 if (uaddr == uaddr2)
2675 return -EINVAL;
2676
52400ba9
DH
2677 if (!bitset)
2678 return -EINVAL;
2679
2680 if (abs_time) {
2681 to = &timeout;
b41277dc
DH
2682 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2683 CLOCK_REALTIME : CLOCK_MONOTONIC,
2684 HRTIMER_MODE_ABS);
52400ba9
DH
2685 hrtimer_init_sleeper(to, current);
2686 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2687 current->timer_slack_ns);
2688 }
2689
2690 /*
2691 * The waiter is allocated on our stack, manipulated by the requeue
2692 * code while we sleep on uaddr.
2693 */
2694 debug_rt_mutex_init_waiter(&rt_waiter);
fb00aca4
PZ
2695 RB_CLEAR_NODE(&rt_waiter.pi_tree_entry);
2696 RB_CLEAR_NODE(&rt_waiter.tree_entry);
52400ba9
DH
2697 rt_waiter.task = NULL;
2698
9ea71503 2699 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
52400ba9
DH
2700 if (unlikely(ret != 0))
2701 goto out;
2702
84bc4af5
DH
2703 q.bitset = bitset;
2704 q.rt_waiter = &rt_waiter;
2705 q.requeue_pi_key = &key2;
2706
7ada876a
DH
2707 /*
2708 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
2709 * count.
2710 */
b41277dc 2711 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
c8b15a70
TG
2712 if (ret)
2713 goto out_key2;
52400ba9 2714
e9c243a5
TG
2715 /*
2716 * The check above which compares uaddrs is not sufficient for
2717 * shared futexes. We need to compare the keys:
2718 */
2719 if (match_futex(&q.key, &key2)) {
31512f8b 2720 queue_unlock(hb);
e9c243a5
TG
2721 ret = -EINVAL;
2722 goto out_put_keys;
2723 }
2724
52400ba9 2725 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
f1a11e05 2726 futex_wait_queue_me(hb, &q, to);
52400ba9
DH
2727
2728 spin_lock(&hb->lock);
2729 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
2730 spin_unlock(&hb->lock);
2731 if (ret)
2732 goto out_put_keys;
2733
2734 /*
2735 * In order for us to be here, we know our q.key == key2, and since
2736 * we took the hb->lock above, we also know that futex_requeue() has
2737 * completed and we no longer have to concern ourselves with a wakeup
7ada876a
DH
2738 * race with the atomic proxy lock acquisition by the requeue code. The
2739 * futex_requeue dropped our key1 reference and incremented our key2
2740 * reference count.
52400ba9
DH
2741 */
2742
2743 /* Check if the requeue code acquired the second futex for us. */
2744 if (!q.rt_waiter) {
2745 /*
2746 * Got the lock. We might not be the anticipated owner if we
2747 * did a lock-steal - fix up the PI-state in that case.
2748 */
2749 if (q.pi_state && (q.pi_state->owner != current)) {
2750 spin_lock(q.lock_ptr);
ae791a2d 2751 ret = fixup_pi_state_owner(uaddr2, &q, current);
da04cecb
PZ
2752 if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current)
2753 rt_mutex_unlock(&q.pi_state->pi_mutex);
c05e790e
TG
2754 /*
2755 * Drop the reference to the pi state which
2756 * the requeue_pi() code acquired for us.
2757 */
2758 free_pi_state(q.pi_state);
52400ba9
DH
2759 spin_unlock(q.lock_ptr);
2760 }
2761 } else {
bdeee63c
PZ
2762 struct rt_mutex *pi_mutex;
2763
52400ba9
DH
2764 /*
2765 * We have been woken up by futex_unlock_pi(), a timeout, or a
2766 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
2767 * the pi_state.
2768 */
f27071cb 2769 WARN_ON(!q.pi_state);
52400ba9
DH
2770 pi_mutex = &q.pi_state->pi_mutex;
2771 ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);
2772 debug_rt_mutex_free_waiter(&rt_waiter);
2773
2774 spin_lock(q.lock_ptr);
2775 /*
2776 * Fixup the pi_state owner and possibly acquire the lock if we
2777 * haven't already.
2778 */
ae791a2d 2779 res = fixup_owner(uaddr2, &q, !ret);
52400ba9
DH
2780 /*
2781 * If fixup_owner() returned an error, proprogate that. If it
56ec1607 2782 * acquired the lock, clear -ETIMEDOUT or -EINTR.
52400ba9
DH
2783 */
2784 if (res)
2785 ret = (res < 0) ? res : 0;
2786
bdeee63c
PZ
2787 /*
2788 * If fixup_pi_state_owner() faulted and was unable to handle
2789 * the fault, unlock the rt_mutex and return the fault to
2790 * userspace.
2791 */
2792 if (ret && rt_mutex_owner(pi_mutex) == current)
2793 rt_mutex_unlock(pi_mutex);
2794
52400ba9
DH
2795 /* Unqueue and drop the lock. */
2796 unqueue_me_pi(&q);
2797 }
2798
bdeee63c 2799 if (ret == -EINTR) {
52400ba9 2800 /*
cc6db4e6
DH
2801 * We've already been requeued, but cannot restart by calling
2802 * futex_lock_pi() directly. We could restart this syscall, but
2803 * it would detect that the user space "val" changed and return
2804 * -EWOULDBLOCK. Save the overhead of the restart and return
2805 * -EWOULDBLOCK directly.
52400ba9 2806 */
2070887f 2807 ret = -EWOULDBLOCK;
52400ba9
DH
2808 }
2809
2810out_put_keys:
ae791a2d 2811 put_futex_key(&q.key);
c8b15a70 2812out_key2:
ae791a2d 2813 put_futex_key(&key2);
52400ba9
DH
2814
2815out:
2816 if (to) {
2817 hrtimer_cancel(&to->timer);
2818 destroy_hrtimer_on_stack(&to->timer);
2819 }
2820 return ret;
2821}
2822
0771dfef
IM
2823/*
2824 * Support for robust futexes: the kernel cleans up held futexes at
2825 * thread exit time.
2826 *
2827 * Implementation: user-space maintains a per-thread list of locks it
2828 * is holding. Upon do_exit(), the kernel carefully walks this list,
2829 * and marks all locks that are owned by this thread with the
c87e2837 2830 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
0771dfef
IM
2831 * always manipulated with the lock held, so the list is private and
2832 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
2833 * field, to allow the kernel to clean up if the thread dies after
2834 * acquiring the lock, but just before it could have added itself to
2835 * the list. There can only be one such pending lock.
2836 */
2837
2838/**
d96ee56c
DH
2839 * sys_set_robust_list() - Set the robust-futex list head of a task
2840 * @head: pointer to the list-head
2841 * @len: length of the list-head, as userspace expects
0771dfef 2842 */
836f92ad
HC
2843SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
2844 size_t, len)
0771dfef 2845{
a0c1e907
TG
2846 if (!futex_cmpxchg_enabled)
2847 return -ENOSYS;
0771dfef
IM
2848 /*
2849 * The kernel knows only one size for now:
2850 */
2851 if (unlikely(len != sizeof(*head)))
2852 return -EINVAL;
2853
2854 current->robust_list = head;
2855
2856 return 0;
2857}
2858
2859/**
d96ee56c
DH
2860 * sys_get_robust_list() - Get the robust-futex list head of a task
2861 * @pid: pid of the process [zero for current task]
2862 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
2863 * @len_ptr: pointer to a length field, the kernel fills in the header size
0771dfef 2864 */
836f92ad
HC
2865SYSCALL_DEFINE3(get_robust_list, int, pid,
2866 struct robust_list_head __user * __user *, head_ptr,
2867 size_t __user *, len_ptr)
0771dfef 2868{
ba46df98 2869 struct robust_list_head __user *head;
0771dfef 2870 unsigned long ret;
bdbb776f 2871 struct task_struct *p;
0771dfef 2872
a0c1e907
TG
2873 if (!futex_cmpxchg_enabled)
2874 return -ENOSYS;
2875
bdbb776f
KC
2876 rcu_read_lock();
2877
2878 ret = -ESRCH;
0771dfef 2879 if (!pid)
bdbb776f 2880 p = current;
0771dfef 2881 else {
228ebcbe 2882 p = find_task_by_vpid(pid);
0771dfef
IM
2883 if (!p)
2884 goto err_unlock;
0771dfef
IM
2885 }
2886
bdbb776f 2887 ret = -EPERM;
229aba44 2888 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
bdbb776f
KC
2889 goto err_unlock;
2890
2891 head = p->robust_list;
2892 rcu_read_unlock();
2893
0771dfef
IM
2894 if (put_user(sizeof(*head), len_ptr))
2895 return -EFAULT;
2896 return put_user(head, head_ptr);
2897
2898err_unlock:
aaa2a97e 2899 rcu_read_unlock();
0771dfef
IM
2900
2901 return ret;
2902}
2903
2904/*
2905 * Process a futex-list entry, check whether it's owned by the
2906 * dying task, and do notification if so:
2907 */
e3f2ddea 2908int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
0771dfef 2909{
7cfdaf38 2910 u32 uval, uninitialized_var(nval), mval;
0771dfef 2911
8f17d3a5
IM
2912retry:
2913 if (get_user(uval, uaddr))
0771dfef
IM
2914 return -1;
2915
b488893a 2916 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
0771dfef
IM
2917 /*
2918 * Ok, this dying thread is truly holding a futex
2919 * of interest. Set the OWNER_DIED bit atomically
2920 * via cmpxchg, and if the value had FUTEX_WAITERS
2921 * set, wake up a waiter (if any). (We have to do a
2922 * futex_wake() even if OWNER_DIED is already set -
2923 * to handle the rare but possible case of recursive
2924 * thread-death.) The rest of the cleanup is done in
2925 * userspace.
2926 */
e3f2ddea 2927 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
6e0aa9f8
TG
2928 /*
2929 * We are not holding a lock here, but we want to have
2930 * the pagefault_disable/enable() protection because
2931 * we want to handle the fault gracefully. If the
2932 * access fails we try to fault in the futex with R/W
2933 * verification via get_user_pages. get_user() above
2934 * does not guarantee R/W access. If that fails we
2935 * give up and leave the futex locked.
2936 */
2937 if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
2938 if (fault_in_user_writeable(uaddr))
2939 return -1;
2940 goto retry;
2941 }
c87e2837 2942 if (nval != uval)
8f17d3a5 2943 goto retry;
0771dfef 2944
e3f2ddea
IM
2945 /*
2946 * Wake robust non-PI futexes here. The wakeup of
2947 * PI futexes happens in exit_pi_state():
2948 */
36cf3b5c 2949 if (!pi && (uval & FUTEX_WAITERS))
c2f9f201 2950 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
0771dfef
IM
2951 }
2952 return 0;
2953}
2954
e3f2ddea
IM
2955/*
2956 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
2957 */
2958static inline int fetch_robust_entry(struct robust_list __user **entry,
ba46df98 2959 struct robust_list __user * __user *head,
1dcc41bb 2960 unsigned int *pi)
e3f2ddea
IM
2961{
2962 unsigned long uentry;
2963
ba46df98 2964 if (get_user(uentry, (unsigned long __user *)head))
e3f2ddea
IM
2965 return -EFAULT;
2966
ba46df98 2967 *entry = (void __user *)(uentry & ~1UL);
e3f2ddea
IM
2968 *pi = uentry & 1;
2969
2970 return 0;
2971}
2972
0771dfef
IM
2973/*
2974 * Walk curr->robust_list (very carefully, it's a userspace list!)
2975 * and mark any locks found there dead, and notify any waiters.
2976 *
2977 * We silently return on any sign of list-walking problem.
2978 */
2979void exit_robust_list(struct task_struct *curr)
2980{
2981 struct robust_list_head __user *head = curr->robust_list;
9f96cb1e 2982 struct robust_list __user *entry, *next_entry, *pending;
4c115e95
DH
2983 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
2984 unsigned int uninitialized_var(next_pi);
0771dfef 2985 unsigned long futex_offset;
9f96cb1e 2986 int rc;
0771dfef 2987
a0c1e907
TG
2988 if (!futex_cmpxchg_enabled)
2989 return;
2990
0771dfef
IM
2991 /*
2992 * Fetch the list head (which was registered earlier, via
2993 * sys_set_robust_list()):
2994 */
e3f2ddea 2995 if (fetch_robust_entry(&entry, &head->list.next, &pi))
0771dfef
IM
2996 return;
2997 /*
2998 * Fetch the relative futex offset:
2999 */
3000 if (get_user(futex_offset, &head->futex_offset))
3001 return;
3002 /*
3003 * Fetch any possibly pending lock-add first, and handle it
3004 * if it exists:
3005 */
e3f2ddea 3006 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
0771dfef 3007 return;
e3f2ddea 3008
9f96cb1e 3009 next_entry = NULL; /* avoid warning with gcc */
0771dfef 3010 while (entry != &head->list) {
9f96cb1e
MS
3011 /*
3012 * Fetch the next entry in the list before calling
3013 * handle_futex_death:
3014 */
3015 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
0771dfef
IM
3016 /*
3017 * A pending lock might already be on the list, so
c87e2837 3018 * don't process it twice:
0771dfef
IM
3019 */
3020 if (entry != pending)
ba46df98 3021 if (handle_futex_death((void __user *)entry + futex_offset,
e3f2ddea 3022 curr, pi))
0771dfef 3023 return;
9f96cb1e 3024 if (rc)
0771dfef 3025 return;
9f96cb1e
MS
3026 entry = next_entry;
3027 pi = next_pi;
0771dfef
IM
3028 /*
3029 * Avoid excessively long or circular lists:
3030 */
3031 if (!--limit)
3032 break;
3033
3034 cond_resched();
3035 }
9f96cb1e
MS
3036
3037 if (pending)
3038 handle_futex_death((void __user *)pending + futex_offset,
3039 curr, pip);
0771dfef
IM
3040}
3041
c19384b5 3042long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
e2970f2f 3043 u32 __user *uaddr2, u32 val2, u32 val3)
1da177e4 3044{
81b40539 3045 int cmd = op & FUTEX_CMD_MASK;
b41277dc 3046 unsigned int flags = 0;
34f01cc1
ED
3047
3048 if (!(op & FUTEX_PRIVATE_FLAG))
b41277dc 3049 flags |= FLAGS_SHARED;
1da177e4 3050
b41277dc
DH
3051 if (op & FUTEX_CLOCK_REALTIME) {
3052 flags |= FLAGS_CLOCKRT;
3053 if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
3054 return -ENOSYS;
3055 }
1da177e4 3056
59263b51
TG
3057 switch (cmd) {
3058 case FUTEX_LOCK_PI:
3059 case FUTEX_UNLOCK_PI:
3060 case FUTEX_TRYLOCK_PI:
3061 case FUTEX_WAIT_REQUEUE_PI:
3062 case FUTEX_CMP_REQUEUE_PI:
3063 if (!futex_cmpxchg_enabled)
3064 return -ENOSYS;
3065 }
3066
34f01cc1 3067 switch (cmd) {
1da177e4 3068 case FUTEX_WAIT:
cd689985
TG
3069 val3 = FUTEX_BITSET_MATCH_ANY;
3070 case FUTEX_WAIT_BITSET:
81b40539 3071 return futex_wait(uaddr, flags, val, timeout, val3);
1da177e4 3072 case FUTEX_WAKE:
cd689985
TG
3073 val3 = FUTEX_BITSET_MATCH_ANY;
3074 case FUTEX_WAKE_BITSET:
81b40539 3075 return futex_wake(uaddr, flags, val, val3);
1da177e4 3076 case FUTEX_REQUEUE:
81b40539 3077 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
1da177e4 3078 case FUTEX_CMP_REQUEUE:
81b40539 3079 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
4732efbe 3080 case FUTEX_WAKE_OP:
81b40539 3081 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
c87e2837 3082 case FUTEX_LOCK_PI:
81b40539 3083 return futex_lock_pi(uaddr, flags, val, timeout, 0);
c87e2837 3084 case FUTEX_UNLOCK_PI:
81b40539 3085 return futex_unlock_pi(uaddr, flags);
c87e2837 3086 case FUTEX_TRYLOCK_PI:
81b40539 3087 return futex_lock_pi(uaddr, flags, 0, timeout, 1);
52400ba9
DH
3088 case FUTEX_WAIT_REQUEUE_PI:
3089 val3 = FUTEX_BITSET_MATCH_ANY;
81b40539
TG
3090 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3091 uaddr2);
52400ba9 3092 case FUTEX_CMP_REQUEUE_PI:
81b40539 3093 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
1da177e4 3094 }
81b40539 3095 return -ENOSYS;
1da177e4
LT
3096}
3097
3098
17da2bd9
HC
3099SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3100 struct timespec __user *, utime, u32 __user *, uaddr2,
3101 u32, val3)
1da177e4 3102{
c19384b5
PP
3103 struct timespec ts;
3104 ktime_t t, *tp = NULL;
e2970f2f 3105 u32 val2 = 0;
34f01cc1 3106 int cmd = op & FUTEX_CMD_MASK;
1da177e4 3107
cd689985 3108 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
52400ba9
DH
3109 cmd == FUTEX_WAIT_BITSET ||
3110 cmd == FUTEX_WAIT_REQUEUE_PI)) {
c19384b5 3111 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
1da177e4 3112 return -EFAULT;
c19384b5 3113 if (!timespec_valid(&ts))
9741ef96 3114 return -EINVAL;
c19384b5
PP
3115
3116 t = timespec_to_ktime(ts);
34f01cc1 3117 if (cmd == FUTEX_WAIT)
5a7780e7 3118 t = ktime_add_safe(ktime_get(), t);
c19384b5 3119 tp = &t;
1da177e4
LT
3120 }
3121 /*
52400ba9 3122 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
f54f0986 3123 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
1da177e4 3124 */
f54f0986 3125 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
ba9c22f2 3126 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
e2970f2f 3127 val2 = (u32) (unsigned long) utime;
1da177e4 3128
c19384b5 3129 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
1da177e4
LT
3130}
3131
03b8c7b6 3132static void __init futex_detect_cmpxchg(void)
1da177e4 3133{
03b8c7b6 3134#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
a0c1e907 3135 u32 curval;
03b8c7b6
HC
3136
3137 /*
3138 * This will fail and we want it. Some arch implementations do
3139 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3140 * functionality. We want to know that before we call in any
3141 * of the complex code paths. Also we want to prevent
3142 * registration of robust lists in that case. NULL is
3143 * guaranteed to fault and we get -EFAULT on functional
3144 * implementation, the non-functional ones will return
3145 * -ENOSYS.
3146 */
3147 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
3148 futex_cmpxchg_enabled = 1;
3149#endif
3150}
3151
3152static int __init futex_init(void)
3153{
63b1a816 3154 unsigned int futex_shift;
a52b89eb
DB
3155 unsigned long i;
3156
3157#if CONFIG_BASE_SMALL
3158 futex_hashsize = 16;
3159#else
3160 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
3161#endif
3162
3163 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
3164 futex_hashsize, 0,
3165 futex_hashsize < 256 ? HASH_SMALL : 0,
63b1a816
HC
3166 &futex_shift, NULL,
3167 futex_hashsize, futex_hashsize);
3168 futex_hashsize = 1UL << futex_shift;
03b8c7b6
HC
3169
3170 futex_detect_cmpxchg();
a0c1e907 3171
a52b89eb 3172 for (i = 0; i < futex_hashsize; i++) {
11d4616b 3173 atomic_set(&futex_queues[i].waiters, 0);
732375c6 3174 plist_head_init(&futex_queues[i].chain);
3e4ab747
TG
3175 spin_lock_init(&futex_queues[i].lock);
3176 }
3177
1da177e4
LT
3178 return 0;
3179}
dcc9b826 3180core_initcall(futex_init);