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