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 *
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/compat.h>
48 #include <linux/slab.h>
49 #include <linux/poll.h>
50 #include <linux/fs.h>
51 #include <linux/file.h>
52 #include <linux/jhash.h>
53 #include <linux/init.h>
54 #include <linux/futex.h>
55 #include <linux/mount.h>
56 #include <linux/pagemap.h>
57 #include <linux/syscalls.h>
58 #include <linux/signal.h>
59 #include <linux/export.h>
60 #include <linux/magic.h>
61 #include <linux/pid.h>
62 #include <linux/nsproxy.h>
63 #include <linux/ptrace.h>
64 #include <linux/sched/rt.h>
65 #include <linux/hugetlb.h>
66 #include <linux/freezer.h>
67 #include <linux/bootmem.h>
68 #include <linux/fault-inject.h>
69
70 #include <asm/futex.h>
71
72 #include "locking/rtmutex_common.h"
73
74 /*
75 * READ this before attempting to hack on futexes!
76 *
77 * Basic futex operation and ordering guarantees
78 * =============================================
79 *
80 * The waiter reads the futex value in user space and calls
81 * futex_wait(). This function computes the hash bucket and acquires
82 * the hash bucket lock. After that it reads the futex user space value
83 * again and verifies that the data has not changed. If it has not changed
84 * it enqueues itself into the hash bucket, releases the hash bucket lock
85 * and schedules.
86 *
87 * The waker side modifies the user space value of the futex and calls
88 * futex_wake(). This function computes the hash bucket and acquires the
89 * hash bucket lock. Then it looks for waiters on that futex in the hash
90 * bucket and wakes them.
91 *
92 * In futex wake up scenarios where no tasks are blocked on a futex, taking
93 * the hb spinlock can be avoided and simply return. In order for this
94 * optimization to work, ordering guarantees must exist so that the waiter
95 * being added to the list is acknowledged when the list is concurrently being
96 * checked by the waker, avoiding scenarios like the following:
97 *
98 * CPU 0 CPU 1
99 * val = *futex;
100 * sys_futex(WAIT, futex, val);
101 * futex_wait(futex, val);
102 * uval = *futex;
103 * *futex = newval;
104 * sys_futex(WAKE, futex);
105 * futex_wake(futex);
106 * if (queue_empty())
107 * return;
108 * if (uval == val)
109 * lock(hash_bucket(futex));
110 * queue();
111 * unlock(hash_bucket(futex));
112 * schedule();
113 *
114 * This would cause the waiter on CPU 0 to wait forever because it
115 * missed the transition of the user space value from val to newval
116 * and the waker did not find the waiter in the hash bucket queue.
117 *
118 * The correct serialization ensures that a waiter either observes
119 * the changed user space value before blocking or is woken by a
120 * concurrent waker:
121 *
122 * CPU 0 CPU 1
123 * val = *futex;
124 * sys_futex(WAIT, futex, val);
125 * futex_wait(futex, val);
126 *
127 * waiters++; (a)
128 * mb(); (A) <-- paired with -.
129 * |
130 * lock(hash_bucket(futex)); |
131 * |
132 * uval = *futex; |
133 * | *futex = newval;
134 * | sys_futex(WAKE, futex);
135 * | futex_wake(futex);
136 * |
137 * `-------> mb(); (B)
138 * if (uval == val)
139 * queue();
140 * unlock(hash_bucket(futex));
141 * schedule(); if (waiters)
142 * lock(hash_bucket(futex));
143 * else wake_waiters(futex);
144 * waiters--; (b) unlock(hash_bucket(futex));
145 *
146 * Where (A) orders the waiters increment and the futex value read through
147 * atomic operations (see hb_waiters_inc) and where (B) orders the write
148 * to futex and the waiters read -- this is done by the barriers for both
149 * shared and private futexes in get_futex_key_refs().
150 *
151 * This yields the following case (where X:=waiters, Y:=futex):
152 *
153 * X = Y = 0
154 *
155 * w[X]=1 w[Y]=1
156 * MB MB
157 * r[Y]=y r[X]=x
158 *
159 * Which guarantees that x==0 && y==0 is impossible; which translates back into
160 * the guarantee that we cannot both miss the futex variable change and the
161 * enqueue.
162 *
163 * Note that a new waiter is accounted for in (a) even when it is possible that
164 * the wait call can return error, in which case we backtrack from it in (b).
165 * Refer to the comment in queue_lock().
166 *
167 * Similarly, in order to account for waiters being requeued on another
168 * address we always increment the waiters for the destination bucket before
169 * acquiring the lock. It then decrements them again after releasing it -
170 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
171 * will do the additional required waiter count housekeeping. This is done for
172 * double_lock_hb() and double_unlock_hb(), respectively.
173 */
174
175 #ifdef CONFIG_HAVE_FUTEX_CMPXCHG
176 #define futex_cmpxchg_enabled 1
177 #else
178 static int __read_mostly futex_cmpxchg_enabled;
179 #endif
180
181 /*
182 * Futex flags used to encode options to functions and preserve them across
183 * restarts.
184 */
185 #define FLAGS_SHARED 0x01
186 #define FLAGS_CLOCKRT 0x02
187 #define FLAGS_HAS_TIMEOUT 0x04
188
189 /*
190 * Priority Inheritance state:
191 */
192 struct futex_pi_state {
193 /*
194 * list of 'owned' pi_state instances - these have to be
195 * cleaned up in do_exit() if the task exits prematurely:
196 */
197 struct list_head list;
198
199 /*
200 * The PI object:
201 */
202 struct rt_mutex pi_mutex;
203
204 struct task_struct *owner;
205 atomic_t refcount;
206
207 union futex_key key;
208 };
209
210 /**
211 * struct futex_q - The hashed futex queue entry, one per waiting task
212 * @list: priority-sorted list of tasks waiting on this futex
213 * @task: the task waiting on the futex
214 * @lock_ptr: the hash bucket lock
215 * @key: the key the futex is hashed on
216 * @pi_state: optional priority inheritance state
217 * @rt_waiter: rt_waiter storage for use with requeue_pi
218 * @requeue_pi_key: the requeue_pi target futex key
219 * @bitset: bitset for the optional bitmasked wakeup
220 *
221 * We use this hashed waitqueue, instead of a normal wait_queue_t, so
222 * we can wake only the relevant ones (hashed queues may be shared).
223 *
224 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
225 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
226 * The order of wakeup is always to make the first condition true, then
227 * the second.
228 *
229 * PI futexes are typically woken before they are removed from the hash list via
230 * the rt_mutex code. See unqueue_me_pi().
231 */
232 struct futex_q {
233 struct plist_node list;
234
235 struct task_struct *task;
236 spinlock_t *lock_ptr;
237 union futex_key key;
238 struct futex_pi_state *pi_state;
239 struct rt_mutex_waiter *rt_waiter;
240 union futex_key *requeue_pi_key;
241 u32 bitset;
242 };
243
244 static const struct futex_q futex_q_init = {
245 /* list gets initialized in queue_me()*/
246 .key = FUTEX_KEY_INIT,
247 .bitset = FUTEX_BITSET_MATCH_ANY
248 };
249
250 /*
251 * Hash buckets are shared by all the futex_keys that hash to the same
252 * location. Each key may have multiple futex_q structures, one for each task
253 * waiting on a futex.
254 */
255 struct futex_hash_bucket {
256 atomic_t waiters;
257 spinlock_t lock;
258 struct plist_head chain;
259 } ____cacheline_aligned_in_smp;
260
261 /*
262 * The base of the bucket array and its size are always used together
263 * (after initialization only in hash_futex()), so ensure that they
264 * reside in the same cacheline.
265 */
266 static struct {
267 struct futex_hash_bucket *queues;
268 unsigned long hashsize;
269 } __futex_data __read_mostly __aligned(2*sizeof(long));
270 #define futex_queues (__futex_data.queues)
271 #define futex_hashsize (__futex_data.hashsize)
272
273
274 /*
275 * Fault injections for futexes.
276 */
277 #ifdef CONFIG_FAIL_FUTEX
278
279 static struct {
280 struct fault_attr attr;
281
282 bool ignore_private;
283 } fail_futex = {
284 .attr = FAULT_ATTR_INITIALIZER,
285 .ignore_private = false,
286 };
287
setup_fail_futex(char * str)288 static int __init setup_fail_futex(char *str)
289 {
290 return setup_fault_attr(&fail_futex.attr, str);
291 }
292 __setup("fail_futex=", setup_fail_futex);
293
should_fail_futex(bool fshared)294 static bool should_fail_futex(bool fshared)
295 {
296 if (fail_futex.ignore_private && !fshared)
297 return false;
298
299 return should_fail(&fail_futex.attr, 1);
300 }
301
302 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
303
fail_futex_debugfs(void)304 static int __init fail_futex_debugfs(void)
305 {
306 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
307 struct dentry *dir;
308
309 dir = fault_create_debugfs_attr("fail_futex", NULL,
310 &fail_futex.attr);
311 if (IS_ERR(dir))
312 return PTR_ERR(dir);
313
314 if (!debugfs_create_bool("ignore-private", mode, dir,
315 &fail_futex.ignore_private)) {
316 debugfs_remove_recursive(dir);
317 return -ENOMEM;
318 }
319
320 return 0;
321 }
322
323 late_initcall(fail_futex_debugfs);
324
325 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
326
327 #else
should_fail_futex(bool fshared)328 static inline bool should_fail_futex(bool fshared)
329 {
330 return false;
331 }
332 #endif /* CONFIG_FAIL_FUTEX */
333
334 #ifdef CONFIG_COMPAT
335 static void compat_exit_robust_list(struct task_struct *curr);
336 #else
compat_exit_robust_list(struct task_struct * curr)337 static inline void compat_exit_robust_list(struct task_struct *curr) { }
338 #endif
339
futex_get_mm(union futex_key * key)340 static inline void futex_get_mm(union futex_key *key)
341 {
342 atomic_inc(&key->private.mm->mm_count);
343 /*
344 * Ensure futex_get_mm() implies a full barrier such that
345 * get_futex_key() implies a full barrier. This is relied upon
346 * as full barrier (B), see the ordering comment above.
347 */
348 smp_mb__after_atomic();
349 }
350
351 /*
352 * Reflects a new waiter being added to the waitqueue.
353 */
hb_waiters_inc(struct futex_hash_bucket * hb)354 static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
355 {
356 #ifdef CONFIG_SMP
357 atomic_inc(&hb->waiters);
358 /*
359 * Full barrier (A), see the ordering comment above.
360 */
361 smp_mb__after_atomic();
362 #endif
363 }
364
365 /*
366 * Reflects a waiter being removed from the waitqueue by wakeup
367 * paths.
368 */
hb_waiters_dec(struct futex_hash_bucket * hb)369 static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
370 {
371 #ifdef CONFIG_SMP
372 atomic_dec(&hb->waiters);
373 #endif
374 }
375
hb_waiters_pending(struct futex_hash_bucket * hb)376 static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
377 {
378 #ifdef CONFIG_SMP
379 return atomic_read(&hb->waiters);
380 #else
381 return 1;
382 #endif
383 }
384
385 /*
386 * We hash on the keys returned from get_futex_key (see below).
387 */
hash_futex(union futex_key * key)388 static struct futex_hash_bucket *hash_futex(union futex_key *key)
389 {
390 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
391 key->both.offset);
392
393 return &futex_queues[hash & (futex_hashsize - 1)];
394 }
395
396 /*
397 * Return 1 if two futex_keys are equal, 0 otherwise.
398 */
match_futex(union futex_key * key1,union futex_key * key2)399 static inline int match_futex(union futex_key *key1, union futex_key *key2)
400 {
401 return (key1 && key2
402 && key1->both.word == key2->both.word
403 && key1->both.ptr == key2->both.ptr
404 && key1->both.offset == key2->both.offset);
405 }
406
407 /*
408 * Take a reference to the resource addressed by a key.
409 * Can be called while holding spinlocks.
410 *
411 */
get_futex_key_refs(union futex_key * key)412 static void get_futex_key_refs(union futex_key *key)
413 {
414 if (!key->both.ptr)
415 return;
416
417 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
418 case FUT_OFF_INODE:
419 smp_mb(); /* explicit smp_mb(); (B) */
420 break;
421 case FUT_OFF_MMSHARED:
422 futex_get_mm(key); /* implies MB (B) */
423 break;
424 default:
425 /*
426 * Private futexes do not hold reference on an inode or
427 * mm, therefore the only purpose of calling get_futex_key_refs
428 * is because we need the barrier for the lockless waiter check.
429 */
430 smp_mb(); /* explicit MB (B) */
431 }
432 }
433
434 /*
435 * Drop a reference to the resource addressed by a key.
436 * The hash bucket spinlock must not be held. This is
437 * a no-op for private futexes, see comment in the get
438 * counterpart.
439 */
drop_futex_key_refs(union futex_key * key)440 static void drop_futex_key_refs(union futex_key *key)
441 {
442 if (!key->both.ptr) {
443 /* If we're here then we tried to put a key we failed to get */
444 WARN_ON_ONCE(1);
445 return;
446 }
447
448 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
449 case FUT_OFF_INODE:
450 break;
451 case FUT_OFF_MMSHARED:
452 mmdrop(key->private.mm);
453 break;
454 }
455 }
456
457 /*
458 * Generate a machine wide unique identifier for this inode.
459 *
460 * This relies on u64 not wrapping in the life-time of the machine; which with
461 * 1ns resolution means almost 585 years.
462 *
463 * This further relies on the fact that a well formed program will not unmap
464 * the file while it has a (shared) futex waiting on it. This mapping will have
465 * a file reference which pins the mount and inode.
466 *
467 * If for some reason an inode gets evicted and read back in again, it will get
468 * a new sequence number and will _NOT_ match, even though it is the exact same
469 * file.
470 *
471 * It is important that match_futex() will never have a false-positive, esp.
472 * for PI futexes that can mess up the state. The above argues that false-negatives
473 * are only possible for malformed programs.
474 */
get_inode_sequence_number(struct inode * inode)475 static u64 get_inode_sequence_number(struct inode *inode)
476 {
477 static atomic64_t i_seq;
478 u64 old;
479
480 /* Does the inode already have a sequence number? */
481 old = atomic64_read(&inode->i_sequence);
482 if (likely(old))
483 return old;
484
485 for (;;) {
486 u64 new = atomic64_add_return(1, &i_seq);
487 if (WARN_ON_ONCE(!new))
488 continue;
489
490 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
491 if (old)
492 return old;
493 return new;
494 }
495 }
496
497 /**
498 * get_futex_key() - Get parameters which are the keys for a futex
499 * @uaddr: virtual address of the futex
500 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
501 * @key: address where result is stored.
502 * @rw: mapping needs to be read/write (values: VERIFY_READ,
503 * VERIFY_WRITE)
504 *
505 * Return: a negative error code or 0
506 *
507 * The key words are stored in *key on success.
508 *
509 * For shared mappings (when @fshared), the key is:
510 * ( inode->i_sequence, page->index, offset_within_page )
511 * [ also see get_inode_sequence_number() ]
512 *
513 * For private mappings (or when !@fshared), the key is:
514 * ( current->mm, address, 0 )
515 *
516 * This allows (cross process, where applicable) identification of the futex
517 * without keeping the page pinned for the duration of the FUTEX_WAIT.
518 *
519 * lock_page() might sleep, the caller should not hold a spinlock.
520 */
521 static int
get_futex_key(u32 __user * uaddr,int fshared,union futex_key * key,int rw)522 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
523 {
524 unsigned long address = (unsigned long)uaddr;
525 struct mm_struct *mm = current->mm;
526 struct page *page, *page_head;
527 struct address_space *mapping;
528 int err, ro = 0;
529
530 /*
531 * The futex address must be "naturally" aligned.
532 */
533 key->both.offset = address % PAGE_SIZE;
534 if (unlikely((address % sizeof(u32)) != 0))
535 return -EINVAL;
536 address -= key->both.offset;
537
538 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
539 return -EFAULT;
540
541 if (unlikely(should_fail_futex(fshared)))
542 return -EFAULT;
543
544 /*
545 * PROCESS_PRIVATE futexes are fast.
546 * As the mm cannot disappear under us and the 'key' only needs
547 * virtual address, we dont even have to find the underlying vma.
548 * Note : We do have to check 'uaddr' is a valid user address,
549 * but access_ok() should be faster than find_vma()
550 */
551 if (!fshared) {
552 key->private.mm = mm;
553 key->private.address = address;
554 get_futex_key_refs(key); /* implies MB (B) */
555 return 0;
556 }
557
558 again:
559 /* Ignore any VERIFY_READ mapping (futex common case) */
560 if (unlikely(should_fail_futex(fshared)))
561 return -EFAULT;
562
563 err = get_user_pages_fast(address, 1, 1, &page);
564 /*
565 * If write access is not required (eg. FUTEX_WAIT), try
566 * and get read-only access.
567 */
568 if (err == -EFAULT && rw == VERIFY_READ) {
569 err = get_user_pages_fast(address, 1, 0, &page);
570 ro = 1;
571 }
572 if (err < 0)
573 return err;
574 else
575 err = 0;
576
577 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
578 page_head = page;
579 if (unlikely(PageTail(page))) {
580 put_page(page);
581 /* serialize against __split_huge_page_splitting() */
582 local_irq_disable();
583 if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) {
584 page_head = compound_head(page);
585 /*
586 * page_head is valid pointer but we must pin
587 * it before taking the PG_lock and/or
588 * PG_compound_lock. The moment we re-enable
589 * irqs __split_huge_page_splitting() can
590 * return and the head page can be freed from
591 * under us. We can't take the PG_lock and/or
592 * PG_compound_lock on a page that could be
593 * freed from under us.
594 */
595 if (page != page_head) {
596 get_page(page_head);
597 put_page(page);
598 }
599 local_irq_enable();
600 } else {
601 local_irq_enable();
602 goto again;
603 }
604 }
605 #else
606 page_head = compound_head(page);
607 if (page != page_head) {
608 get_page(page_head);
609 put_page(page);
610 }
611 #endif
612
613 /*
614 * The treatment of mapping from this point on is critical. The page
615 * lock protects many things but in this context the page lock
616 * stabilizes mapping, prevents inode freeing in the shared
617 * file-backed region case and guards against movement to swap cache.
618 *
619 * Strictly speaking the page lock is not needed in all cases being
620 * considered here and page lock forces unnecessarily serialization
621 * From this point on, mapping will be re-verified if necessary and
622 * page lock will be acquired only if it is unavoidable
623 */
624
625 mapping = READ_ONCE(page_head->mapping);
626
627 /*
628 * If page_head->mapping is NULL, then it cannot be a PageAnon
629 * page; but it might be the ZERO_PAGE or in the gate area or
630 * in a special mapping (all cases which we are happy to fail);
631 * or it may have been a good file page when get_user_pages_fast
632 * found it, but truncated or holepunched or subjected to
633 * invalidate_complete_page2 before we got the page lock (also
634 * cases which we are happy to fail). And we hold a reference,
635 * so refcount care in invalidate_complete_page's remove_mapping
636 * prevents drop_caches from setting mapping to NULL beneath us.
637 *
638 * The case we do have to guard against is when memory pressure made
639 * shmem_writepage move it from filecache to swapcache beneath us:
640 * an unlikely race, but we do need to retry for page_head->mapping.
641 */
642 if (unlikely(!mapping)) {
643 int shmem_swizzled;
644
645 /*
646 * Page lock is required to identify which special case above
647 * applies. If this is really a shmem page then the page lock
648 * will prevent unexpected transitions.
649 */
650 lock_page(page_head);
651 shmem_swizzled = PageSwapCache(page_head) || page_head->mapping;
652 unlock_page(page_head);
653 put_page(page_head);
654
655 if (shmem_swizzled)
656 goto again;
657
658 return -EFAULT;
659 }
660
661 /*
662 * Private mappings are handled in a simple way.
663 *
664 * If the futex key is stored on an anonymous page, then the associated
665 * object is the mm which is implicitly pinned by the calling process.
666 *
667 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
668 * it's a read-only handle, it's expected that futexes attach to
669 * the object not the particular process.
670 */
671 if (PageAnon(page_head)) {
672 /*
673 * A RO anonymous page will never change and thus doesn't make
674 * sense for futex operations.
675 */
676 if (unlikely(should_fail_futex(fshared)) || ro) {
677 err = -EFAULT;
678 goto out;
679 }
680
681 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
682 key->private.mm = mm;
683 key->private.address = address;
684
685 } else {
686 struct inode *inode;
687
688 /*
689 * The associated futex object in this case is the inode and
690 * the page->mapping must be traversed. Ordinarily this should
691 * be stabilised under page lock but it's not strictly
692 * necessary in this case as we just want to pin the inode, not
693 * update the radix tree or anything like that.
694 *
695 * The RCU read lock is taken as the inode is finally freed
696 * under RCU. If the mapping still matches expectations then the
697 * mapping->host can be safely accessed as being a valid inode.
698 */
699 rcu_read_lock();
700
701 if (READ_ONCE(page_head->mapping) != mapping) {
702 rcu_read_unlock();
703 put_page(page_head);
704
705 goto again;
706 }
707
708 inode = READ_ONCE(mapping->host);
709 if (!inode) {
710 rcu_read_unlock();
711 put_page(page_head);
712
713 goto again;
714 }
715
716 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
717 key->shared.i_seq = get_inode_sequence_number(inode);
718 key->shared.pgoff = basepage_index(page);
719 rcu_read_unlock();
720 }
721
722 get_futex_key_refs(key); /* implies smp_mb(); (B) */
723
724 out:
725 put_page(page_head);
726 return err;
727 }
728
put_futex_key(union futex_key * key)729 static inline void put_futex_key(union futex_key *key)
730 {
731 drop_futex_key_refs(key);
732 }
733
734 /**
735 * fault_in_user_writeable() - Fault in user address and verify RW access
736 * @uaddr: pointer to faulting user space address
737 *
738 * Slow path to fixup the fault we just took in the atomic write
739 * access to @uaddr.
740 *
741 * We have no generic implementation of a non-destructive write to the
742 * user address. We know that we faulted in the atomic pagefault
743 * disabled section so we can as well avoid the #PF overhead by
744 * calling get_user_pages() right away.
745 */
fault_in_user_writeable(u32 __user * uaddr)746 static int fault_in_user_writeable(u32 __user *uaddr)
747 {
748 struct mm_struct *mm = current->mm;
749 int ret;
750
751 down_read(&mm->mmap_sem);
752 ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
753 FAULT_FLAG_WRITE);
754 up_read(&mm->mmap_sem);
755
756 return ret < 0 ? ret : 0;
757 }
758
759 /**
760 * futex_top_waiter() - Return the highest priority waiter on a futex
761 * @hb: the hash bucket the futex_q's reside in
762 * @key: the futex key (to distinguish it from other futex futex_q's)
763 *
764 * Must be called with the hb lock held.
765 */
futex_top_waiter(struct futex_hash_bucket * hb,union futex_key * key)766 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
767 union futex_key *key)
768 {
769 struct futex_q *this;
770
771 plist_for_each_entry(this, &hb->chain, list) {
772 if (match_futex(&this->key, key))
773 return this;
774 }
775 return NULL;
776 }
777
cmpxchg_futex_value_locked(u32 * curval,u32 __user * uaddr,u32 uval,u32 newval)778 static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
779 u32 uval, u32 newval)
780 {
781 int ret;
782
783 pagefault_disable();
784 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
785 pagefault_enable();
786
787 return ret;
788 }
789
get_futex_value_locked(u32 * dest,u32 __user * from)790 static int get_futex_value_locked(u32 *dest, u32 __user *from)
791 {
792 int ret;
793
794 pagefault_disable();
795 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
796 pagefault_enable();
797
798 return ret ? -EFAULT : 0;
799 }
800
801
802 /*
803 * PI code:
804 */
refill_pi_state_cache(void)805 static int refill_pi_state_cache(void)
806 {
807 struct futex_pi_state *pi_state;
808
809 if (likely(current->pi_state_cache))
810 return 0;
811
812 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
813
814 if (!pi_state)
815 return -ENOMEM;
816
817 INIT_LIST_HEAD(&pi_state->list);
818 /* pi_mutex gets initialized later */
819 pi_state->owner = NULL;
820 atomic_set(&pi_state->refcount, 1);
821 pi_state->key = FUTEX_KEY_INIT;
822
823 current->pi_state_cache = pi_state;
824
825 return 0;
826 }
827
alloc_pi_state(void)828 static struct futex_pi_state *alloc_pi_state(void)
829 {
830 struct futex_pi_state *pi_state = current->pi_state_cache;
831
832 WARN_ON(!pi_state);
833 current->pi_state_cache = NULL;
834
835 return pi_state;
836 }
837
pi_state_update_owner(struct futex_pi_state * pi_state,struct task_struct * new_owner)838 static void pi_state_update_owner(struct futex_pi_state *pi_state,
839 struct task_struct *new_owner)
840 {
841 struct task_struct *old_owner = pi_state->owner;
842
843 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
844
845 if (old_owner) {
846 raw_spin_lock(&old_owner->pi_lock);
847 WARN_ON(list_empty(&pi_state->list));
848 list_del_init(&pi_state->list);
849 raw_spin_unlock(&old_owner->pi_lock);
850 }
851
852 if (new_owner) {
853 raw_spin_lock(&new_owner->pi_lock);
854 WARN_ON(!list_empty(&pi_state->list));
855 list_add(&pi_state->list, &new_owner->pi_state_list);
856 pi_state->owner = new_owner;
857 raw_spin_unlock(&new_owner->pi_lock);
858 }
859 }
860
get_pi_state(struct futex_pi_state * pi_state)861 static void get_pi_state(struct futex_pi_state *pi_state)
862 {
863 WARN_ON_ONCE(!atomic_inc_not_zero(&pi_state->refcount));
864 }
865
866 /*
867 * Drops a reference to the pi_state object and frees or caches it
868 * when the last reference is gone.
869 *
870 * Must be called with the hb lock held.
871 */
put_pi_state(struct futex_pi_state * pi_state)872 static void put_pi_state(struct futex_pi_state *pi_state)
873 {
874 if (!pi_state)
875 return;
876
877 if (!atomic_dec_and_test(&pi_state->refcount))
878 return;
879
880 /*
881 * If pi_state->owner is NULL, the owner is most probably dying
882 * and has cleaned up the pi_state already
883 */
884 if (pi_state->owner) {
885 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
886 pi_state_update_owner(pi_state, NULL);
887 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
888 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
889 }
890
891 if (current->pi_state_cache)
892 kfree(pi_state);
893 else {
894 /*
895 * pi_state->list is already empty.
896 * clear pi_state->owner.
897 * refcount is at 0 - put it back to 1.
898 */
899 pi_state->owner = NULL;
900 atomic_set(&pi_state->refcount, 1);
901 current->pi_state_cache = pi_state;
902 }
903 }
904
905 /*
906 * Look up the task based on what TID userspace gave us.
907 * We dont trust it.
908 */
futex_find_get_task(pid_t pid)909 static struct task_struct *futex_find_get_task(pid_t pid)
910 {
911 struct task_struct *p;
912
913 rcu_read_lock();
914 p = find_task_by_vpid(pid);
915 if (p)
916 get_task_struct(p);
917
918 rcu_read_unlock();
919
920 return p;
921 }
922
923 /*
924 * This task is holding PI mutexes at exit time => bad.
925 * Kernel cleans up PI-state, but userspace is likely hosed.
926 * (Robust-futex cleanup is separate and might save the day for userspace.)
927 */
exit_pi_state_list(struct task_struct * curr)928 static void exit_pi_state_list(struct task_struct *curr)
929 {
930 struct list_head *next, *head = &curr->pi_state_list;
931 struct futex_pi_state *pi_state;
932 struct futex_hash_bucket *hb;
933 union futex_key key = FUTEX_KEY_INIT;
934
935 if (!futex_cmpxchg_enabled)
936 return;
937 /*
938 * We are a ZOMBIE and nobody can enqueue itself on
939 * pi_state_list anymore, but we have to be careful
940 * versus waiters unqueueing themselves:
941 */
942 raw_spin_lock_irq(&curr->pi_lock);
943 while (!list_empty(head)) {
944
945 next = head->next;
946 pi_state = list_entry(next, struct futex_pi_state, list);
947 key = pi_state->key;
948 hb = hash_futex(&key);
949 raw_spin_unlock_irq(&curr->pi_lock);
950
951 spin_lock(&hb->lock);
952
953 raw_spin_lock_irq(&curr->pi_lock);
954 /*
955 * We dropped the pi-lock, so re-check whether this
956 * task still owns the PI-state:
957 */
958 if (head->next != next) {
959 spin_unlock(&hb->lock);
960 continue;
961 }
962
963 WARN_ON(pi_state->owner != curr);
964 WARN_ON(list_empty(&pi_state->list));
965 list_del_init(&pi_state->list);
966 pi_state->owner = NULL;
967 raw_spin_unlock_irq(&curr->pi_lock);
968
969 get_pi_state(pi_state);
970 spin_unlock(&hb->lock);
971
972 rt_mutex_futex_unlock(&pi_state->pi_mutex);
973 put_pi_state(pi_state);
974
975 raw_spin_lock_irq(&curr->pi_lock);
976 }
977 raw_spin_unlock_irq(&curr->pi_lock);
978 }
979
980 /*
981 * We need to check the following states:
982 *
983 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
984 *
985 * [1] NULL | --- | --- | 0 | 0/1 | Valid
986 * [2] NULL | --- | --- | >0 | 0/1 | Valid
987 *
988 * [3] Found | NULL | -- | Any | 0/1 | Invalid
989 *
990 * [4] Found | Found | NULL | 0 | 1 | Valid
991 * [5] Found | Found | NULL | >0 | 1 | Invalid
992 *
993 * [6] Found | Found | task | 0 | 1 | Valid
994 *
995 * [7] Found | Found | NULL | Any | 0 | Invalid
996 *
997 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
998 * [9] Found | Found | task | 0 | 0 | Invalid
999 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
1000 *
1001 * [1] Indicates that the kernel can acquire the futex atomically. We
1002 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
1003 *
1004 * [2] Valid, if TID does not belong to a kernel thread. If no matching
1005 * thread is found then it indicates that the owner TID has died.
1006 *
1007 * [3] Invalid. The waiter is queued on a non PI futex
1008 *
1009 * [4] Valid state after exit_robust_list(), which sets the user space
1010 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
1011 *
1012 * [5] The user space value got manipulated between exit_robust_list()
1013 * and exit_pi_state_list()
1014 *
1015 * [6] Valid state after exit_pi_state_list() which sets the new owner in
1016 * the pi_state but cannot access the user space value.
1017 *
1018 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
1019 *
1020 * [8] Owner and user space value match
1021 *
1022 * [9] There is no transient state which sets the user space TID to 0
1023 * except exit_robust_list(), but this is indicated by the
1024 * FUTEX_OWNER_DIED bit. See [4]
1025 *
1026 * [10] There is no transient state which leaves owner and user space
1027 * TID out of sync. Except one error case where the kernel is denied
1028 * write access to the user address, see fixup_pi_state_owner().
1029 *
1030 *
1031 * Serialization and lifetime rules:
1032 *
1033 * hb->lock:
1034 *
1035 * hb -> futex_q, relation
1036 * futex_q -> pi_state, relation
1037 *
1038 * (cannot be raw because hb can contain arbitrary amount
1039 * of futex_q's)
1040 *
1041 * pi_mutex->wait_lock:
1042 *
1043 * {uval, pi_state}
1044 *
1045 * (and pi_mutex 'obviously')
1046 *
1047 * p->pi_lock:
1048 *
1049 * p->pi_state_list -> pi_state->list, relation
1050 *
1051 * pi_state->refcount:
1052 *
1053 * pi_state lifetime
1054 *
1055 *
1056 * Lock order:
1057 *
1058 * hb->lock
1059 * pi_mutex->wait_lock
1060 * p->pi_lock
1061 *
1062 */
1063
1064 /*
1065 * Validate that the existing waiter has a pi_state and sanity check
1066 * the pi_state against the user space value. If correct, attach to
1067 * it.
1068 */
attach_to_pi_state(u32 __user * uaddr,u32 uval,struct futex_pi_state * pi_state,struct futex_pi_state ** ps)1069 static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1070 struct futex_pi_state *pi_state,
1071 struct futex_pi_state **ps)
1072 {
1073 pid_t pid = uval & FUTEX_TID_MASK;
1074 int ret, uval2;
1075
1076 /*
1077 * Userspace might have messed up non-PI and PI futexes [3]
1078 */
1079 if (unlikely(!pi_state))
1080 return -EINVAL;
1081
1082 /*
1083 * We get here with hb->lock held, and having found a
1084 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1085 * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
1086 * which in turn means that futex_lock_pi() still has a reference on
1087 * our pi_state.
1088 *
1089 * The waiter holding a reference on @pi_state also protects against
1090 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1091 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1092 * free pi_state before we can take a reference ourselves.
1093 */
1094 WARN_ON(!atomic_read(&pi_state->refcount));
1095
1096 /*
1097 * Now that we have a pi_state, we can acquire wait_lock
1098 * and do the state validation.
1099 */
1100 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1101
1102 /*
1103 * Since {uval, pi_state} is serialized by wait_lock, and our current
1104 * uval was read without holding it, it can have changed. Verify it
1105 * still is what we expect it to be, otherwise retry the entire
1106 * operation.
1107 */
1108 if (get_futex_value_locked(&uval2, uaddr))
1109 goto out_efault;
1110
1111 if (uval != uval2)
1112 goto out_eagain;
1113
1114 /*
1115 * Handle the owner died case:
1116 */
1117 if (uval & FUTEX_OWNER_DIED) {
1118 /*
1119 * exit_pi_state_list sets owner to NULL and wakes the
1120 * topmost waiter. The task which acquires the
1121 * pi_state->rt_mutex will fixup owner.
1122 */
1123 if (!pi_state->owner) {
1124 /*
1125 * No pi state owner, but the user space TID
1126 * is not 0. Inconsistent state. [5]
1127 */
1128 if (pid)
1129 goto out_einval;
1130 /*
1131 * Take a ref on the state and return success. [4]
1132 */
1133 goto out_attach;
1134 }
1135
1136 /*
1137 * If TID is 0, then either the dying owner has not
1138 * yet executed exit_pi_state_list() or some waiter
1139 * acquired the rtmutex in the pi state, but did not
1140 * yet fixup the TID in user space.
1141 *
1142 * Take a ref on the state and return success. [6]
1143 */
1144 if (!pid)
1145 goto out_attach;
1146 } else {
1147 /*
1148 * If the owner died bit is not set, then the pi_state
1149 * must have an owner. [7]
1150 */
1151 if (!pi_state->owner)
1152 goto out_einval;
1153 }
1154
1155 /*
1156 * Bail out if user space manipulated the futex value. If pi
1157 * state exists then the owner TID must be the same as the
1158 * user space TID. [9/10]
1159 */
1160 if (pid != task_pid_vnr(pi_state->owner))
1161 goto out_einval;
1162
1163 out_attach:
1164 get_pi_state(pi_state);
1165 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1166 *ps = pi_state;
1167 return 0;
1168
1169 out_einval:
1170 ret = -EINVAL;
1171 goto out_error;
1172
1173 out_eagain:
1174 ret = -EAGAIN;
1175 goto out_error;
1176
1177 out_efault:
1178 ret = -EFAULT;
1179 goto out_error;
1180
1181 out_error:
1182 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1183 return ret;
1184 }
1185
1186 /**
1187 * wait_for_owner_exiting - Block until the owner has exited
1188 * @exiting: Pointer to the exiting task
1189 *
1190 * Caller must hold a refcount on @exiting.
1191 */
wait_for_owner_exiting(int ret,struct task_struct * exiting)1192 static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1193 {
1194 if (ret != -EBUSY) {
1195 WARN_ON_ONCE(exiting);
1196 return;
1197 }
1198
1199 if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
1200 return;
1201
1202 mutex_lock(&exiting->futex_exit_mutex);
1203 /*
1204 * No point in doing state checking here. If the waiter got here
1205 * while the task was in exec()->exec_futex_release() then it can
1206 * have any FUTEX_STATE_* value when the waiter has acquired the
1207 * mutex. OK, if running, EXITING or DEAD if it reached exit()
1208 * already. Highly unlikely and not a problem. Just one more round
1209 * through the futex maze.
1210 */
1211 mutex_unlock(&exiting->futex_exit_mutex);
1212
1213 put_task_struct(exiting);
1214 }
1215
handle_exit_race(u32 __user * uaddr,u32 uval,struct task_struct * tsk)1216 static int handle_exit_race(u32 __user *uaddr, u32 uval,
1217 struct task_struct *tsk)
1218 {
1219 u32 uval2;
1220
1221 /*
1222 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1223 * caller that the alleged owner is busy.
1224 */
1225 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
1226 return -EBUSY;
1227
1228 /*
1229 * Reread the user space value to handle the following situation:
1230 *
1231 * CPU0 CPU1
1232 *
1233 * sys_exit() sys_futex()
1234 * do_exit() futex_lock_pi()
1235 * futex_lock_pi_atomic()
1236 * exit_signals(tsk) No waiters:
1237 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1238 * mm_release(tsk) Set waiter bit
1239 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1240 * Set owner died attach_to_pi_owner() {
1241 * *uaddr = 0xC0000000; tsk = get_task(PID);
1242 * } if (!tsk->flags & PF_EXITING) {
1243 * ... attach();
1244 * tsk->futex_state = } else {
1245 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1246 * FUTEX_STATE_DEAD)
1247 * return -EAGAIN;
1248 * return -ESRCH; <--- FAIL
1249 * }
1250 *
1251 * Returning ESRCH unconditionally is wrong here because the
1252 * user space value has been changed by the exiting task.
1253 *
1254 * The same logic applies to the case where the exiting task is
1255 * already gone.
1256 */
1257 if (get_futex_value_locked(&uval2, uaddr))
1258 return -EFAULT;
1259
1260 /* If the user space value has changed, try again. */
1261 if (uval2 != uval)
1262 return -EAGAIN;
1263
1264 /*
1265 * The exiting task did not have a robust list, the robust list was
1266 * corrupted or the user space value in *uaddr is simply bogus.
1267 * Give up and tell user space.
1268 */
1269 return -ESRCH;
1270 }
1271
1272 /*
1273 * Lookup the task for the TID provided from user space and attach to
1274 * it after doing proper sanity checks.
1275 */
attach_to_pi_owner(u32 __user * uaddr,u32 uval,union futex_key * key,struct futex_pi_state ** ps,struct task_struct ** exiting)1276 static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
1277 struct futex_pi_state **ps,
1278 struct task_struct **exiting)
1279 {
1280 pid_t pid = uval & FUTEX_TID_MASK;
1281 struct futex_pi_state *pi_state;
1282 struct task_struct *p;
1283
1284 /*
1285 * We are the first waiter - try to look up the real owner and attach
1286 * the new pi_state to it, but bail out when TID = 0 [1]
1287 *
1288 * The !pid check is paranoid. None of the call sites should end up
1289 * with pid == 0, but better safe than sorry. Let the caller retry
1290 */
1291 if (!pid)
1292 return -EAGAIN;
1293 p = futex_find_get_task(pid);
1294 if (!p)
1295 return handle_exit_race(uaddr, uval, NULL);
1296
1297 if (unlikely(p->flags & PF_KTHREAD)) {
1298 put_task_struct(p);
1299 return -EPERM;
1300 }
1301
1302 /*
1303 * We need to look at the task state to figure out, whether the
1304 * task is exiting. To protect against the change of the task state
1305 * in futex_exit_release(), we do this protected by p->pi_lock:
1306 */
1307 raw_spin_lock_irq(&p->pi_lock);
1308 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
1309 /*
1310 * The task is on the way out. When the futex state is
1311 * FUTEX_STATE_DEAD, we know that the task has finished
1312 * the cleanup:
1313 */
1314 int ret = handle_exit_race(uaddr, uval, p);
1315
1316 raw_spin_unlock_irq(&p->pi_lock);
1317 /*
1318 * If the owner task is between FUTEX_STATE_EXITING and
1319 * FUTEX_STATE_DEAD then store the task pointer and keep
1320 * the reference on the task struct. The calling code will
1321 * drop all locks, wait for the task to reach
1322 * FUTEX_STATE_DEAD and then drop the refcount. This is
1323 * required to prevent a live lock when the current task
1324 * preempted the exiting task between the two states.
1325 */
1326 if (ret == -EBUSY)
1327 *exiting = p;
1328 else
1329 put_task_struct(p);
1330 return ret;
1331 }
1332
1333 /*
1334 * No existing pi state. First waiter. [2]
1335 *
1336 * This creates pi_state, we have hb->lock held, this means nothing can
1337 * observe this state, wait_lock is irrelevant.
1338 */
1339 pi_state = alloc_pi_state();
1340
1341 /*
1342 * Initialize the pi_mutex in locked state and make @p
1343 * the owner of it:
1344 */
1345 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1346
1347 /* Store the key for possible exit cleanups: */
1348 pi_state->key = *key;
1349
1350 WARN_ON(!list_empty(&pi_state->list));
1351 list_add(&pi_state->list, &p->pi_state_list);
1352 pi_state->owner = p;
1353 raw_spin_unlock_irq(&p->pi_lock);
1354
1355 put_task_struct(p);
1356
1357 *ps = pi_state;
1358
1359 return 0;
1360 }
1361
lookup_pi_state(u32 __user * uaddr,u32 uval,struct futex_hash_bucket * hb,union futex_key * key,struct futex_pi_state ** ps,struct task_struct ** exiting)1362 static int lookup_pi_state(u32 __user *uaddr, u32 uval,
1363 struct futex_hash_bucket *hb,
1364 union futex_key *key, struct futex_pi_state **ps,
1365 struct task_struct **exiting)
1366 {
1367 struct futex_q *match = futex_top_waiter(hb, key);
1368
1369 /*
1370 * If there is a waiter on that futex, validate it and
1371 * attach to the pi_state when the validation succeeds.
1372 */
1373 if (match)
1374 return attach_to_pi_state(uaddr, uval, match->pi_state, ps);
1375
1376 /*
1377 * We are the first waiter - try to look up the owner based on
1378 * @uval and attach to it.
1379 */
1380 return attach_to_pi_owner(uaddr, uval, key, ps, exiting);
1381 }
1382
lock_pi_update_atomic(u32 __user * uaddr,u32 uval,u32 newval)1383 static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1384 {
1385 u32 uninitialized_var(curval);
1386
1387 if (unlikely(should_fail_futex(true)))
1388 return -EFAULT;
1389
1390 if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
1391 return -EFAULT;
1392
1393 /* If user space value changed, let the caller retry */
1394 return curval != uval ? -EAGAIN : 0;
1395 }
1396
1397 /**
1398 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
1399 * @uaddr: the pi futex user address
1400 * @hb: the pi futex hash bucket
1401 * @key: the futex key associated with uaddr and hb
1402 * @ps: the pi_state pointer where we store the result of the
1403 * lookup
1404 * @task: the task to perform the atomic lock work for. This will
1405 * be "current" except in the case of requeue pi.
1406 * @exiting: Pointer to store the task pointer of the owner task
1407 * which is in the middle of exiting
1408 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1409 *
1410 * Return:
1411 * 0 - ready to wait;
1412 * 1 - acquired the lock;
1413 * <0 - error
1414 *
1415 * The hb->lock and futex_key refs shall be held by the caller.
1416 *
1417 * @exiting is only set when the return value is -EBUSY. If so, this holds
1418 * a refcount on the exiting task on return and the caller needs to drop it
1419 * after waiting for the exit to complete.
1420 */
futex_lock_pi_atomic(u32 __user * uaddr,struct futex_hash_bucket * hb,union futex_key * key,struct futex_pi_state ** ps,struct task_struct * task,struct task_struct ** exiting,int set_waiters)1421 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1422 union futex_key *key,
1423 struct futex_pi_state **ps,
1424 struct task_struct *task,
1425 struct task_struct **exiting,
1426 int set_waiters)
1427 {
1428 u32 uval, newval, vpid = task_pid_vnr(task);
1429 struct futex_q *match;
1430 int ret;
1431
1432 /*
1433 * Read the user space value first so we can validate a few
1434 * things before proceeding further.
1435 */
1436 if (get_futex_value_locked(&uval, uaddr))
1437 return -EFAULT;
1438
1439 if (unlikely(should_fail_futex(true)))
1440 return -EFAULT;
1441
1442 /*
1443 * Detect deadlocks.
1444 */
1445 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1446 return -EDEADLK;
1447
1448 if ((unlikely(should_fail_futex(true))))
1449 return -EDEADLK;
1450
1451 /*
1452 * Lookup existing state first. If it exists, try to attach to
1453 * its pi_state.
1454 */
1455 match = futex_top_waiter(hb, key);
1456 if (match)
1457 return attach_to_pi_state(uaddr, uval, match->pi_state, ps);
1458
1459 /*
1460 * No waiter and user TID is 0. We are here because the
1461 * waiters or the owner died bit is set or called from
1462 * requeue_cmp_pi or for whatever reason something took the
1463 * syscall.
1464 */
1465 if (!(uval & FUTEX_TID_MASK)) {
1466 /*
1467 * We take over the futex. No other waiters and the user space
1468 * TID is 0. We preserve the owner died bit.
1469 */
1470 newval = uval & FUTEX_OWNER_DIED;
1471 newval |= vpid;
1472
1473 /* The futex requeue_pi code can enforce the waiters bit */
1474 if (set_waiters)
1475 newval |= FUTEX_WAITERS;
1476
1477 ret = lock_pi_update_atomic(uaddr, uval, newval);
1478 /* If the take over worked, return 1 */
1479 return ret < 0 ? ret : 1;
1480 }
1481
1482 /*
1483 * First waiter. Set the waiters bit before attaching ourself to
1484 * the owner. If owner tries to unlock, it will be forced into
1485 * the kernel and blocked on hb->lock.
1486 */
1487 newval = uval | FUTEX_WAITERS;
1488 ret = lock_pi_update_atomic(uaddr, uval, newval);
1489 if (ret)
1490 return ret;
1491 /*
1492 * If the update of the user space value succeeded, we try to
1493 * attach to the owner. If that fails, no harm done, we only
1494 * set the FUTEX_WAITERS bit in the user space variable.
1495 */
1496 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
1497 }
1498
1499 /**
1500 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1501 * @q: The futex_q to unqueue
1502 *
1503 * The q->lock_ptr must not be NULL and must be held by the caller.
1504 */
__unqueue_futex(struct futex_q * q)1505 static void __unqueue_futex(struct futex_q *q)
1506 {
1507 struct futex_hash_bucket *hb;
1508
1509 if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
1510 || WARN_ON(plist_node_empty(&q->list)))
1511 return;
1512
1513 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1514 plist_del(&q->list, &hb->chain);
1515 hb_waiters_dec(hb);
1516 }
1517
1518 /*
1519 * The hash bucket lock must be held when this is called.
1520 * Afterwards, the futex_q must not be accessed. Callers
1521 * must ensure to later call wake_up_q() for the actual
1522 * wakeups to occur.
1523 */
mark_wake_futex(struct wake_q_head * wake_q,struct futex_q * q)1524 static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
1525 {
1526 struct task_struct *p = q->task;
1527
1528 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1529 return;
1530
1531 /*
1532 * Queue the task for later wakeup for after we've released
1533 * the hb->lock. wake_q_add() grabs reference to p.
1534 */
1535 wake_q_add(wake_q, p);
1536 __unqueue_futex(q);
1537 /*
1538 * The waiting task can free the futex_q as soon as
1539 * q->lock_ptr = NULL is written, without taking any locks. A
1540 * memory barrier is required here to prevent the following
1541 * store to lock_ptr from getting ahead of the plist_del.
1542 */
1543 smp_wmb();
1544 q->lock_ptr = NULL;
1545 }
1546
1547 /*
1548 * Caller must hold a reference on @pi_state.
1549 */
wake_futex_pi(u32 __user * uaddr,u32 uval,struct futex_pi_state * pi_state)1550 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
1551 {
1552 u32 uninitialized_var(curval), newval;
1553 struct task_struct *new_owner;
1554 bool deboost = false;
1555 WAKE_Q(wake_q);
1556 int ret = 0;
1557
1558 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
1559 if (WARN_ON_ONCE(!new_owner)) {
1560 /*
1561 * As per the comment in futex_unlock_pi() this should not happen.
1562 *
1563 * When this happens, give up our locks and try again, giving
1564 * the futex_lock_pi() instance time to complete, either by
1565 * waiting on the rtmutex or removing itself from the futex
1566 * queue.
1567 */
1568 ret = -EAGAIN;
1569 goto out_unlock;
1570 }
1571
1572 /*
1573 * We pass it to the next owner. The WAITERS bit is always kept
1574 * enabled while there is PI state around. We cleanup the owner
1575 * died bit, because we are the owner.
1576 */
1577 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
1578
1579 if (unlikely(should_fail_futex(true)))
1580 ret = -EFAULT;
1581
1582 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)) {
1583 ret = -EFAULT;
1584
1585 } else if (curval != uval) {
1586 /*
1587 * If a unconditional UNLOCK_PI operation (user space did not
1588 * try the TID->0 transition) raced with a waiter setting the
1589 * FUTEX_WAITERS flag between get_user() and locking the hash
1590 * bucket lock, retry the operation.
1591 */
1592 if ((FUTEX_TID_MASK & curval) == uval)
1593 ret = -EAGAIN;
1594 else
1595 ret = -EINVAL;
1596 }
1597
1598 if (!ret) {
1599 /*
1600 * This is a point of no return; once we modified the uval
1601 * there is no going back and subsequent operations must
1602 * not fail.
1603 */
1604 pi_state_update_owner(pi_state, new_owner);
1605 deboost = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
1606 }
1607
1608 out_unlock:
1609 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1610
1611 if (deboost) {
1612 wake_up_q(&wake_q);
1613 rt_mutex_adjust_prio(current);
1614 }
1615
1616 return ret;
1617 }
1618
1619 /*
1620 * Express the locking dependencies for lockdep:
1621 */
1622 static inline void
double_lock_hb(struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2)1623 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1624 {
1625 if (hb1 <= hb2) {
1626 spin_lock(&hb1->lock);
1627 if (hb1 < hb2)
1628 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1629 } else { /* hb1 > hb2 */
1630 spin_lock(&hb2->lock);
1631 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1632 }
1633 }
1634
1635 static inline void
double_unlock_hb(struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2)1636 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1637 {
1638 spin_unlock(&hb1->lock);
1639 if (hb1 != hb2)
1640 spin_unlock(&hb2->lock);
1641 }
1642
1643 /*
1644 * Wake up waiters matching bitset queued on this futex (uaddr).
1645 */
1646 static int
futex_wake(u32 __user * uaddr,unsigned int flags,int nr_wake,u32 bitset)1647 futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1648 {
1649 struct futex_hash_bucket *hb;
1650 struct futex_q *this, *next;
1651 union futex_key key = FUTEX_KEY_INIT;
1652 int ret;
1653 WAKE_Q(wake_q);
1654
1655 if (!bitset)
1656 return -EINVAL;
1657
1658 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
1659 if (unlikely(ret != 0))
1660 goto out;
1661
1662 hb = hash_futex(&key);
1663
1664 /* Make sure we really have tasks to wakeup */
1665 if (!hb_waiters_pending(hb))
1666 goto out_put_key;
1667
1668 spin_lock(&hb->lock);
1669
1670 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1671 if (match_futex (&this->key, &key)) {
1672 if (this->pi_state || this->rt_waiter) {
1673 ret = -EINVAL;
1674 break;
1675 }
1676
1677 /* Check if one of the bits is set in both bitsets */
1678 if (!(this->bitset & bitset))
1679 continue;
1680
1681 mark_wake_futex(&wake_q, this);
1682 if (++ret >= nr_wake)
1683 break;
1684 }
1685 }
1686
1687 spin_unlock(&hb->lock);
1688 wake_up_q(&wake_q);
1689 out_put_key:
1690 put_futex_key(&key);
1691 out:
1692 return ret;
1693 }
1694
futex_atomic_op_inuser(unsigned int encoded_op,u32 __user * uaddr)1695 static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1696 {
1697 unsigned int op = (encoded_op & 0x70000000) >> 28;
1698 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
1699 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1700 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
1701 int oldval, ret;
1702
1703 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
1704 if (oparg < 0 || oparg > 31) {
1705 char comm[sizeof(current->comm)];
1706 /*
1707 * kill this print and return -EINVAL when userspace
1708 * is sane again
1709 */
1710 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1711 get_task_comm(comm, current), oparg);
1712 oparg &= 31;
1713 }
1714 oparg = 1 << oparg;
1715 }
1716
1717 if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))
1718 return -EFAULT;
1719
1720 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
1721 if (ret)
1722 return ret;
1723
1724 switch (cmp) {
1725 case FUTEX_OP_CMP_EQ:
1726 return oldval == cmparg;
1727 case FUTEX_OP_CMP_NE:
1728 return oldval != cmparg;
1729 case FUTEX_OP_CMP_LT:
1730 return oldval < cmparg;
1731 case FUTEX_OP_CMP_GE:
1732 return oldval >= cmparg;
1733 case FUTEX_OP_CMP_LE:
1734 return oldval <= cmparg;
1735 case FUTEX_OP_CMP_GT:
1736 return oldval > cmparg;
1737 default:
1738 return -ENOSYS;
1739 }
1740 }
1741
1742 /*
1743 * Wake up all waiters hashed on the physical page that is mapped
1744 * to this virtual address:
1745 */
1746 static int
futex_wake_op(u32 __user * uaddr1,unsigned int flags,u32 __user * uaddr2,int nr_wake,int nr_wake2,int op)1747 futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
1748 int nr_wake, int nr_wake2, int op)
1749 {
1750 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1751 struct futex_hash_bucket *hb1, *hb2;
1752 struct futex_q *this, *next;
1753 int ret, op_ret;
1754 WAKE_Q(wake_q);
1755
1756 retry:
1757 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
1758 if (unlikely(ret != 0))
1759 goto out;
1760 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
1761 if (unlikely(ret != 0))
1762 goto out_put_key1;
1763
1764 hb1 = hash_futex(&key1);
1765 hb2 = hash_futex(&key2);
1766
1767 retry_private:
1768 double_lock_hb(hb1, hb2);
1769 op_ret = futex_atomic_op_inuser(op, uaddr2);
1770 if (unlikely(op_ret < 0)) {
1771
1772 double_unlock_hb(hb1, hb2);
1773
1774 #ifndef CONFIG_MMU
1775 /*
1776 * we don't get EFAULT from MMU faults if we don't have an MMU,
1777 * but we might get them from range checking
1778 */
1779 ret = op_ret;
1780 goto out_put_keys;
1781 #endif
1782
1783 if (unlikely(op_ret != -EFAULT)) {
1784 ret = op_ret;
1785 goto out_put_keys;
1786 }
1787
1788 ret = fault_in_user_writeable(uaddr2);
1789 if (ret)
1790 goto out_put_keys;
1791
1792 if (!(flags & FLAGS_SHARED))
1793 goto retry_private;
1794
1795 put_futex_key(&key2);
1796 put_futex_key(&key1);
1797 goto retry;
1798 }
1799
1800 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
1801 if (match_futex (&this->key, &key1)) {
1802 if (this->pi_state || this->rt_waiter) {
1803 ret = -EINVAL;
1804 goto out_unlock;
1805 }
1806 mark_wake_futex(&wake_q, this);
1807 if (++ret >= nr_wake)
1808 break;
1809 }
1810 }
1811
1812 if (op_ret > 0) {
1813 op_ret = 0;
1814 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
1815 if (match_futex (&this->key, &key2)) {
1816 if (this->pi_state || this->rt_waiter) {
1817 ret = -EINVAL;
1818 goto out_unlock;
1819 }
1820 mark_wake_futex(&wake_q, this);
1821 if (++op_ret >= nr_wake2)
1822 break;
1823 }
1824 }
1825 ret += op_ret;
1826 }
1827
1828 out_unlock:
1829 double_unlock_hb(hb1, hb2);
1830 wake_up_q(&wake_q);
1831 out_put_keys:
1832 put_futex_key(&key2);
1833 out_put_key1:
1834 put_futex_key(&key1);
1835 out:
1836 return ret;
1837 }
1838
1839 /**
1840 * requeue_futex() - Requeue a futex_q from one hb to another
1841 * @q: the futex_q to requeue
1842 * @hb1: the source hash_bucket
1843 * @hb2: the target hash_bucket
1844 * @key2: the new key for the requeued futex_q
1845 */
1846 static inline
requeue_futex(struct futex_q * q,struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2,union futex_key * key2)1847 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1848 struct futex_hash_bucket *hb2, union futex_key *key2)
1849 {
1850
1851 /*
1852 * If key1 and key2 hash to the same bucket, no need to
1853 * requeue.
1854 */
1855 if (likely(&hb1->chain != &hb2->chain)) {
1856 plist_del(&q->list, &hb1->chain);
1857 hb_waiters_dec(hb1);
1858 hb_waiters_inc(hb2);
1859 plist_add(&q->list, &hb2->chain);
1860 q->lock_ptr = &hb2->lock;
1861 }
1862 get_futex_key_refs(key2);
1863 q->key = *key2;
1864 }
1865
1866 /**
1867 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1868 * @q: the futex_q
1869 * @key: the key of the requeue target futex
1870 * @hb: the hash_bucket of the requeue target futex
1871 *
1872 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1873 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1874 * to the requeue target futex so the waiter can detect the wakeup on the right
1875 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1876 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1877 * to protect access to the pi_state to fixup the owner later. Must be called
1878 * with both q->lock_ptr and hb->lock held.
1879 */
1880 static inline
requeue_pi_wake_futex(struct futex_q * q,union futex_key * key,struct futex_hash_bucket * hb)1881 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1882 struct futex_hash_bucket *hb)
1883 {
1884 get_futex_key_refs(key);
1885 q->key = *key;
1886
1887 __unqueue_futex(q);
1888
1889 WARN_ON(!q->rt_waiter);
1890 q->rt_waiter = NULL;
1891
1892 q->lock_ptr = &hb->lock;
1893
1894 wake_up_state(q->task, TASK_NORMAL);
1895 }
1896
1897 /**
1898 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1899 * @pifutex: the user address of the to futex
1900 * @hb1: the from futex hash bucket, must be locked by the caller
1901 * @hb2: the to futex hash bucket, must be locked by the caller
1902 * @key1: the from futex key
1903 * @key2: the to futex key
1904 * @ps: address to store the pi_state pointer
1905 * @exiting: Pointer to store the task pointer of the owner task
1906 * which is in the middle of exiting
1907 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1908 *
1909 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1910 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1911 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1912 * hb1 and hb2 must be held by the caller.
1913 *
1914 * @exiting is only set when the return value is -EBUSY. If so, this holds
1915 * a refcount on the exiting task on return and the caller needs to drop it
1916 * after waiting for the exit to complete.
1917 *
1918 * Return:
1919 * 0 - failed to acquire the lock atomically;
1920 * >0 - acquired the lock, return value is vpid of the top_waiter
1921 * <0 - error
1922 */
1923 static int
futex_proxy_trylock_atomic(u32 __user * pifutex,struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2,union futex_key * key1,union futex_key * key2,struct futex_pi_state ** ps,struct task_struct ** exiting,int set_waiters)1924 futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
1925 struct futex_hash_bucket *hb2, union futex_key *key1,
1926 union futex_key *key2, struct futex_pi_state **ps,
1927 struct task_struct **exiting, int set_waiters)
1928 {
1929 struct futex_q *top_waiter = NULL;
1930 u32 curval;
1931 int ret, vpid;
1932
1933 if (get_futex_value_locked(&curval, pifutex))
1934 return -EFAULT;
1935
1936 if (unlikely(should_fail_futex(true)))
1937 return -EFAULT;
1938
1939 /*
1940 * Find the top_waiter and determine if there are additional waiters.
1941 * If the caller intends to requeue more than 1 waiter to pifutex,
1942 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1943 * as we have means to handle the possible fault. If not, don't set
1944 * the bit unecessarily as it will force the subsequent unlock to enter
1945 * the kernel.
1946 */
1947 top_waiter = futex_top_waiter(hb1, key1);
1948
1949 /* There are no waiters, nothing for us to do. */
1950 if (!top_waiter)
1951 return 0;
1952
1953 /* Ensure we requeue to the expected futex. */
1954 if (!match_futex(top_waiter->requeue_pi_key, key2))
1955 return -EINVAL;
1956
1957 /*
1958 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1959 * the contended case or if set_waiters is 1. The pi_state is returned
1960 * in ps in contended cases.
1961 */
1962 vpid = task_pid_vnr(top_waiter->task);
1963 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1964 exiting, set_waiters);
1965 if (ret == 1) {
1966 requeue_pi_wake_futex(top_waiter, key2, hb2);
1967 return vpid;
1968 }
1969 return ret;
1970 }
1971
1972 /**
1973 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1974 * @uaddr1: source futex user address
1975 * @flags: futex flags (FLAGS_SHARED, etc.)
1976 * @uaddr2: target futex user address
1977 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1978 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1979 * @cmpval: @uaddr1 expected value (or %NULL)
1980 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
1981 * pi futex (pi to pi requeue is not supported)
1982 *
1983 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1984 * uaddr2 atomically on behalf of the top waiter.
1985 *
1986 * Return:
1987 * >=0 - on success, the number of tasks requeued or woken;
1988 * <0 - on error
1989 */
futex_requeue(u32 __user * uaddr1,unsigned int flags,u32 __user * uaddr2,int nr_wake,int nr_requeue,u32 * cmpval,int requeue_pi)1990 static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
1991 u32 __user *uaddr2, int nr_wake, int nr_requeue,
1992 u32 *cmpval, int requeue_pi)
1993 {
1994 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1995 int drop_count = 0, task_count = 0, ret;
1996 struct futex_pi_state *pi_state = NULL;
1997 struct futex_hash_bucket *hb1, *hb2;
1998 struct futex_q *this, *next;
1999 WAKE_Q(wake_q);
2000
2001 if (nr_wake < 0 || nr_requeue < 0)
2002 return -EINVAL;
2003
2004 if (requeue_pi) {
2005 /*
2006 * Requeue PI only works on two distinct uaddrs. This
2007 * check is only valid for private futexes. See below.
2008 */
2009 if (uaddr1 == uaddr2)
2010 return -EINVAL;
2011
2012 /*
2013 * requeue_pi requires a pi_state, try to allocate it now
2014 * without any locks in case it fails.
2015 */
2016 if (refill_pi_state_cache())
2017 return -ENOMEM;
2018 /*
2019 * requeue_pi must wake as many tasks as it can, up to nr_wake
2020 * + nr_requeue, since it acquires the rt_mutex prior to
2021 * returning to userspace, so as to not leave the rt_mutex with
2022 * waiters and no owner. However, second and third wake-ups
2023 * cannot be predicted as they involve race conditions with the
2024 * first wake and a fault while looking up the pi_state. Both
2025 * pthread_cond_signal() and pthread_cond_broadcast() should
2026 * use nr_wake=1.
2027 */
2028 if (nr_wake != 1)
2029 return -EINVAL;
2030 }
2031
2032 retry:
2033 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
2034 if (unlikely(ret != 0))
2035 goto out;
2036 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
2037 requeue_pi ? VERIFY_WRITE : VERIFY_READ);
2038 if (unlikely(ret != 0))
2039 goto out_put_key1;
2040
2041 /*
2042 * The check above which compares uaddrs is not sufficient for
2043 * shared futexes. We need to compare the keys:
2044 */
2045 if (requeue_pi && match_futex(&key1, &key2)) {
2046 ret = -EINVAL;
2047 goto out_put_keys;
2048 }
2049
2050 hb1 = hash_futex(&key1);
2051 hb2 = hash_futex(&key2);
2052
2053 retry_private:
2054 hb_waiters_inc(hb2);
2055 double_lock_hb(hb1, hb2);
2056
2057 if (likely(cmpval != NULL)) {
2058 u32 curval;
2059
2060 ret = get_futex_value_locked(&curval, uaddr1);
2061
2062 if (unlikely(ret)) {
2063 double_unlock_hb(hb1, hb2);
2064 hb_waiters_dec(hb2);
2065
2066 ret = get_user(curval, uaddr1);
2067 if (ret)
2068 goto out_put_keys;
2069
2070 if (!(flags & FLAGS_SHARED))
2071 goto retry_private;
2072
2073 put_futex_key(&key2);
2074 put_futex_key(&key1);
2075 goto retry;
2076 }
2077 if (curval != *cmpval) {
2078 ret = -EAGAIN;
2079 goto out_unlock;
2080 }
2081 }
2082
2083 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
2084 struct task_struct *exiting = NULL;
2085
2086 /*
2087 * Attempt to acquire uaddr2 and wake the top waiter. If we
2088 * intend to requeue waiters, force setting the FUTEX_WAITERS
2089 * bit. We force this here where we are able to easily handle
2090 * faults rather in the requeue loop below.
2091 */
2092 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
2093 &key2, &pi_state,
2094 &exiting, nr_requeue);
2095
2096 /*
2097 * At this point the top_waiter has either taken uaddr2 or is
2098 * waiting on it. If the former, then the pi_state will not
2099 * exist yet, look it up one more time to ensure we have a
2100 * reference to it. If the lock was taken, ret contains the
2101 * vpid of the top waiter task.
2102 */
2103 if (ret > 0) {
2104 WARN_ON(pi_state);
2105 drop_count++;
2106 task_count++;
2107 /*
2108 * If we acquired the lock, then the user
2109 * space value of uaddr2 should be vpid. It
2110 * cannot be changed by the top waiter as it
2111 * is blocked on hb2 lock if it tries to do
2112 * so. If something fiddled with it behind our
2113 * back the pi state lookup might unearth
2114 * it. So we rather use the known value than
2115 * rereading and handing potential crap to
2116 * lookup_pi_state.
2117 */
2118 ret = lookup_pi_state(uaddr2, ret, hb2, &key2,
2119 &pi_state, &exiting);
2120 }
2121
2122 switch (ret) {
2123 case 0:
2124 break;
2125 case -EFAULT:
2126 put_pi_state(pi_state);
2127 pi_state = NULL;
2128 double_unlock_hb(hb1, hb2);
2129 hb_waiters_dec(hb2);
2130 put_futex_key(&key2);
2131 put_futex_key(&key1);
2132 ret = fault_in_user_writeable(uaddr2);
2133 if (!ret)
2134 goto retry;
2135 goto out;
2136 case -EBUSY:
2137 case -EAGAIN:
2138 /*
2139 * Two reasons for this:
2140 * - EBUSY: Owner is exiting and we just wait for the
2141 * exit to complete.
2142 * - EAGAIN: The user space value changed.
2143 */
2144 put_pi_state(pi_state);
2145 pi_state = NULL;
2146 double_unlock_hb(hb1, hb2);
2147 hb_waiters_dec(hb2);
2148 put_futex_key(&key2);
2149 put_futex_key(&key1);
2150 /*
2151 * Handle the case where the owner is in the middle of
2152 * exiting. Wait for the exit to complete otherwise
2153 * this task might loop forever, aka. live lock.
2154 */
2155 wait_for_owner_exiting(ret, exiting);
2156 cond_resched();
2157 goto retry;
2158 default:
2159 goto out_unlock;
2160 }
2161 }
2162
2163 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
2164 if (task_count - nr_wake >= nr_requeue)
2165 break;
2166
2167 if (!match_futex(&this->key, &key1))
2168 continue;
2169
2170 /*
2171 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
2172 * be paired with each other and no other futex ops.
2173 *
2174 * We should never be requeueing a futex_q with a pi_state,
2175 * which is awaiting a futex_unlock_pi().
2176 */
2177 if ((requeue_pi && !this->rt_waiter) ||
2178 (!requeue_pi && this->rt_waiter) ||
2179 this->pi_state) {
2180 ret = -EINVAL;
2181 break;
2182 }
2183
2184 /*
2185 * Wake nr_wake waiters. For requeue_pi, if we acquired the
2186 * lock, we already woke the top_waiter. If not, it will be
2187 * woken by futex_unlock_pi().
2188 */
2189 if (++task_count <= nr_wake && !requeue_pi) {
2190 mark_wake_futex(&wake_q, this);
2191 continue;
2192 }
2193
2194 /* Ensure we requeue to the expected futex for requeue_pi. */
2195 if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
2196 ret = -EINVAL;
2197 break;
2198 }
2199
2200 /*
2201 * Requeue nr_requeue waiters and possibly one more in the case
2202 * of requeue_pi if we couldn't acquire the lock atomically.
2203 */
2204 if (requeue_pi) {
2205 /* Prepare the waiter to take the rt_mutex. */
2206 get_pi_state(pi_state);
2207 this->pi_state = pi_state;
2208 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
2209 this->rt_waiter,
2210 this->task);
2211 if (ret == 1) {
2212 /* We got the lock. */
2213 requeue_pi_wake_futex(this, &key2, hb2);
2214 drop_count++;
2215 continue;
2216 } else if (ret) {
2217 /* -EDEADLK */
2218 this->pi_state = NULL;
2219 put_pi_state(pi_state);
2220 goto out_unlock;
2221 }
2222 }
2223 requeue_futex(this, hb1, hb2, &key2);
2224 drop_count++;
2225 }
2226
2227 out_unlock:
2228 put_pi_state(pi_state);
2229 double_unlock_hb(hb1, hb2);
2230 wake_up_q(&wake_q);
2231 hb_waiters_dec(hb2);
2232
2233 /*
2234 * drop_futex_key_refs() must be called outside the spinlocks. During
2235 * the requeue we moved futex_q's from the hash bucket at key1 to the
2236 * one at key2 and updated their key pointer. We no longer need to
2237 * hold the references to key1.
2238 */
2239 while (--drop_count >= 0)
2240 drop_futex_key_refs(&key1);
2241
2242 out_put_keys:
2243 put_futex_key(&key2);
2244 out_put_key1:
2245 put_futex_key(&key1);
2246 out:
2247 return ret ? ret : task_count;
2248 }
2249
2250 /* The key must be already stored in q->key. */
queue_lock(struct futex_q * q)2251 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
2252 __acquires(&hb->lock)
2253 {
2254 struct futex_hash_bucket *hb;
2255
2256 hb = hash_futex(&q->key);
2257
2258 /*
2259 * Increment the counter before taking the lock so that
2260 * a potential waker won't miss a to-be-slept task that is
2261 * waiting for the spinlock. This is safe as all queue_lock()
2262 * users end up calling queue_me(). Similarly, for housekeeping,
2263 * decrement the counter at queue_unlock() when some error has
2264 * occurred and we don't end up adding the task to the list.
2265 */
2266 hb_waiters_inc(hb);
2267
2268 q->lock_ptr = &hb->lock;
2269
2270 spin_lock(&hb->lock); /* implies MB (A) */
2271 return hb;
2272 }
2273
2274 static inline void
queue_unlock(struct futex_hash_bucket * hb)2275 queue_unlock(struct futex_hash_bucket *hb)
2276 __releases(&hb->lock)
2277 {
2278 spin_unlock(&hb->lock);
2279 hb_waiters_dec(hb);
2280 }
2281
__queue_me(struct futex_q * q,struct futex_hash_bucket * hb)2282 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2283 {
2284 int prio;
2285
2286 /*
2287 * The priority used to register this element is
2288 * - either the real thread-priority for the real-time threads
2289 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2290 * - or MAX_RT_PRIO for non-RT threads.
2291 * Thus, all RT-threads are woken first in priority order, and
2292 * the others are woken last, in FIFO order.
2293 */
2294 prio = min(current->normal_prio, MAX_RT_PRIO);
2295
2296 plist_node_init(&q->list, prio);
2297 plist_add(&q->list, &hb->chain);
2298 q->task = current;
2299 }
2300
2301 /**
2302 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2303 * @q: The futex_q to enqueue
2304 * @hb: The destination hash bucket
2305 *
2306 * The hb->lock must be held by the caller, and is released here. A call to
2307 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2308 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2309 * or nothing if the unqueue is done as part of the wake process and the unqueue
2310 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2311 * an example).
2312 */
queue_me(struct futex_q * q,struct futex_hash_bucket * hb)2313 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2314 __releases(&hb->lock)
2315 {
2316 __queue_me(q, hb);
2317 spin_unlock(&hb->lock);
2318 }
2319
2320 /**
2321 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2322 * @q: The futex_q to unqueue
2323 *
2324 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2325 * be paired with exactly one earlier call to queue_me().
2326 *
2327 * Return:
2328 * 1 - if the futex_q was still queued (and we removed unqueued it);
2329 * 0 - if the futex_q was already removed by the waking thread
2330 */
unqueue_me(struct futex_q * q)2331 static int unqueue_me(struct futex_q *q)
2332 {
2333 spinlock_t *lock_ptr;
2334 int ret = 0;
2335
2336 /* In the common case we don't take the spinlock, which is nice. */
2337 retry:
2338 /*
2339 * q->lock_ptr can change between this read and the following spin_lock.
2340 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2341 * optimizing lock_ptr out of the logic below.
2342 */
2343 lock_ptr = READ_ONCE(q->lock_ptr);
2344 if (lock_ptr != NULL) {
2345 spin_lock(lock_ptr);
2346 /*
2347 * q->lock_ptr can change between reading it and
2348 * spin_lock(), causing us to take the wrong lock. This
2349 * corrects the race condition.
2350 *
2351 * Reasoning goes like this: if we have the wrong lock,
2352 * q->lock_ptr must have changed (maybe several times)
2353 * between reading it and the spin_lock(). It can
2354 * change again after the spin_lock() but only if it was
2355 * already changed before the spin_lock(). It cannot,
2356 * however, change back to the original value. Therefore
2357 * we can detect whether we acquired the correct lock.
2358 */
2359 if (unlikely(lock_ptr != q->lock_ptr)) {
2360 spin_unlock(lock_ptr);
2361 goto retry;
2362 }
2363 __unqueue_futex(q);
2364
2365 BUG_ON(q->pi_state);
2366
2367 spin_unlock(lock_ptr);
2368 ret = 1;
2369 }
2370
2371 drop_futex_key_refs(&q->key);
2372 return ret;
2373 }
2374
2375 /*
2376 * PI futexes can not be requeued and must remove themself from the
2377 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
2378 * and dropped here.
2379 */
unqueue_me_pi(struct futex_q * q)2380 static void unqueue_me_pi(struct futex_q *q)
2381 __releases(q->lock_ptr)
2382 {
2383 __unqueue_futex(q);
2384
2385 BUG_ON(!q->pi_state);
2386 put_pi_state(q->pi_state);
2387 q->pi_state = NULL;
2388
2389 spin_unlock(q->lock_ptr);
2390 }
2391
__fixup_pi_state_owner(u32 __user * uaddr,struct futex_q * q,struct task_struct * argowner)2392 static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2393 struct task_struct *argowner)
2394 {
2395 struct futex_pi_state *pi_state = q->pi_state;
2396 struct task_struct *oldowner, *newowner;
2397 u32 uval, curval, newval, newtid;
2398 int err = 0;
2399
2400 oldowner = pi_state->owner;
2401 /*
2402 * We are here because either:
2403 *
2404 * - we stole the lock and pi_state->owner needs updating to reflect
2405 * that (@argowner == current),
2406 *
2407 * or:
2408 *
2409 * - someone stole our lock and we need to fix things to point to the
2410 * new owner (@argowner == NULL).
2411 *
2412 * Either way, we have to replace the TID in the user space variable.
2413 * This must be atomic as we have to preserve the owner died bit here.
2414 *
2415 * Note: We write the user space value _before_ changing the pi_state
2416 * because we can fault here. Imagine swapped out pages or a fork
2417 * that marked all the anonymous memory readonly for cow.
2418 *
2419 * Modifying pi_state _before_ the user space value would leave the
2420 * pi_state in an inconsistent state when we fault here, because we
2421 * need to drop the locks to handle the fault. This might be observed
2422 * in the PID check in lookup_pi_state.
2423 */
2424 retry:
2425 if (!argowner) {
2426 if (oldowner != current) {
2427 /*
2428 * We raced against a concurrent self; things are
2429 * already fixed up. Nothing to do.
2430 */
2431 return 0;
2432 }
2433
2434 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
2435 /* We got the lock. pi_state is correct. Tell caller */
2436 return 1;
2437 }
2438
2439 /*
2440 * The trylock just failed, so either there is an owner or
2441 * there is a higher priority waiter than this one.
2442 */
2443 newowner = rt_mutex_owner(&pi_state->pi_mutex);
2444 /*
2445 * If the higher priority waiter has not yet taken over the
2446 * rtmutex then newowner is NULL. We can't return here with
2447 * that state because it's inconsistent vs. the user space
2448 * state. So drop the locks and try again. It's a valid
2449 * situation and not any different from the other retry
2450 * conditions.
2451 */
2452 if (unlikely(!newowner)) {
2453 err = -EAGAIN;
2454 goto handle_fault;
2455 }
2456 } else {
2457 WARN_ON_ONCE(argowner != current);
2458 if (oldowner == current) {
2459 /*
2460 * We raced against a concurrent self; things are
2461 * already fixed up. Nothing to do.
2462 */
2463 return 1;
2464 }
2465 newowner = argowner;
2466 }
2467
2468 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
2469 /* Owner died? */
2470 if (!pi_state->owner)
2471 newtid |= FUTEX_OWNER_DIED;
2472
2473 if (get_futex_value_locked(&uval, uaddr))
2474 goto handle_fault;
2475
2476 for (;;) {
2477 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2478
2479 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
2480 goto handle_fault;
2481 if (curval == uval)
2482 break;
2483 uval = curval;
2484 }
2485
2486 /*
2487 * We fixed up user space. Now we need to fix the pi_state
2488 * itself.
2489 */
2490 pi_state_update_owner(pi_state, newowner);
2491
2492 return argowner == current;
2493
2494 /*
2495 * To handle the page fault we need to drop the locks here. That gives
2496 * the other task (either the highest priority waiter itself or the
2497 * task which stole the rtmutex) the chance to try the fixup of the
2498 * pi_state. So once we are back from handling the fault we need to
2499 * check the pi_state after reacquiring the locks and before trying to
2500 * do another fixup. When the fixup has been done already we simply
2501 * return.
2502 *
2503 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2504 * drop hb->lock since the caller owns the hb -> futex_q relation.
2505 * Dropping the pi_mutex->wait_lock requires the state revalidate.
2506 */
2507 handle_fault:
2508 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2509 spin_unlock(q->lock_ptr);
2510
2511 err = fault_in_user_writeable(uaddr);
2512
2513 spin_lock(q->lock_ptr);
2514 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2515
2516 /*
2517 * Check if someone else fixed it for us:
2518 */
2519 if (pi_state->owner != oldowner)
2520 return argowner == current;
2521
2522 /* Retry if err was -EAGAIN or the fault in succeeded */
2523 if (!err)
2524 goto retry;
2525
2526 /*
2527 * fault_in_user_writeable() failed so user state is immutable. At
2528 * best we can make the kernel state consistent but user state will
2529 * be most likely hosed and any subsequent unlock operation will be
2530 * rejected due to PI futex rule [10].
2531 *
2532 * Ensure that the rtmutex owner is also the pi_state owner despite
2533 * the user space value claiming something different. There is no
2534 * point in unlocking the rtmutex if current is the owner as it
2535 * would need to wait until the next waiter has taken the rtmutex
2536 * to guarantee consistent state. Keep it simple. Userspace asked
2537 * for this wreckaged state.
2538 *
2539 * The rtmutex has an owner - either current or some other
2540 * task. See the EAGAIN loop above.
2541 */
2542 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
2543
2544 return err;
2545 }
2546
fixup_pi_state_owner(u32 __user * uaddr,struct futex_q * q,struct task_struct * argowner)2547 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2548 struct task_struct *argowner)
2549 {
2550 struct futex_pi_state *pi_state = q->pi_state;
2551 int ret;
2552
2553 lockdep_assert_held(q->lock_ptr);
2554
2555 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2556 ret = __fixup_pi_state_owner(uaddr, q, argowner);
2557 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2558 return ret;
2559 }
2560
2561 static long futex_wait_restart(struct restart_block *restart);
2562
2563 /**
2564 * fixup_owner() - Post lock pi_state and corner case management
2565 * @uaddr: user address of the futex
2566 * @q: futex_q (contains pi_state and access to the rt_mutex)
2567 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2568 *
2569 * After attempting to lock an rt_mutex, this function is called to cleanup
2570 * the pi_state owner as well as handle race conditions that may allow us to
2571 * acquire the lock. Must be called with the hb lock held.
2572 *
2573 * Return:
2574 * 1 - success, lock taken;
2575 * 0 - success, lock not taken;
2576 * <0 - on error (-EFAULT)
2577 */
fixup_owner(u32 __user * uaddr,struct futex_q * q,int locked)2578 static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
2579 {
2580 if (locked) {
2581 /*
2582 * Got the lock. We might not be the anticipated owner if we
2583 * did a lock-steal - fix up the PI-state in that case:
2584 *
2585 * Speculative pi_state->owner read (we don't hold wait_lock);
2586 * since we own the lock pi_state->owner == current is the
2587 * stable state, anything else needs more attention.
2588 */
2589 if (q->pi_state->owner != current)
2590 return fixup_pi_state_owner(uaddr, q, current);
2591 return 1;
2592 }
2593
2594 /*
2595 * If we didn't get the lock; check if anybody stole it from us. In
2596 * that case, we need to fix up the uval to point to them instead of
2597 * us, otherwise bad things happen. [10]
2598 *
2599 * Another speculative read; pi_state->owner == current is unstable
2600 * but needs our attention.
2601 */
2602 if (q->pi_state->owner == current)
2603 return fixup_pi_state_owner(uaddr, q, NULL);
2604
2605 /*
2606 * Paranoia check. If we did not take the lock, then we should not be
2607 * the owner of the rt_mutex. Warn and establish consistent state.
2608 */
2609 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
2610 return fixup_pi_state_owner(uaddr, q, current);
2611
2612 return 0;
2613 }
2614
2615 /**
2616 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2617 * @hb: the futex hash bucket, must be locked by the caller
2618 * @q: the futex_q to queue up on
2619 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
2620 */
futex_wait_queue_me(struct futex_hash_bucket * hb,struct futex_q * q,struct hrtimer_sleeper * timeout)2621 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
2622 struct hrtimer_sleeper *timeout)
2623 {
2624 /*
2625 * The task state is guaranteed to be set before another task can
2626 * wake it. set_current_state() is implemented using smp_store_mb() and
2627 * queue_me() calls spin_unlock() upon completion, both serializing
2628 * access to the hash list and forcing another memory barrier.
2629 */
2630 set_current_state(TASK_INTERRUPTIBLE);
2631 queue_me(q, hb);
2632
2633 /* Arm the timer */
2634 if (timeout)
2635 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
2636
2637 /*
2638 * If we have been removed from the hash list, then another task
2639 * has tried to wake us, and we can skip the call to schedule().
2640 */
2641 if (likely(!plist_node_empty(&q->list))) {
2642 /*
2643 * If the timer has already expired, current will already be
2644 * flagged for rescheduling. Only call schedule if there
2645 * is no timeout, or if it has yet to expire.
2646 */
2647 if (!timeout || timeout->task)
2648 freezable_schedule();
2649 }
2650 __set_current_state(TASK_RUNNING);
2651 }
2652
2653 /**
2654 * futex_wait_setup() - Prepare to wait on a futex
2655 * @uaddr: the futex userspace address
2656 * @val: the expected value
2657 * @flags: futex flags (FLAGS_SHARED, etc.)
2658 * @q: the associated futex_q
2659 * @hb: storage for hash_bucket pointer to be returned to caller
2660 *
2661 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2662 * compare it with the expected value. Handle atomic faults internally.
2663 * Return with the hb lock held and a q.key reference on success, and unlocked
2664 * with no q.key reference on failure.
2665 *
2666 * Return:
2667 * 0 - uaddr contains val and hb has been locked;
2668 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
2669 */
futex_wait_setup(u32 __user * uaddr,u32 val,unsigned int flags,struct futex_q * q,struct futex_hash_bucket ** hb)2670 static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
2671 struct futex_q *q, struct futex_hash_bucket **hb)
2672 {
2673 u32 uval;
2674 int ret;
2675
2676 /*
2677 * Access the page AFTER the hash-bucket is locked.
2678 * Order is important:
2679 *
2680 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2681 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2682 *
2683 * The basic logical guarantee of a futex is that it blocks ONLY
2684 * if cond(var) is known to be true at the time of blocking, for
2685 * any cond. If we locked the hash-bucket after testing *uaddr, that
2686 * would open a race condition where we could block indefinitely with
2687 * cond(var) false, which would violate the guarantee.
2688 *
2689 * On the other hand, we insert q and release the hash-bucket only
2690 * after testing *uaddr. This guarantees that futex_wait() will NOT
2691 * absorb a wakeup if *uaddr does not match the desired values
2692 * while the syscall executes.
2693 */
2694 retry:
2695 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
2696 if (unlikely(ret != 0))
2697 return ret;
2698
2699 retry_private:
2700 *hb = queue_lock(q);
2701
2702 ret = get_futex_value_locked(&uval, uaddr);
2703
2704 if (ret) {
2705 queue_unlock(*hb);
2706
2707 ret = get_user(uval, uaddr);
2708 if (ret)
2709 goto out;
2710
2711 if (!(flags & FLAGS_SHARED))
2712 goto retry_private;
2713
2714 put_futex_key(&q->key);
2715 goto retry;
2716 }
2717
2718 if (uval != val) {
2719 queue_unlock(*hb);
2720 ret = -EWOULDBLOCK;
2721 }
2722
2723 out:
2724 if (ret)
2725 put_futex_key(&q->key);
2726 return ret;
2727 }
2728
futex_wait(u32 __user * uaddr,unsigned int flags,u32 val,ktime_t * abs_time,u32 bitset)2729 static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2730 ktime_t *abs_time, u32 bitset)
2731 {
2732 struct hrtimer_sleeper timeout, *to = NULL;
2733 struct restart_block *restart;
2734 struct futex_hash_bucket *hb;
2735 struct futex_q q = futex_q_init;
2736 int ret;
2737
2738 if (!bitset)
2739 return -EINVAL;
2740 q.bitset = bitset;
2741
2742 if (abs_time) {
2743 to = &timeout;
2744
2745 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2746 CLOCK_REALTIME : CLOCK_MONOTONIC,
2747 HRTIMER_MODE_ABS);
2748 hrtimer_init_sleeper(to, current);
2749 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2750 current->timer_slack_ns);
2751 }
2752
2753 retry:
2754 /*
2755 * Prepare to wait on uaddr. On success, holds hb lock and increments
2756 * q.key refs.
2757 */
2758 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
2759 if (ret)
2760 goto out;
2761
2762 /* queue_me and wait for wakeup, timeout, or a signal. */
2763 futex_wait_queue_me(hb, &q, to);
2764
2765 /* If we were woken (and unqueued), we succeeded, whatever. */
2766 ret = 0;
2767 /* unqueue_me() drops q.key ref */
2768 if (!unqueue_me(&q))
2769 goto out;
2770 ret = -ETIMEDOUT;
2771 if (to && !to->task)
2772 goto out;
2773
2774 /*
2775 * We expect signal_pending(current), but we might be the
2776 * victim of a spurious wakeup as well.
2777 */
2778 if (!signal_pending(current))
2779 goto retry;
2780
2781 ret = -ERESTARTSYS;
2782 if (!abs_time)
2783 goto out;
2784
2785 restart = ¤t->restart_block;
2786 restart->fn = futex_wait_restart;
2787 restart->futex.uaddr = uaddr;
2788 restart->futex.val = val;
2789 restart->futex.time = abs_time->tv64;
2790 restart->futex.bitset = bitset;
2791 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
2792
2793 ret = -ERESTART_RESTARTBLOCK;
2794
2795 out:
2796 if (to) {
2797 hrtimer_cancel(&to->timer);
2798 destroy_hrtimer_on_stack(&to->timer);
2799 }
2800 return ret;
2801 }
2802
2803
futex_wait_restart(struct restart_block * restart)2804 static long futex_wait_restart(struct restart_block *restart)
2805 {
2806 u32 __user *uaddr = restart->futex.uaddr;
2807 ktime_t t, *tp = NULL;
2808
2809 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2810 t.tv64 = restart->futex.time;
2811 tp = &t;
2812 }
2813 restart->fn = do_no_restart_syscall;
2814
2815 return (long)futex_wait(uaddr, restart->futex.flags,
2816 restart->futex.val, tp, restart->futex.bitset);
2817 }
2818
2819
2820 /*
2821 * Userspace tried a 0 -> TID atomic transition of the futex value
2822 * and failed. The kernel side here does the whole locking operation:
2823 * if there are waiters then it will block as a consequence of relying
2824 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2825 * a 0 value of the futex too.).
2826 *
2827 * Also serves as futex trylock_pi()'ing, and due semantics.
2828 */
futex_lock_pi(u32 __user * uaddr,unsigned int flags,ktime_t * time,int trylock)2829 static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
2830 ktime_t *time, int trylock)
2831 {
2832 struct hrtimer_sleeper timeout, *to = NULL;
2833 struct task_struct *exiting = NULL;
2834 struct rt_mutex_waiter rt_waiter;
2835 struct futex_hash_bucket *hb;
2836 struct futex_q q = futex_q_init;
2837 int res, ret;
2838
2839 if (refill_pi_state_cache())
2840 return -ENOMEM;
2841
2842 if (time) {
2843 to = &timeout;
2844 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
2845 HRTIMER_MODE_ABS);
2846 hrtimer_init_sleeper(to, current);
2847 hrtimer_set_expires(&to->timer, *time);
2848 }
2849
2850 retry:
2851 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
2852 if (unlikely(ret != 0))
2853 goto out;
2854
2855 retry_private:
2856 hb = queue_lock(&q);
2857
2858 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
2859 &exiting, 0);
2860 if (unlikely(ret)) {
2861 /*
2862 * Atomic work succeeded and we got the lock,
2863 * or failed. Either way, we do _not_ block.
2864 */
2865 switch (ret) {
2866 case 1:
2867 /* We got the lock. */
2868 ret = 0;
2869 goto out_unlock_put_key;
2870 case -EFAULT:
2871 goto uaddr_faulted;
2872 case -EBUSY:
2873 case -EAGAIN:
2874 /*
2875 * Two reasons for this:
2876 * - EBUSY: Task is exiting and we just wait for the
2877 * exit to complete.
2878 * - EAGAIN: The user space value changed.
2879 */
2880 queue_unlock(hb);
2881 put_futex_key(&q.key);
2882 /*
2883 * Handle the case where the owner is in the middle of
2884 * exiting. Wait for the exit to complete otherwise
2885 * this task might loop forever, aka. live lock.
2886 */
2887 wait_for_owner_exiting(ret, exiting);
2888 cond_resched();
2889 goto retry;
2890 default:
2891 goto out_unlock_put_key;
2892 }
2893 }
2894
2895 WARN_ON(!q.pi_state);
2896
2897 /*
2898 * Only actually queue now that the atomic ops are done:
2899 */
2900 __queue_me(&q, hb);
2901
2902 if (trylock) {
2903 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
2904 /* Fixup the trylock return value: */
2905 ret = ret ? 0 : -EWOULDBLOCK;
2906 goto no_block;
2907 }
2908
2909 /*
2910 * We must add ourselves to the rt_mutex waitlist while holding hb->lock
2911 * such that the hb and rt_mutex wait lists match.
2912 */
2913 rt_mutex_init_waiter(&rt_waiter);
2914 ret = rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
2915 if (ret) {
2916 if (ret == 1)
2917 ret = 0;
2918
2919 goto no_block;
2920 }
2921
2922 spin_unlock(q.lock_ptr);
2923
2924 if (unlikely(to))
2925 hrtimer_start_expires(&to->timer, HRTIMER_MODE_ABS);
2926
2927 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
2928
2929 spin_lock(q.lock_ptr);
2930 /*
2931 * If we failed to acquire the lock (signal/timeout), we must
2932 * first acquire the hb->lock before removing the lock from the
2933 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex
2934 * wait lists consistent.
2935 */
2936 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
2937 ret = 0;
2938
2939 no_block:
2940 /*
2941 * Fixup the pi_state owner and possibly acquire the lock if we
2942 * haven't already.
2943 */
2944 res = fixup_owner(uaddr, &q, !ret);
2945 /*
2946 * If fixup_owner() returned an error, proprogate that. If it acquired
2947 * the lock, clear our -ETIMEDOUT or -EINTR.
2948 */
2949 if (res)
2950 ret = (res < 0) ? res : 0;
2951
2952 /* Unqueue and drop the lock */
2953 unqueue_me_pi(&q);
2954
2955 goto out_put_key;
2956
2957 out_unlock_put_key:
2958 queue_unlock(hb);
2959
2960 out_put_key:
2961 put_futex_key(&q.key);
2962 out:
2963 if (to) {
2964 hrtimer_cancel(&to->timer);
2965 destroy_hrtimer_on_stack(&to->timer);
2966 }
2967 return ret != -EINTR ? ret : -ERESTARTNOINTR;
2968
2969 uaddr_faulted:
2970 queue_unlock(hb);
2971
2972 ret = fault_in_user_writeable(uaddr);
2973 if (ret)
2974 goto out_put_key;
2975
2976 if (!(flags & FLAGS_SHARED))
2977 goto retry_private;
2978
2979 put_futex_key(&q.key);
2980 goto retry;
2981 }
2982
2983 /*
2984 * Userspace attempted a TID -> 0 atomic transition, and failed.
2985 * This is the in-kernel slowpath: we look up the PI state (if any),
2986 * and do the rt-mutex unlock.
2987 */
futex_unlock_pi(u32 __user * uaddr,unsigned int flags)2988 static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
2989 {
2990 u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
2991 union futex_key key = FUTEX_KEY_INIT;
2992 struct futex_hash_bucket *hb;
2993 struct futex_q *match;
2994 int ret;
2995
2996 retry:
2997 if (get_user(uval, uaddr))
2998 return -EFAULT;
2999 /*
3000 * We release only a lock we actually own:
3001 */
3002 if ((uval & FUTEX_TID_MASK) != vpid)
3003 return -EPERM;
3004
3005 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
3006 if (ret)
3007 return ret;
3008
3009 hb = hash_futex(&key);
3010 spin_lock(&hb->lock);
3011
3012 /*
3013 * Check waiters first. We do not trust user space values at
3014 * all and we at least want to know if user space fiddled
3015 * with the futex value instead of blindly unlocking.
3016 */
3017 match = futex_top_waiter(hb, &key);
3018 if (match) {
3019 struct futex_pi_state *pi_state = match->pi_state;
3020
3021 ret = -EINVAL;
3022 if (!pi_state)
3023 goto out_unlock;
3024
3025 /*
3026 * If current does not own the pi_state then the futex is
3027 * inconsistent and user space fiddled with the futex value.
3028 */
3029 if (pi_state->owner != current)
3030 goto out_unlock;
3031
3032 get_pi_state(pi_state);
3033 /*
3034 * Since modifying the wait_list is done while holding both
3035 * hb->lock and wait_lock, holding either is sufficient to
3036 * observe it.
3037 *
3038 * By taking wait_lock while still holding hb->lock, we ensure
3039 * there is no point where we hold neither; and therefore
3040 * wake_futex_pi() must observe a state consistent with what we
3041 * observed.
3042 */
3043 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
3044 spin_unlock(&hb->lock);
3045
3046 ret = wake_futex_pi(uaddr, uval, pi_state);
3047
3048 put_pi_state(pi_state);
3049
3050 /*
3051 * Success, we're done! No tricky corner cases.
3052 */
3053 if (!ret)
3054 goto out_putkey;
3055 /*
3056 * The atomic access to the futex value generated a
3057 * pagefault, so retry the user-access and the wakeup:
3058 */
3059 if (ret == -EFAULT)
3060 goto pi_faulted;
3061 /*
3062 * A unconditional UNLOCK_PI op raced against a waiter
3063 * setting the FUTEX_WAITERS bit. Try again.
3064 */
3065 if (ret == -EAGAIN) {
3066 put_futex_key(&key);
3067 goto retry;
3068 }
3069 /*
3070 * wake_futex_pi has detected invalid state. Tell user
3071 * space.
3072 */
3073 goto out_putkey;
3074 }
3075
3076 /*
3077 * We have no kernel internal state, i.e. no waiters in the
3078 * kernel. Waiters which are about to queue themselves are stuck
3079 * on hb->lock. So we can safely ignore them. We do neither
3080 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3081 * owner.
3082 */
3083 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, 0)) {
3084 spin_unlock(&hb->lock);
3085 goto pi_faulted;
3086 }
3087
3088 /*
3089 * If uval has changed, let user space handle it.
3090 */
3091 ret = (curval == uval) ? 0 : -EAGAIN;
3092
3093 out_unlock:
3094 spin_unlock(&hb->lock);
3095 out_putkey:
3096 put_futex_key(&key);
3097 return ret;
3098
3099 pi_faulted:
3100 put_futex_key(&key);
3101
3102 ret = fault_in_user_writeable(uaddr);
3103 if (!ret)
3104 goto retry;
3105
3106 return ret;
3107 }
3108
3109 /**
3110 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
3111 * @hb: the hash_bucket futex_q was original enqueued on
3112 * @q: the futex_q woken while waiting to be requeued
3113 * @key2: the futex_key of the requeue target futex
3114 * @timeout: the timeout associated with the wait (NULL if none)
3115 *
3116 * Detect if the task was woken on the initial futex as opposed to the requeue
3117 * target futex. If so, determine if it was a timeout or a signal that caused
3118 * the wakeup and return the appropriate error code to the caller. Must be
3119 * called with the hb lock held.
3120 *
3121 * Return:
3122 * 0 = no early wakeup detected;
3123 * <0 = -ETIMEDOUT or -ERESTARTNOINTR
3124 */
3125 static inline
handle_early_requeue_pi_wakeup(struct futex_hash_bucket * hb,struct futex_q * q,union futex_key * key2,struct hrtimer_sleeper * timeout)3126 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
3127 struct futex_q *q, union futex_key *key2,
3128 struct hrtimer_sleeper *timeout)
3129 {
3130 int ret = 0;
3131
3132 /*
3133 * With the hb lock held, we avoid races while we process the wakeup.
3134 * We only need to hold hb (and not hb2) to ensure atomicity as the
3135 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
3136 * It can't be requeued from uaddr2 to something else since we don't
3137 * support a PI aware source futex for requeue.
3138 */
3139 if (!match_futex(&q->key, key2)) {
3140 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
3141 /*
3142 * We were woken prior to requeue by a timeout or a signal.
3143 * Unqueue the futex_q and determine which it was.
3144 */
3145 plist_del(&q->list, &hb->chain);
3146 hb_waiters_dec(hb);
3147
3148 /* Handle spurious wakeups gracefully */
3149 ret = -EWOULDBLOCK;
3150 if (timeout && !timeout->task)
3151 ret = -ETIMEDOUT;
3152 else if (signal_pending(current))
3153 ret = -ERESTARTNOINTR;
3154 }
3155 return ret;
3156 }
3157
3158 /**
3159 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
3160 * @uaddr: the futex we initially wait on (non-pi)
3161 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
3162 * the same type, no requeueing from private to shared, etc.
3163 * @val: the expected value of uaddr
3164 * @abs_time: absolute timeout
3165 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
3166 * @uaddr2: the pi futex we will take prior to returning to user-space
3167 *
3168 * The caller will wait on uaddr and will be requeued by futex_requeue() to
3169 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
3170 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
3171 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
3172 * without one, the pi logic would not know which task to boost/deboost, if
3173 * there was a need to.
3174 *
3175 * We call schedule in futex_wait_queue_me() when we enqueue and return there
3176 * via the following--
3177 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
3178 * 2) wakeup on uaddr2 after a requeue
3179 * 3) signal
3180 * 4) timeout
3181 *
3182 * If 3, cleanup and return -ERESTARTNOINTR.
3183 *
3184 * If 2, we may then block on trying to take the rt_mutex and return via:
3185 * 5) successful lock
3186 * 6) signal
3187 * 7) timeout
3188 * 8) other lock acquisition failure
3189 *
3190 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
3191 *
3192 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
3193 *
3194 * Return:
3195 * 0 - On success;
3196 * <0 - On error
3197 */
futex_wait_requeue_pi(u32 __user * uaddr,unsigned int flags,u32 val,ktime_t * abs_time,u32 bitset,u32 __user * uaddr2)3198 static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
3199 u32 val, ktime_t *abs_time, u32 bitset,
3200 u32 __user *uaddr2)
3201 {
3202 struct hrtimer_sleeper timeout, *to = NULL;
3203 struct rt_mutex_waiter rt_waiter;
3204 struct futex_hash_bucket *hb;
3205 union futex_key key2 = FUTEX_KEY_INIT;
3206 struct futex_q q = futex_q_init;
3207 int res, ret;
3208
3209 if (uaddr == uaddr2)
3210 return -EINVAL;
3211
3212 if (!bitset)
3213 return -EINVAL;
3214
3215 if (abs_time) {
3216 to = &timeout;
3217 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
3218 CLOCK_REALTIME : CLOCK_MONOTONIC,
3219 HRTIMER_MODE_ABS);
3220 hrtimer_init_sleeper(to, current);
3221 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
3222 current->timer_slack_ns);
3223 }
3224
3225 /*
3226 * The waiter is allocated on our stack, manipulated by the requeue
3227 * code while we sleep on uaddr.
3228 */
3229 rt_mutex_init_waiter(&rt_waiter);
3230
3231 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
3232 if (unlikely(ret != 0))
3233 goto out;
3234
3235 q.bitset = bitset;
3236 q.rt_waiter = &rt_waiter;
3237 q.requeue_pi_key = &key2;
3238
3239 /*
3240 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
3241 * count.
3242 */
3243 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
3244 if (ret)
3245 goto out_key2;
3246
3247 /*
3248 * The check above which compares uaddrs is not sufficient for
3249 * shared futexes. We need to compare the keys:
3250 */
3251 if (match_futex(&q.key, &key2)) {
3252 queue_unlock(hb);
3253 ret = -EINVAL;
3254 goto out_put_keys;
3255 }
3256
3257 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
3258 futex_wait_queue_me(hb, &q, to);
3259
3260 spin_lock(&hb->lock);
3261 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
3262 spin_unlock(&hb->lock);
3263 if (ret)
3264 goto out_put_keys;
3265
3266 /*
3267 * In order for us to be here, we know our q.key == key2, and since
3268 * we took the hb->lock above, we also know that futex_requeue() has
3269 * completed and we no longer have to concern ourselves with a wakeup
3270 * race with the atomic proxy lock acquisition by the requeue code. The
3271 * futex_requeue dropped our key1 reference and incremented our key2
3272 * reference count.
3273 */
3274
3275 /* Check if the requeue code acquired the second futex for us. */
3276 if (!q.rt_waiter) {
3277 /*
3278 * Got the lock. We might not be the anticipated owner if we
3279 * did a lock-steal - fix up the PI-state in that case.
3280 */
3281 if (q.pi_state && (q.pi_state->owner != current)) {
3282 spin_lock(q.lock_ptr);
3283 ret = fixup_pi_state_owner(uaddr2, &q, current);
3284 /*
3285 * Drop the reference to the pi state which
3286 * the requeue_pi() code acquired for us.
3287 */
3288 put_pi_state(q.pi_state);
3289 spin_unlock(q.lock_ptr);
3290 /*
3291 * Adjust the return value. It's either -EFAULT or
3292 * success (1) but the caller expects 0 for success.
3293 */
3294 ret = ret < 0 ? ret : 0;
3295 }
3296 } else {
3297 struct rt_mutex *pi_mutex;
3298
3299 /*
3300 * We have been woken up by futex_unlock_pi(), a timeout, or a
3301 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
3302 * the pi_state.
3303 */
3304 WARN_ON(!q.pi_state);
3305 pi_mutex = &q.pi_state->pi_mutex;
3306 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
3307
3308 spin_lock(q.lock_ptr);
3309 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
3310 ret = 0;
3311
3312 debug_rt_mutex_free_waiter(&rt_waiter);
3313 /*
3314 * Fixup the pi_state owner and possibly acquire the lock if we
3315 * haven't already.
3316 */
3317 res = fixup_owner(uaddr2, &q, !ret);
3318 /*
3319 * If fixup_owner() returned an error, proprogate that. If it
3320 * acquired the lock, clear -ETIMEDOUT or -EINTR.
3321 */
3322 if (res)
3323 ret = (res < 0) ? res : 0;
3324
3325 /* Unqueue and drop the lock. */
3326 unqueue_me_pi(&q);
3327 }
3328
3329 if (ret == -EINTR) {
3330 /*
3331 * We've already been requeued, but cannot restart by calling
3332 * futex_lock_pi() directly. We could restart this syscall, but
3333 * it would detect that the user space "val" changed and return
3334 * -EWOULDBLOCK. Save the overhead of the restart and return
3335 * -EWOULDBLOCK directly.
3336 */
3337 ret = -EWOULDBLOCK;
3338 }
3339
3340 out_put_keys:
3341 put_futex_key(&q.key);
3342 out_key2:
3343 put_futex_key(&key2);
3344
3345 out:
3346 if (to) {
3347 hrtimer_cancel(&to->timer);
3348 destroy_hrtimer_on_stack(&to->timer);
3349 }
3350 return ret;
3351 }
3352
3353 /*
3354 * Support for robust futexes: the kernel cleans up held futexes at
3355 * thread exit time.
3356 *
3357 * Implementation: user-space maintains a per-thread list of locks it
3358 * is holding. Upon do_exit(), the kernel carefully walks this list,
3359 * and marks all locks that are owned by this thread with the
3360 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
3361 * always manipulated with the lock held, so the list is private and
3362 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
3363 * field, to allow the kernel to clean up if the thread dies after
3364 * acquiring the lock, but just before it could have added itself to
3365 * the list. There can only be one such pending lock.
3366 */
3367
3368 /**
3369 * sys_set_robust_list() - Set the robust-futex list head of a task
3370 * @head: pointer to the list-head
3371 * @len: length of the list-head, as userspace expects
3372 */
SYSCALL_DEFINE2(set_robust_list,struct robust_list_head __user *,head,size_t,len)3373 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
3374 size_t, len)
3375 {
3376 if (!futex_cmpxchg_enabled)
3377 return -ENOSYS;
3378 /*
3379 * The kernel knows only one size for now:
3380 */
3381 if (unlikely(len != sizeof(*head)))
3382 return -EINVAL;
3383
3384 current->robust_list = head;
3385
3386 return 0;
3387 }
3388
3389 /**
3390 * sys_get_robust_list() - Get the robust-futex list head of a task
3391 * @pid: pid of the process [zero for current task]
3392 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
3393 * @len_ptr: pointer to a length field, the kernel fills in the header size
3394 */
SYSCALL_DEFINE3(get_robust_list,int,pid,struct robust_list_head __user * __user *,head_ptr,size_t __user *,len_ptr)3395 SYSCALL_DEFINE3(get_robust_list, int, pid,
3396 struct robust_list_head __user * __user *, head_ptr,
3397 size_t __user *, len_ptr)
3398 {
3399 struct robust_list_head __user *head;
3400 unsigned long ret;
3401 struct task_struct *p;
3402
3403 if (!futex_cmpxchg_enabled)
3404 return -ENOSYS;
3405
3406 rcu_read_lock();
3407
3408 ret = -ESRCH;
3409 if (!pid)
3410 p = current;
3411 else {
3412 p = find_task_by_vpid(pid);
3413 if (!p)
3414 goto err_unlock;
3415 }
3416
3417 ret = -EPERM;
3418 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3419 goto err_unlock;
3420
3421 head = p->robust_list;
3422 rcu_read_unlock();
3423
3424 if (put_user(sizeof(*head), len_ptr))
3425 return -EFAULT;
3426 return put_user(head, head_ptr);
3427
3428 err_unlock:
3429 rcu_read_unlock();
3430
3431 return ret;
3432 }
3433
3434 /*
3435 * Process a futex-list entry, check whether it's owned by the
3436 * dying task, and do notification if so:
3437 */
handle_futex_death(u32 __user * uaddr,struct task_struct * curr,int pi)3438 static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
3439 {
3440 u32 uval, uninitialized_var(nval), mval;
3441
3442 /* Futex address must be 32bit aligned */
3443 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3444 return -1;
3445
3446 retry:
3447 if (get_user(uval, uaddr))
3448 return -1;
3449
3450 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
3451 /*
3452 * Ok, this dying thread is truly holding a futex
3453 * of interest. Set the OWNER_DIED bit atomically
3454 * via cmpxchg, and if the value had FUTEX_WAITERS
3455 * set, wake up a waiter (if any). (We have to do a
3456 * futex_wake() even if OWNER_DIED is already set -
3457 * to handle the rare but possible case of recursive
3458 * thread-death.) The rest of the cleanup is done in
3459 * userspace.
3460 */
3461 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3462 /*
3463 * We are not holding a lock here, but we want to have
3464 * the pagefault_disable/enable() protection because
3465 * we want to handle the fault gracefully. If the
3466 * access fails we try to fault in the futex with R/W
3467 * verification via get_user_pages. get_user() above
3468 * does not guarantee R/W access. If that fails we
3469 * give up and leave the futex locked.
3470 */
3471 if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
3472 if (fault_in_user_writeable(uaddr))
3473 return -1;
3474 goto retry;
3475 }
3476 if (nval != uval)
3477 goto retry;
3478
3479 /*
3480 * Wake robust non-PI futexes here. The wakeup of
3481 * PI futexes happens in exit_pi_state():
3482 */
3483 if (!pi && (uval & FUTEX_WAITERS))
3484 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3485 }
3486 return 0;
3487 }
3488
3489 /*
3490 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3491 */
fetch_robust_entry(struct robust_list __user ** entry,struct robust_list __user * __user * head,unsigned int * pi)3492 static inline int fetch_robust_entry(struct robust_list __user **entry,
3493 struct robust_list __user * __user *head,
3494 unsigned int *pi)
3495 {
3496 unsigned long uentry;
3497
3498 if (get_user(uentry, (unsigned long __user *)head))
3499 return -EFAULT;
3500
3501 *entry = (void __user *)(uentry & ~1UL);
3502 *pi = uentry & 1;
3503
3504 return 0;
3505 }
3506
3507 /*
3508 * Walk curr->robust_list (very carefully, it's a userspace list!)
3509 * and mark any locks found there dead, and notify any waiters.
3510 *
3511 * We silently return on any sign of list-walking problem.
3512 */
exit_robust_list(struct task_struct * curr)3513 static void exit_robust_list(struct task_struct *curr)
3514 {
3515 struct robust_list_head __user *head = curr->robust_list;
3516 struct robust_list __user *entry, *next_entry, *pending;
3517 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3518 unsigned int uninitialized_var(next_pi);
3519 unsigned long futex_offset;
3520 int rc;
3521
3522 if (!futex_cmpxchg_enabled)
3523 return;
3524
3525 /*
3526 * Fetch the list head (which was registered earlier, via
3527 * sys_set_robust_list()):
3528 */
3529 if (fetch_robust_entry(&entry, &head->list.next, &pi))
3530 return;
3531 /*
3532 * Fetch the relative futex offset:
3533 */
3534 if (get_user(futex_offset, &head->futex_offset))
3535 return;
3536 /*
3537 * Fetch any possibly pending lock-add first, and handle it
3538 * if it exists:
3539 */
3540 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
3541 return;
3542
3543 next_entry = NULL; /* avoid warning with gcc */
3544 while (entry != &head->list) {
3545 /*
3546 * Fetch the next entry in the list before calling
3547 * handle_futex_death:
3548 */
3549 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
3550 /*
3551 * A pending lock might already be on the list, so
3552 * don't process it twice:
3553 */
3554 if (entry != pending)
3555 if (handle_futex_death((void __user *)entry + futex_offset,
3556 curr, pi))
3557 return;
3558 if (rc)
3559 return;
3560 entry = next_entry;
3561 pi = next_pi;
3562 /*
3563 * Avoid excessively long or circular lists:
3564 */
3565 if (!--limit)
3566 break;
3567
3568 cond_resched();
3569 }
3570
3571 if (pending)
3572 handle_futex_death((void __user *)pending + futex_offset,
3573 curr, pip);
3574 }
3575
futex_cleanup(struct task_struct * tsk)3576 static void futex_cleanup(struct task_struct *tsk)
3577 {
3578 if (unlikely(tsk->robust_list)) {
3579 exit_robust_list(tsk);
3580 tsk->robust_list = NULL;
3581 }
3582
3583 #ifdef CONFIG_COMPAT
3584 if (unlikely(tsk->compat_robust_list)) {
3585 compat_exit_robust_list(tsk);
3586 tsk->compat_robust_list = NULL;
3587 }
3588 #endif
3589
3590 if (unlikely(!list_empty(&tsk->pi_state_list)))
3591 exit_pi_state_list(tsk);
3592 }
3593
3594 /**
3595 * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
3596 * @tsk: task to set the state on
3597 *
3598 * Set the futex exit state of the task lockless. The futex waiter code
3599 * observes that state when a task is exiting and loops until the task has
3600 * actually finished the futex cleanup. The worst case for this is that the
3601 * waiter runs through the wait loop until the state becomes visible.
3602 *
3603 * This is called from the recursive fault handling path in do_exit().
3604 *
3605 * This is best effort. Either the futex exit code has run already or
3606 * not. If the OWNER_DIED bit has been set on the futex then the waiter can
3607 * take it over. If not, the problem is pushed back to user space. If the
3608 * futex exit code did not run yet, then an already queued waiter might
3609 * block forever, but there is nothing which can be done about that.
3610 */
futex_exit_recursive(struct task_struct * tsk)3611 void futex_exit_recursive(struct task_struct *tsk)
3612 {
3613 /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
3614 if (tsk->futex_state == FUTEX_STATE_EXITING)
3615 mutex_unlock(&tsk->futex_exit_mutex);
3616 tsk->futex_state = FUTEX_STATE_DEAD;
3617 }
3618
futex_cleanup_begin(struct task_struct * tsk)3619 static void futex_cleanup_begin(struct task_struct *tsk)
3620 {
3621 /*
3622 * Prevent various race issues against a concurrent incoming waiter
3623 * including live locks by forcing the waiter to block on
3624 * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
3625 * attach_to_pi_owner().
3626 */
3627 mutex_lock(&tsk->futex_exit_mutex);
3628
3629 /*
3630 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
3631 *
3632 * This ensures that all subsequent checks of tsk->futex_state in
3633 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
3634 * tsk->pi_lock held.
3635 *
3636 * It guarantees also that a pi_state which was queued right before
3637 * the state change under tsk->pi_lock by a concurrent waiter must
3638 * be observed in exit_pi_state_list().
3639 */
3640 raw_spin_lock_irq(&tsk->pi_lock);
3641 tsk->futex_state = FUTEX_STATE_EXITING;
3642 raw_spin_unlock_irq(&tsk->pi_lock);
3643 }
3644
futex_cleanup_end(struct task_struct * tsk,int state)3645 static void futex_cleanup_end(struct task_struct *tsk, int state)
3646 {
3647 /*
3648 * Lockless store. The only side effect is that an observer might
3649 * take another loop until it becomes visible.
3650 */
3651 tsk->futex_state = state;
3652 /*
3653 * Drop the exit protection. This unblocks waiters which observed
3654 * FUTEX_STATE_EXITING to reevaluate the state.
3655 */
3656 mutex_unlock(&tsk->futex_exit_mutex);
3657 }
3658
futex_exec_release(struct task_struct * tsk)3659 void futex_exec_release(struct task_struct *tsk)
3660 {
3661 /*
3662 * The state handling is done for consistency, but in the case of
3663 * exec() there is no way to prevent futher damage as the PID stays
3664 * the same. But for the unlikely and arguably buggy case that a
3665 * futex is held on exec(), this provides at least as much state
3666 * consistency protection which is possible.
3667 */
3668 futex_cleanup_begin(tsk);
3669 futex_cleanup(tsk);
3670 /*
3671 * Reset the state to FUTEX_STATE_OK. The task is alive and about
3672 * exec a new binary.
3673 */
3674 futex_cleanup_end(tsk, FUTEX_STATE_OK);
3675 }
3676
futex_exit_release(struct task_struct * tsk)3677 void futex_exit_release(struct task_struct *tsk)
3678 {
3679 futex_cleanup_begin(tsk);
3680 futex_cleanup(tsk);
3681 futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
3682 }
3683
do_futex(u32 __user * uaddr,int op,u32 val,ktime_t * timeout,u32 __user * uaddr2,u32 val2,u32 val3)3684 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
3685 u32 __user *uaddr2, u32 val2, u32 val3)
3686 {
3687 int cmd = op & FUTEX_CMD_MASK;
3688 unsigned int flags = 0;
3689
3690 if (!(op & FUTEX_PRIVATE_FLAG))
3691 flags |= FLAGS_SHARED;
3692
3693 if (op & FUTEX_CLOCK_REALTIME) {
3694 flags |= FLAGS_CLOCKRT;
3695 if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
3696 return -ENOSYS;
3697 }
3698
3699 switch (cmd) {
3700 case FUTEX_LOCK_PI:
3701 case FUTEX_UNLOCK_PI:
3702 case FUTEX_TRYLOCK_PI:
3703 case FUTEX_WAIT_REQUEUE_PI:
3704 case FUTEX_CMP_REQUEUE_PI:
3705 if (!futex_cmpxchg_enabled)
3706 return -ENOSYS;
3707 }
3708
3709 switch (cmd) {
3710 case FUTEX_WAIT:
3711 val3 = FUTEX_BITSET_MATCH_ANY;
3712 case FUTEX_WAIT_BITSET:
3713 return futex_wait(uaddr, flags, val, timeout, val3);
3714 case FUTEX_WAKE:
3715 val3 = FUTEX_BITSET_MATCH_ANY;
3716 case FUTEX_WAKE_BITSET:
3717 return futex_wake(uaddr, flags, val, val3);
3718 case FUTEX_REQUEUE:
3719 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
3720 case FUTEX_CMP_REQUEUE:
3721 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
3722 case FUTEX_WAKE_OP:
3723 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
3724 case FUTEX_LOCK_PI:
3725 return futex_lock_pi(uaddr, flags, timeout, 0);
3726 case FUTEX_UNLOCK_PI:
3727 return futex_unlock_pi(uaddr, flags);
3728 case FUTEX_TRYLOCK_PI:
3729 return futex_lock_pi(uaddr, flags, NULL, 1);
3730 case FUTEX_WAIT_REQUEUE_PI:
3731 val3 = FUTEX_BITSET_MATCH_ANY;
3732 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3733 uaddr2);
3734 case FUTEX_CMP_REQUEUE_PI:
3735 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
3736 }
3737 return -ENOSYS;
3738 }
3739
3740
SYSCALL_DEFINE6(futex,u32 __user *,uaddr,int,op,u32,val,struct timespec __user *,utime,u32 __user *,uaddr2,u32,val3)3741 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3742 struct timespec __user *, utime, u32 __user *, uaddr2,
3743 u32, val3)
3744 {
3745 struct timespec ts;
3746 ktime_t t, *tp = NULL;
3747 u32 val2 = 0;
3748 int cmd = op & FUTEX_CMD_MASK;
3749
3750 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
3751 cmd == FUTEX_WAIT_BITSET ||
3752 cmd == FUTEX_WAIT_REQUEUE_PI)) {
3753 if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
3754 return -EFAULT;
3755 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
3756 return -EFAULT;
3757 if (!timespec_valid(&ts))
3758 return -EINVAL;
3759
3760 t = timespec_to_ktime(ts);
3761 if (cmd == FUTEX_WAIT)
3762 t = ktime_add_safe(ktime_get(), t);
3763 tp = &t;
3764 }
3765 /*
3766 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
3767 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
3768 */
3769 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
3770 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
3771 val2 = (u32) (unsigned long) utime;
3772
3773 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
3774 }
3775
3776 #ifdef CONFIG_COMPAT
3777 /*
3778 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3779 */
3780 static inline int
compat_fetch_robust_entry(compat_uptr_t * uentry,struct robust_list __user ** entry,compat_uptr_t __user * head,unsigned int * pi)3781 compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
3782 compat_uptr_t __user *head, unsigned int *pi)
3783 {
3784 if (get_user(*uentry, head))
3785 return -EFAULT;
3786
3787 *entry = compat_ptr((*uentry) & ~1);
3788 *pi = (unsigned int)(*uentry) & 1;
3789
3790 return 0;
3791 }
3792
futex_uaddr(struct robust_list __user * entry,compat_long_t futex_offset)3793 static void __user *futex_uaddr(struct robust_list __user *entry,
3794 compat_long_t futex_offset)
3795 {
3796 compat_uptr_t base = ptr_to_compat(entry);
3797 void __user *uaddr = compat_ptr(base + futex_offset);
3798
3799 return uaddr;
3800 }
3801
3802 /*
3803 * Walk curr->robust_list (very carefully, it's a userspace list!)
3804 * and mark any locks found there dead, and notify any waiters.
3805 *
3806 * We silently return on any sign of list-walking problem.
3807 */
compat_exit_robust_list(struct task_struct * curr)3808 void compat_exit_robust_list(struct task_struct *curr)
3809 {
3810 struct compat_robust_list_head __user *head = curr->compat_robust_list;
3811 struct robust_list __user *entry, *next_entry, *pending;
3812 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3813 unsigned int uninitialized_var(next_pi);
3814 compat_uptr_t uentry, next_uentry, upending;
3815 compat_long_t futex_offset;
3816 int rc;
3817
3818 if (!futex_cmpxchg_enabled)
3819 return;
3820
3821 /*
3822 * Fetch the list head (which was registered earlier, via
3823 * sys_set_robust_list()):
3824 */
3825 if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
3826 return;
3827 /*
3828 * Fetch the relative futex offset:
3829 */
3830 if (get_user(futex_offset, &head->futex_offset))
3831 return;
3832 /*
3833 * Fetch any possibly pending lock-add first, and handle it
3834 * if it exists:
3835 */
3836 if (compat_fetch_robust_entry(&upending, &pending,
3837 &head->list_op_pending, &pip))
3838 return;
3839
3840 next_entry = NULL; /* avoid warning with gcc */
3841 while (entry != (struct robust_list __user *) &head->list) {
3842 /*
3843 * Fetch the next entry in the list before calling
3844 * handle_futex_death:
3845 */
3846 rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
3847 (compat_uptr_t __user *)&entry->next, &next_pi);
3848 /*
3849 * A pending lock might already be on the list, so
3850 * dont process it twice:
3851 */
3852 if (entry != pending) {
3853 void __user *uaddr = futex_uaddr(entry, futex_offset);
3854
3855 if (handle_futex_death(uaddr, curr, pi))
3856 return;
3857 }
3858 if (rc)
3859 return;
3860 uentry = next_uentry;
3861 entry = next_entry;
3862 pi = next_pi;
3863 /*
3864 * Avoid excessively long or circular lists:
3865 */
3866 if (!--limit)
3867 break;
3868
3869 cond_resched();
3870 }
3871 if (pending) {
3872 void __user *uaddr = futex_uaddr(pending, futex_offset);
3873
3874 handle_futex_death(uaddr, curr, pip);
3875 }
3876 }
3877
COMPAT_SYSCALL_DEFINE2(set_robust_list,struct compat_robust_list_head __user *,head,compat_size_t,len)3878 COMPAT_SYSCALL_DEFINE2(set_robust_list,
3879 struct compat_robust_list_head __user *, head,
3880 compat_size_t, len)
3881 {
3882 if (!futex_cmpxchg_enabled)
3883 return -ENOSYS;
3884
3885 if (unlikely(len != sizeof(*head)))
3886 return -EINVAL;
3887
3888 current->compat_robust_list = head;
3889
3890 return 0;
3891 }
3892
COMPAT_SYSCALL_DEFINE3(get_robust_list,int,pid,compat_uptr_t __user *,head_ptr,compat_size_t __user *,len_ptr)3893 COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
3894 compat_uptr_t __user *, head_ptr,
3895 compat_size_t __user *, len_ptr)
3896 {
3897 struct compat_robust_list_head __user *head;
3898 unsigned long ret;
3899 struct task_struct *p;
3900
3901 if (!futex_cmpxchg_enabled)
3902 return -ENOSYS;
3903
3904 rcu_read_lock();
3905
3906 ret = -ESRCH;
3907 if (!pid)
3908 p = current;
3909 else {
3910 p = find_task_by_vpid(pid);
3911 if (!p)
3912 goto err_unlock;
3913 }
3914
3915 ret = -EPERM;
3916 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3917 goto err_unlock;
3918
3919 head = p->compat_robust_list;
3920 rcu_read_unlock();
3921
3922 if (put_user(sizeof(*head), len_ptr))
3923 return -EFAULT;
3924 return put_user(ptr_to_compat(head), head_ptr);
3925
3926 err_unlock:
3927 rcu_read_unlock();
3928
3929 return ret;
3930 }
3931
COMPAT_SYSCALL_DEFINE6(futex,u32 __user *,uaddr,int,op,u32,val,struct compat_timespec __user *,utime,u32 __user *,uaddr2,u32,val3)3932 COMPAT_SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3933 struct compat_timespec __user *, utime, u32 __user *, uaddr2,
3934 u32, val3)
3935 {
3936 struct timespec ts;
3937 ktime_t t, *tp = NULL;
3938 int val2 = 0;
3939 int cmd = op & FUTEX_CMD_MASK;
3940
3941 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
3942 cmd == FUTEX_WAIT_BITSET ||
3943 cmd == FUTEX_WAIT_REQUEUE_PI)) {
3944 if (compat_get_timespec(&ts, utime))
3945 return -EFAULT;
3946 if (!timespec_valid(&ts))
3947 return -EINVAL;
3948
3949 t = timespec_to_ktime(ts);
3950 if (cmd == FUTEX_WAIT)
3951 t = ktime_add_safe(ktime_get(), t);
3952 tp = &t;
3953 }
3954 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
3955 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
3956 val2 = (int) (unsigned long) utime;
3957
3958 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
3959 }
3960 #endif /* CONFIG_COMPAT */
3961
futex_detect_cmpxchg(void)3962 static void __init futex_detect_cmpxchg(void)
3963 {
3964 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
3965 u32 curval;
3966
3967 /*
3968 * This will fail and we want it. Some arch implementations do
3969 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3970 * functionality. We want to know that before we call in any
3971 * of the complex code paths. Also we want to prevent
3972 * registration of robust lists in that case. NULL is
3973 * guaranteed to fault and we get -EFAULT on functional
3974 * implementation, the non-functional ones will return
3975 * -ENOSYS.
3976 */
3977 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
3978 futex_cmpxchg_enabled = 1;
3979 #endif
3980 }
3981
futex_init(void)3982 static int __init futex_init(void)
3983 {
3984 unsigned int futex_shift;
3985 unsigned long i;
3986
3987 #if CONFIG_BASE_SMALL
3988 futex_hashsize = 16;
3989 #else
3990 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
3991 #endif
3992
3993 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
3994 futex_hashsize, 0,
3995 futex_hashsize < 256 ? HASH_SMALL : 0,
3996 &futex_shift, NULL,
3997 futex_hashsize, futex_hashsize);
3998 futex_hashsize = 1UL << futex_shift;
3999
4000 futex_detect_cmpxchg();
4001
4002 for (i = 0; i < futex_hashsize; i++) {
4003 atomic_set(&futex_queues[i].waiters, 0);
4004 plist_head_init(&futex_queues[i].chain);
4005 spin_lock_init(&futex_queues[i].lock);
4006 }
4007
4008 return 0;
4009 }
4010 core_initcall(futex_init);
4011