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