futex: reduce mmap_sem usage
[linux-2.6.git] / 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  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
23  *  enough at me, Linus for the original (flawed) idea, Matthew
24  *  Kirkwood for proof-of-concept implementation.
25  *
26  *  "The futexes are also cursed."
27  *  "But they come in a choice of three flavours!"
28  *
29  *  This program is free software; you can redistribute it and/or modify
30  *  it under the terms of the GNU General Public License as published by
31  *  the Free Software Foundation; either version 2 of the License, or
32  *  (at your option) any later version.
33  *
34  *  This program is distributed in the hope that it will be useful,
35  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
36  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  *  GNU General Public License for more details.
38  *
39  *  You should have received a copy of the GNU General Public License
40  *  along with this program; if not, write to the Free Software
41  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
42  */
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/fs.h>
46 #include <linux/file.h>
47 #include <linux/jhash.h>
48 #include <linux/init.h>
49 #include <linux/futex.h>
50 #include <linux/mount.h>
51 #include <linux/pagemap.h>
52 #include <linux/syscalls.h>
53 #include <linux/signal.h>
54 #include <linux/module.h>
55 #include <linux/magic.h>
56 #include <linux/pid.h>
57 #include <linux/nsproxy.h>
58
59 #include <asm/futex.h>
60
61 #include "rtmutex_common.h"
62
63 int __read_mostly futex_cmpxchg_enabled;
64
65 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
66
67 /*
68  * Priority Inheritance state:
69  */
70 struct futex_pi_state {
71         /*
72          * list of 'owned' pi_state instances - these have to be
73          * cleaned up in do_exit() if the task exits prematurely:
74          */
75         struct list_head list;
76
77         /*
78          * The PI object:
79          */
80         struct rt_mutex pi_mutex;
81
82         struct task_struct *owner;
83         atomic_t refcount;
84
85         union futex_key key;
86 };
87
88 /*
89  * We use this hashed waitqueue instead of a normal wait_queue_t, so
90  * we can wake only the relevant ones (hashed queues may be shared).
91  *
92  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
93  * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
94  * The order of wakup is always to make the first condition true, then
95  * wake up q->waiters, then make the second condition true.
96  */
97 struct futex_q {
98         struct plist_node list;
99         wait_queue_head_t waiters;
100
101         /* Which hash list lock to use: */
102         spinlock_t *lock_ptr;
103
104         /* Key which the futex is hashed on: */
105         union futex_key key;
106
107         /* Optional priority inheritance state: */
108         struct futex_pi_state *pi_state;
109         struct task_struct *task;
110
111         /* Bitset for the optional bitmasked wakeup */
112         u32 bitset;
113 };
114
115 /*
116  * Split the global futex_lock into every hash list lock.
117  */
118 struct futex_hash_bucket {
119         spinlock_t lock;
120         struct plist_head chain;
121 };
122
123 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
124
125 /*
126  * We hash on the keys returned from get_futex_key (see below).
127  */
128 static struct futex_hash_bucket *hash_futex(union futex_key *key)
129 {
130         u32 hash = jhash2((u32*)&key->both.word,
131                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
132                           key->both.offset);
133         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
134 }
135
136 /*
137  * Return 1 if two futex_keys are equal, 0 otherwise.
138  */
139 static inline int match_futex(union futex_key *key1, union futex_key *key2)
140 {
141         return (key1->both.word == key2->both.word
142                 && key1->both.ptr == key2->both.ptr
143                 && key1->both.offset == key2->both.offset);
144 }
145
146 /*
147  * Take a reference to the resource addressed by a key.
148  * Can be called while holding spinlocks.
149  *
150  */
151 static void get_futex_key_refs(union futex_key *key)
152 {
153         if (!key->both.ptr)
154                 return;
155
156         switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
157         case FUT_OFF_INODE:
158                 atomic_inc(&key->shared.inode->i_count);
159                 break;
160         case FUT_OFF_MMSHARED:
161                 atomic_inc(&key->private.mm->mm_count);
162                 break;
163         }
164 }
165
166 /*
167  * Drop a reference to the resource addressed by a key.
168  * The hash bucket spinlock must not be held.
169  */
170 static void drop_futex_key_refs(union futex_key *key)
171 {
172         if (!key->both.ptr)
173                 return;
174
175         switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
176         case FUT_OFF_INODE:
177                 iput(key->shared.inode);
178                 break;
179         case FUT_OFF_MMSHARED:
180                 mmdrop(key->private.mm);
181                 break;
182         }
183 }
184
185 /**
186  * get_futex_key - Get parameters which are the keys for a futex.
187  * @uaddr: virtual address of the futex
188  * @shared: NULL for a PROCESS_PRIVATE futex,
189  *      &current->mm->mmap_sem for a PROCESS_SHARED futex
190  * @key: address where result is stored.
191  *
192  * Returns a negative error code or 0
193  * The key words are stored in *key on success.
194  *
195  * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
196  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
197  * We can usually work out the index without swapping in the page.
198  *
199  * fshared is NULL for PROCESS_PRIVATE futexes
200  * For other futexes, it points to &current->mm->mmap_sem and
201  * caller must have taken the reader lock. but NOT any spinlocks.
202  */
203 static int get_futex_key(u32 __user *uaddr, struct rw_semaphore *fshared,
204                          union futex_key *key)
205 {
206         unsigned long address = (unsigned long)uaddr;
207         struct mm_struct *mm = current->mm;
208         struct page *page;
209         int err;
210
211         /*
212          * The futex address must be "naturally" aligned.
213          */
214         key->both.offset = address % PAGE_SIZE;
215         if (unlikely((address % sizeof(u32)) != 0))
216                 return -EINVAL;
217         address -= key->both.offset;
218
219         /*
220          * PROCESS_PRIVATE futexes are fast.
221          * As the mm cannot disappear under us and the 'key' only needs
222          * virtual address, we dont even have to find the underlying vma.
223          * Note : We do have to check 'uaddr' is a valid user address,
224          *        but access_ok() should be faster than find_vma()
225          */
226         if (!fshared) {
227                 if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))))
228                         return -EFAULT;
229                 key->private.mm = mm;
230                 key->private.address = address;
231                 return 0;
232         }
233
234 again:
235         down_read(&mm->mmap_sem);
236         err = get_user_pages(current, mm, address, 1, 0, 0, &page, NULL);
237         up_read(&mm->mmap_sem);
238         if (err < 0)
239                 return err;
240
241         lock_page(page);
242         if (!page->mapping) {
243                 unlock_page(page);
244                 put_page(page);
245                 goto again;
246         }
247
248         /*
249          * Private mappings are handled in a simple way.
250          *
251          * NOTE: When userspace waits on a MAP_SHARED mapping, even if
252          * it's a read-only handle, it's expected that futexes attach to
253          * the object not the particular process.
254          */
255         if (PageAnon(page)) {
256                 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
257                 key->private.mm = mm;
258                 key->private.address = address;
259         } else {
260                 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
261                 key->shared.inode = page->mapping->host;
262                 key->shared.pgoff = page->index;
263         }
264
265         get_futex_key_refs(key);
266
267         unlock_page(page);
268         put_page(page);
269         return 0;
270 }
271
272 static inline
273 void put_futex_key(struct rw_semaphore *fshared, union futex_key *key)
274 {
275         drop_futex_key_refs(key);
276 }
277
278 static u32 cmpxchg_futex_value_locked(u32 __user *uaddr, u32 uval, u32 newval)
279 {
280         u32 curval;
281
282         pagefault_disable();
283         curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
284         pagefault_enable();
285
286         return curval;
287 }
288
289 static int get_futex_value_locked(u32 *dest, u32 __user *from)
290 {
291         int ret;
292
293         pagefault_disable();
294         ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
295         pagefault_enable();
296
297         return ret ? -EFAULT : 0;
298 }
299
300 /*
301  * Fault handling.
302  * if fshared is non NULL, current->mm->mmap_sem is already held
303  */
304 static int futex_handle_fault(unsigned long address,
305                               struct rw_semaphore *fshared, int attempt)
306 {
307         struct vm_area_struct * vma;
308         struct mm_struct *mm = current->mm;
309         int ret = -EFAULT;
310
311         if (attempt > 2)
312                 return ret;
313
314         down_read(&mm->mmap_sem);
315         vma = find_vma(mm, address);
316         if (vma && address >= vma->vm_start &&
317             (vma->vm_flags & VM_WRITE)) {
318                 int fault;
319                 fault = handle_mm_fault(mm, vma, address, 1);
320                 if (unlikely((fault & VM_FAULT_ERROR))) {
321 #if 0
322                         /* XXX: let's do this when we verify it is OK */
323                         if (ret & VM_FAULT_OOM)
324                                 ret = -ENOMEM;
325 #endif
326                 } else {
327                         ret = 0;
328                         if (fault & VM_FAULT_MAJOR)
329                                 current->maj_flt++;
330                         else
331                                 current->min_flt++;
332                 }
333         }
334         up_read(&mm->mmap_sem);
335         return ret;
336 }
337
338 /*
339  * PI code:
340  */
341 static int refill_pi_state_cache(void)
342 {
343         struct futex_pi_state *pi_state;
344
345         if (likely(current->pi_state_cache))
346                 return 0;
347
348         pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
349
350         if (!pi_state)
351                 return -ENOMEM;
352
353         INIT_LIST_HEAD(&pi_state->list);
354         /* pi_mutex gets initialized later */
355         pi_state->owner = NULL;
356         atomic_set(&pi_state->refcount, 1);
357         pi_state->key = FUTEX_KEY_INIT;
358
359         current->pi_state_cache = pi_state;
360
361         return 0;
362 }
363
364 static struct futex_pi_state * alloc_pi_state(void)
365 {
366         struct futex_pi_state *pi_state = current->pi_state_cache;
367
368         WARN_ON(!pi_state);
369         current->pi_state_cache = NULL;
370
371         return pi_state;
372 }
373
374 static void free_pi_state(struct futex_pi_state *pi_state)
375 {
376         if (!atomic_dec_and_test(&pi_state->refcount))
377                 return;
378
379         /*
380          * If pi_state->owner is NULL, the owner is most probably dying
381          * and has cleaned up the pi_state already
382          */
383         if (pi_state->owner) {
384                 spin_lock_irq(&pi_state->owner->pi_lock);
385                 list_del_init(&pi_state->list);
386                 spin_unlock_irq(&pi_state->owner->pi_lock);
387
388                 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
389         }
390
391         if (current->pi_state_cache)
392                 kfree(pi_state);
393         else {
394                 /*
395                  * pi_state->list is already empty.
396                  * clear pi_state->owner.
397                  * refcount is at 0 - put it back to 1.
398                  */
399                 pi_state->owner = NULL;
400                 atomic_set(&pi_state->refcount, 1);
401                 current->pi_state_cache = pi_state;
402         }
403 }
404
405 /*
406  * Look up the task based on what TID userspace gave us.
407  * We dont trust it.
408  */
409 static struct task_struct * futex_find_get_task(pid_t pid)
410 {
411         struct task_struct *p;
412
413         rcu_read_lock();
414         p = find_task_by_vpid(pid);
415         if (!p || ((current->euid != p->euid) && (current->euid != p->uid)))
416                 p = ERR_PTR(-ESRCH);
417         else
418                 get_task_struct(p);
419
420         rcu_read_unlock();
421
422         return p;
423 }
424
425 /*
426  * This task is holding PI mutexes at exit time => bad.
427  * Kernel cleans up PI-state, but userspace is likely hosed.
428  * (Robust-futex cleanup is separate and might save the day for userspace.)
429  */
430 void exit_pi_state_list(struct task_struct *curr)
431 {
432         struct list_head *next, *head = &curr->pi_state_list;
433         struct futex_pi_state *pi_state;
434         struct futex_hash_bucket *hb;
435         union futex_key key = FUTEX_KEY_INIT;
436
437         if (!futex_cmpxchg_enabled)
438                 return;
439         /*
440          * We are a ZOMBIE and nobody can enqueue itself on
441          * pi_state_list anymore, but we have to be careful
442          * versus waiters unqueueing themselves:
443          */
444         spin_lock_irq(&curr->pi_lock);
445         while (!list_empty(head)) {
446
447                 next = head->next;
448                 pi_state = list_entry(next, struct futex_pi_state, list);
449                 key = pi_state->key;
450                 hb = hash_futex(&key);
451                 spin_unlock_irq(&curr->pi_lock);
452
453                 spin_lock(&hb->lock);
454
455                 spin_lock_irq(&curr->pi_lock);
456                 /*
457                  * We dropped the pi-lock, so re-check whether this
458                  * task still owns the PI-state:
459                  */
460                 if (head->next != next) {
461                         spin_unlock(&hb->lock);
462                         continue;
463                 }
464
465                 WARN_ON(pi_state->owner != curr);
466                 WARN_ON(list_empty(&pi_state->list));
467                 list_del_init(&pi_state->list);
468                 pi_state->owner = NULL;
469                 spin_unlock_irq(&curr->pi_lock);
470
471                 rt_mutex_unlock(&pi_state->pi_mutex);
472
473                 spin_unlock(&hb->lock);
474
475                 spin_lock_irq(&curr->pi_lock);
476         }
477         spin_unlock_irq(&curr->pi_lock);
478 }
479
480 static int
481 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
482                 union futex_key *key, struct futex_pi_state **ps)
483 {
484         struct futex_pi_state *pi_state = NULL;
485         struct futex_q *this, *next;
486         struct plist_head *head;
487         struct task_struct *p;
488         pid_t pid = uval & FUTEX_TID_MASK;
489
490         head = &hb->chain;
491
492         plist_for_each_entry_safe(this, next, head, list) {
493                 if (match_futex(&this->key, key)) {
494                         /*
495                          * Another waiter already exists - bump up
496                          * the refcount and return its pi_state:
497                          */
498                         pi_state = this->pi_state;
499                         /*
500                          * Userspace might have messed up non PI and PI futexes
501                          */
502                         if (unlikely(!pi_state))
503                                 return -EINVAL;
504
505                         WARN_ON(!atomic_read(&pi_state->refcount));
506                         WARN_ON(pid && pi_state->owner &&
507                                 pi_state->owner->pid != pid);
508
509                         atomic_inc(&pi_state->refcount);
510                         *ps = pi_state;
511
512                         return 0;
513                 }
514         }
515
516         /*
517          * We are the first waiter - try to look up the real owner and attach
518          * the new pi_state to it, but bail out when TID = 0
519          */
520         if (!pid)
521                 return -ESRCH;
522         p = futex_find_get_task(pid);
523         if (IS_ERR(p))
524                 return PTR_ERR(p);
525
526         /*
527          * We need to look at the task state flags to figure out,
528          * whether the task is exiting. To protect against the do_exit
529          * change of the task flags, we do this protected by
530          * p->pi_lock:
531          */
532         spin_lock_irq(&p->pi_lock);
533         if (unlikely(p->flags & PF_EXITING)) {
534                 /*
535                  * The task is on the way out. When PF_EXITPIDONE is
536                  * set, we know that the task has finished the
537                  * cleanup:
538                  */
539                 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
540
541                 spin_unlock_irq(&p->pi_lock);
542                 put_task_struct(p);
543                 return ret;
544         }
545
546         pi_state = alloc_pi_state();
547
548         /*
549          * Initialize the pi_mutex in locked state and make 'p'
550          * the owner of it:
551          */
552         rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
553
554         /* Store the key for possible exit cleanups: */
555         pi_state->key = *key;
556
557         WARN_ON(!list_empty(&pi_state->list));
558         list_add(&pi_state->list, &p->pi_state_list);
559         pi_state->owner = p;
560         spin_unlock_irq(&p->pi_lock);
561
562         put_task_struct(p);
563
564         *ps = pi_state;
565
566         return 0;
567 }
568
569 /*
570  * The hash bucket lock must be held when this is called.
571  * Afterwards, the futex_q must not be accessed.
572  */
573 static void wake_futex(struct futex_q *q)
574 {
575         plist_del(&q->list, &q->list.plist);
576         /*
577          * The lock in wake_up_all() is a crucial memory barrier after the
578          * plist_del() and also before assigning to q->lock_ptr.
579          */
580         wake_up_all(&q->waiters);
581         /*
582          * The waiting task can free the futex_q as soon as this is written,
583          * without taking any locks.  This must come last.
584          *
585          * A memory barrier is required here to prevent the following store
586          * to lock_ptr from getting ahead of the wakeup. Clearing the lock
587          * at the end of wake_up_all() does not prevent this store from
588          * moving.
589          */
590         smp_wmb();
591         q->lock_ptr = NULL;
592 }
593
594 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
595 {
596         struct task_struct *new_owner;
597         struct futex_pi_state *pi_state = this->pi_state;
598         u32 curval, newval;
599
600         if (!pi_state)
601                 return -EINVAL;
602
603         spin_lock(&pi_state->pi_mutex.wait_lock);
604         new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
605
606         /*
607          * This happens when we have stolen the lock and the original
608          * pending owner did not enqueue itself back on the rt_mutex.
609          * Thats not a tragedy. We know that way, that a lock waiter
610          * is on the fly. We make the futex_q waiter the pending owner.
611          */
612         if (!new_owner)
613                 new_owner = this->task;
614
615         /*
616          * We pass it to the next owner. (The WAITERS bit is always
617          * kept enabled while there is PI state around. We must also
618          * preserve the owner died bit.)
619          */
620         if (!(uval & FUTEX_OWNER_DIED)) {
621                 int ret = 0;
622
623                 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
624
625                 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
626
627                 if (curval == -EFAULT)
628                         ret = -EFAULT;
629                 else if (curval != uval)
630                         ret = -EINVAL;
631                 if (ret) {
632                         spin_unlock(&pi_state->pi_mutex.wait_lock);
633                         return ret;
634                 }
635         }
636
637         spin_lock_irq(&pi_state->owner->pi_lock);
638         WARN_ON(list_empty(&pi_state->list));
639         list_del_init(&pi_state->list);
640         spin_unlock_irq(&pi_state->owner->pi_lock);
641
642         spin_lock_irq(&new_owner->pi_lock);
643         WARN_ON(!list_empty(&pi_state->list));
644         list_add(&pi_state->list, &new_owner->pi_state_list);
645         pi_state->owner = new_owner;
646         spin_unlock_irq(&new_owner->pi_lock);
647
648         spin_unlock(&pi_state->pi_mutex.wait_lock);
649         rt_mutex_unlock(&pi_state->pi_mutex);
650
651         return 0;
652 }
653
654 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
655 {
656         u32 oldval;
657
658         /*
659          * There is no waiter, so we unlock the futex. The owner died
660          * bit has not to be preserved here. We are the owner:
661          */
662         oldval = cmpxchg_futex_value_locked(uaddr, uval, 0);
663
664         if (oldval == -EFAULT)
665                 return oldval;
666         if (oldval != uval)
667                 return -EAGAIN;
668
669         return 0;
670 }
671
672 /*
673  * Express the locking dependencies for lockdep:
674  */
675 static inline void
676 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
677 {
678         if (hb1 <= hb2) {
679                 spin_lock(&hb1->lock);
680                 if (hb1 < hb2)
681                         spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
682         } else { /* hb1 > hb2 */
683                 spin_lock(&hb2->lock);
684                 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
685         }
686 }
687
688 /*
689  * Wake up all waiters hashed on the physical page that is mapped
690  * to this virtual address:
691  */
692 static int futex_wake(u32 __user *uaddr, struct rw_semaphore *fshared,
693                       int nr_wake, u32 bitset)
694 {
695         struct futex_hash_bucket *hb;
696         struct futex_q *this, *next;
697         struct plist_head *head;
698         union futex_key key = FUTEX_KEY_INIT;
699         int ret;
700
701         if (!bitset)
702                 return -EINVAL;
703
704         ret = get_futex_key(uaddr, fshared, &key);
705         if (unlikely(ret != 0))
706                 goto out;
707
708         hb = hash_futex(&key);
709         spin_lock(&hb->lock);
710         head = &hb->chain;
711
712         plist_for_each_entry_safe(this, next, head, list) {
713                 if (match_futex (&this->key, &key)) {
714                         if (this->pi_state) {
715                                 ret = -EINVAL;
716                                 break;
717                         }
718
719                         /* Check if one of the bits is set in both bitsets */
720                         if (!(this->bitset & bitset))
721                                 continue;
722
723                         wake_futex(this);
724                         if (++ret >= nr_wake)
725                                 break;
726                 }
727         }
728
729         spin_unlock(&hb->lock);
730 out:
731         put_futex_key(fshared, &key);
732         return ret;
733 }
734
735 /*
736  * Wake up all waiters hashed on the physical page that is mapped
737  * to this virtual address:
738  */
739 static int
740 futex_wake_op(u32 __user *uaddr1, struct rw_semaphore *fshared,
741               u32 __user *uaddr2,
742               int nr_wake, int nr_wake2, int op)
743 {
744         union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
745         struct futex_hash_bucket *hb1, *hb2;
746         struct plist_head *head;
747         struct futex_q *this, *next;
748         int ret, op_ret, attempt = 0;
749
750 retryfull:
751         ret = get_futex_key(uaddr1, fshared, &key1);
752         if (unlikely(ret != 0))
753                 goto out;
754         ret = get_futex_key(uaddr2, fshared, &key2);
755         if (unlikely(ret != 0))
756                 goto out;
757
758         hb1 = hash_futex(&key1);
759         hb2 = hash_futex(&key2);
760
761 retry:
762         double_lock_hb(hb1, hb2);
763
764         op_ret = futex_atomic_op_inuser(op, uaddr2);
765         if (unlikely(op_ret < 0)) {
766                 u32 dummy;
767
768                 spin_unlock(&hb1->lock);
769                 if (hb1 != hb2)
770                         spin_unlock(&hb2->lock);
771
772 #ifndef CONFIG_MMU
773                 /*
774                  * we don't get EFAULT from MMU faults if we don't have an MMU,
775                  * but we might get them from range checking
776                  */
777                 ret = op_ret;
778                 goto out;
779 #endif
780
781                 if (unlikely(op_ret != -EFAULT)) {
782                         ret = op_ret;
783                         goto out;
784                 }
785
786                 /*
787                  * futex_atomic_op_inuser needs to both read and write
788                  * *(int __user *)uaddr2, but we can't modify it
789                  * non-atomically.  Therefore, if get_user below is not
790                  * enough, we need to handle the fault ourselves, while
791                  * still holding the mmap_sem.
792                  */
793                 if (attempt++) {
794                         ret = futex_handle_fault((unsigned long)uaddr2,
795                                                  fshared, attempt);
796                         if (ret)
797                                 goto out;
798                         goto retry;
799                 }
800
801                 ret = get_user(dummy, uaddr2);
802                 if (ret)
803                         return ret;
804
805                 goto retryfull;
806         }
807
808         head = &hb1->chain;
809
810         plist_for_each_entry_safe(this, next, head, list) {
811                 if (match_futex (&this->key, &key1)) {
812                         wake_futex(this);
813                         if (++ret >= nr_wake)
814                                 break;
815                 }
816         }
817
818         if (op_ret > 0) {
819                 head = &hb2->chain;
820
821                 op_ret = 0;
822                 plist_for_each_entry_safe(this, next, head, list) {
823                         if (match_futex (&this->key, &key2)) {
824                                 wake_futex(this);
825                                 if (++op_ret >= nr_wake2)
826                                         break;
827                         }
828                 }
829                 ret += op_ret;
830         }
831
832         spin_unlock(&hb1->lock);
833         if (hb1 != hb2)
834                 spin_unlock(&hb2->lock);
835 out:
836         put_futex_key(fshared, &key2);
837         put_futex_key(fshared, &key1);
838
839         return ret;
840 }
841
842 /*
843  * Requeue all waiters hashed on one physical page to another
844  * physical page.
845  */
846 static int futex_requeue(u32 __user *uaddr1, struct rw_semaphore *fshared,
847                          u32 __user *uaddr2,
848                          int nr_wake, int nr_requeue, u32 *cmpval)
849 {
850         union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
851         struct futex_hash_bucket *hb1, *hb2;
852         struct plist_head *head1;
853         struct futex_q *this, *next;
854         int ret, drop_count = 0;
855
856  retry:
857         ret = get_futex_key(uaddr1, fshared, &key1);
858         if (unlikely(ret != 0))
859                 goto out;
860         ret = get_futex_key(uaddr2, fshared, &key2);
861         if (unlikely(ret != 0))
862                 goto out;
863
864         hb1 = hash_futex(&key1);
865         hb2 = hash_futex(&key2);
866
867         double_lock_hb(hb1, hb2);
868
869         if (likely(cmpval != NULL)) {
870                 u32 curval;
871
872                 ret = get_futex_value_locked(&curval, uaddr1);
873
874                 if (unlikely(ret)) {
875                         spin_unlock(&hb1->lock);
876                         if (hb1 != hb2)
877                                 spin_unlock(&hb2->lock);
878
879                         ret = get_user(curval, uaddr1);
880
881                         if (!ret)
882                                 goto retry;
883
884                         return ret;
885                 }
886                 if (curval != *cmpval) {
887                         ret = -EAGAIN;
888                         goto out_unlock;
889                 }
890         }
891
892         head1 = &hb1->chain;
893         plist_for_each_entry_safe(this, next, head1, list) {
894                 if (!match_futex (&this->key, &key1))
895                         continue;
896                 if (++ret <= nr_wake) {
897                         wake_futex(this);
898                 } else {
899                         /*
900                          * If key1 and key2 hash to the same bucket, no need to
901                          * requeue.
902                          */
903                         if (likely(head1 != &hb2->chain)) {
904                                 plist_del(&this->list, &hb1->chain);
905                                 plist_add(&this->list, &hb2->chain);
906                                 this->lock_ptr = &hb2->lock;
907 #ifdef CONFIG_DEBUG_PI_LIST
908                                 this->list.plist.lock = &hb2->lock;
909 #endif
910                         }
911                         this->key = key2;
912                         get_futex_key_refs(&key2);
913                         drop_count++;
914
915                         if (ret - nr_wake >= nr_requeue)
916                                 break;
917                 }
918         }
919
920 out_unlock:
921         spin_unlock(&hb1->lock);
922         if (hb1 != hb2)
923                 spin_unlock(&hb2->lock);
924
925         /* drop_futex_key_refs() must be called outside the spinlocks. */
926         while (--drop_count >= 0)
927                 drop_futex_key_refs(&key1);
928
929 out:
930         put_futex_key(fshared, &key2);
931         put_futex_key(fshared, &key1);
932         return ret;
933 }
934
935 /* The key must be already stored in q->key. */
936 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
937 {
938         struct futex_hash_bucket *hb;
939
940         init_waitqueue_head(&q->waiters);
941
942         get_futex_key_refs(&q->key);
943         hb = hash_futex(&q->key);
944         q->lock_ptr = &hb->lock;
945
946         spin_lock(&hb->lock);
947         return hb;
948 }
949
950 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
951 {
952         int prio;
953
954         /*
955          * The priority used to register this element is
956          * - either the real thread-priority for the real-time threads
957          * (i.e. threads with a priority lower than MAX_RT_PRIO)
958          * - or MAX_RT_PRIO for non-RT threads.
959          * Thus, all RT-threads are woken first in priority order, and
960          * the others are woken last, in FIFO order.
961          */
962         prio = min(current->normal_prio, MAX_RT_PRIO);
963
964         plist_node_init(&q->list, prio);
965 #ifdef CONFIG_DEBUG_PI_LIST
966         q->list.plist.lock = &hb->lock;
967 #endif
968         plist_add(&q->list, &hb->chain);
969         q->task = current;
970         spin_unlock(&hb->lock);
971 }
972
973 static inline void
974 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
975 {
976         spin_unlock(&hb->lock);
977         drop_futex_key_refs(&q->key);
978 }
979
980 /*
981  * queue_me and unqueue_me must be called as a pair, each
982  * exactly once.  They are called with the hashed spinlock held.
983  */
984
985 /* Return 1 if we were still queued (ie. 0 means we were woken) */
986 static int unqueue_me(struct futex_q *q)
987 {
988         spinlock_t *lock_ptr;
989         int ret = 0;
990
991         /* In the common case we don't take the spinlock, which is nice. */
992  retry:
993         lock_ptr = q->lock_ptr;
994         barrier();
995         if (lock_ptr != NULL) {
996                 spin_lock(lock_ptr);
997                 /*
998                  * q->lock_ptr can change between reading it and
999                  * spin_lock(), causing us to take the wrong lock.  This
1000                  * corrects the race condition.
1001                  *
1002                  * Reasoning goes like this: if we have the wrong lock,
1003                  * q->lock_ptr must have changed (maybe several times)
1004                  * between reading it and the spin_lock().  It can
1005                  * change again after the spin_lock() but only if it was
1006                  * already changed before the spin_lock().  It cannot,
1007                  * however, change back to the original value.  Therefore
1008                  * we can detect whether we acquired the correct lock.
1009                  */
1010                 if (unlikely(lock_ptr != q->lock_ptr)) {
1011                         spin_unlock(lock_ptr);
1012                         goto retry;
1013                 }
1014                 WARN_ON(plist_node_empty(&q->list));
1015                 plist_del(&q->list, &q->list.plist);
1016
1017                 BUG_ON(q->pi_state);
1018
1019                 spin_unlock(lock_ptr);
1020                 ret = 1;
1021         }
1022
1023         drop_futex_key_refs(&q->key);
1024         return ret;
1025 }
1026
1027 /*
1028  * PI futexes can not be requeued and must remove themself from the
1029  * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1030  * and dropped here.
1031  */
1032 static void unqueue_me_pi(struct futex_q *q)
1033 {
1034         WARN_ON(plist_node_empty(&q->list));
1035         plist_del(&q->list, &q->list.plist);
1036
1037         BUG_ON(!q->pi_state);
1038         free_pi_state(q->pi_state);
1039         q->pi_state = NULL;
1040
1041         spin_unlock(q->lock_ptr);
1042
1043         drop_futex_key_refs(&q->key);
1044 }
1045
1046 /*
1047  * Fixup the pi_state owner with the new owner.
1048  *
1049  * Must be called with hash bucket lock held and mm->sem held for non
1050  * private futexes.
1051  */
1052 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
1053                                 struct task_struct *newowner,
1054                                 struct rw_semaphore *fshared)
1055 {
1056         u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
1057         struct futex_pi_state *pi_state = q->pi_state;
1058         struct task_struct *oldowner = pi_state->owner;
1059         u32 uval, curval, newval;
1060         int ret, attempt = 0;
1061
1062         /* Owner died? */
1063         if (!pi_state->owner)
1064                 newtid |= FUTEX_OWNER_DIED;
1065
1066         /*
1067          * We are here either because we stole the rtmutex from the
1068          * pending owner or we are the pending owner which failed to
1069          * get the rtmutex. We have to replace the pending owner TID
1070          * in the user space variable. This must be atomic as we have
1071          * to preserve the owner died bit here.
1072          *
1073          * Note: We write the user space value _before_ changing the
1074          * pi_state because we can fault here. Imagine swapped out
1075          * pages or a fork, which was running right before we acquired
1076          * mmap_sem, that marked all the anonymous memory readonly for
1077          * cow.
1078          *
1079          * Modifying pi_state _before_ the user space value would
1080          * leave the pi_state in an inconsistent state when we fault
1081          * here, because we need to drop the hash bucket lock to
1082          * handle the fault. This might be observed in the PID check
1083          * in lookup_pi_state.
1084          */
1085 retry:
1086         if (get_futex_value_locked(&uval, uaddr))
1087                 goto handle_fault;
1088
1089         while (1) {
1090                 newval = (uval & FUTEX_OWNER_DIED) | newtid;
1091
1092                 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1093
1094                 if (curval == -EFAULT)
1095                         goto handle_fault;
1096                 if (curval == uval)
1097                         break;
1098                 uval = curval;
1099         }
1100
1101         /*
1102          * We fixed up user space. Now we need to fix the pi_state
1103          * itself.
1104          */
1105         if (pi_state->owner != NULL) {
1106                 spin_lock_irq(&pi_state->owner->pi_lock);
1107                 WARN_ON(list_empty(&pi_state->list));
1108                 list_del_init(&pi_state->list);
1109                 spin_unlock_irq(&pi_state->owner->pi_lock);
1110         }
1111
1112         pi_state->owner = newowner;
1113
1114         spin_lock_irq(&newowner->pi_lock);
1115         WARN_ON(!list_empty(&pi_state->list));
1116         list_add(&pi_state->list, &newowner->pi_state_list);
1117         spin_unlock_irq(&newowner->pi_lock);
1118         return 0;
1119
1120         /*
1121          * To handle the page fault we need to drop the hash bucket
1122          * lock here. That gives the other task (either the pending
1123          * owner itself or the task which stole the rtmutex) the
1124          * chance to try the fixup of the pi_state. So once we are
1125          * back from handling the fault we need to check the pi_state
1126          * after reacquiring the hash bucket lock and before trying to
1127          * do another fixup. When the fixup has been done already we
1128          * simply return.
1129          */
1130 handle_fault:
1131         spin_unlock(q->lock_ptr);
1132
1133         ret = futex_handle_fault((unsigned long)uaddr, fshared, attempt++);
1134
1135         spin_lock(q->lock_ptr);
1136
1137         /*
1138          * Check if someone else fixed it for us:
1139          */
1140         if (pi_state->owner != oldowner)
1141                 return 0;
1142
1143         if (ret)
1144                 return ret;
1145
1146         goto retry;
1147 }
1148
1149 /*
1150  * In case we must use restart_block to restart a futex_wait,
1151  * we encode in the 'flags' shared capability
1152  */
1153 #define FLAGS_SHARED  1
1154
1155 static long futex_wait_restart(struct restart_block *restart);
1156
1157 static int futex_wait(u32 __user *uaddr, struct rw_semaphore *fshared,
1158                       u32 val, ktime_t *abs_time, u32 bitset)
1159 {
1160         struct task_struct *curr = current;
1161         DECLARE_WAITQUEUE(wait, curr);
1162         struct futex_hash_bucket *hb;
1163         struct futex_q q;
1164         u32 uval;
1165         int ret;
1166         struct hrtimer_sleeper t;
1167         int rem = 0;
1168
1169         if (!bitset)
1170                 return -EINVAL;
1171
1172         q.pi_state = NULL;
1173         q.bitset = bitset;
1174  retry:
1175         q.key = FUTEX_KEY_INIT;
1176         ret = get_futex_key(uaddr, fshared, &q.key);
1177         if (unlikely(ret != 0))
1178                 goto out_release_sem;
1179
1180         hb = queue_lock(&q);
1181
1182         /*
1183          * Access the page AFTER the futex is queued.
1184          * Order is important:
1185          *
1186          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1187          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
1188          *
1189          * The basic logical guarantee of a futex is that it blocks ONLY
1190          * if cond(var) is known to be true at the time of blocking, for
1191          * any cond.  If we queued after testing *uaddr, that would open
1192          * a race condition where we could block indefinitely with
1193          * cond(var) false, which would violate the guarantee.
1194          *
1195          * A consequence is that futex_wait() can return zero and absorb
1196          * a wakeup when *uaddr != val on entry to the syscall.  This is
1197          * rare, but normal.
1198          *
1199          * for shared futexes, we hold the mmap semaphore, so the mapping
1200          * cannot have changed since we looked it up in get_futex_key.
1201          */
1202         ret = get_futex_value_locked(&uval, uaddr);
1203
1204         if (unlikely(ret)) {
1205                 queue_unlock(&q, hb);
1206
1207                 ret = get_user(uval, uaddr);
1208
1209                 if (!ret)
1210                         goto retry;
1211                 return ret;
1212         }
1213         ret = -EWOULDBLOCK;
1214         if (uval != val)
1215                 goto out_unlock_release_sem;
1216
1217         /* Only actually queue if *uaddr contained val.  */
1218         queue_me(&q, hb);
1219
1220         /*
1221          * There might have been scheduling since the queue_me(), as we
1222          * cannot hold a spinlock across the get_user() in case it
1223          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1224          * queueing ourselves into the futex hash.  This code thus has to
1225          * rely on the futex_wake() code removing us from hash when it
1226          * wakes us up.
1227          */
1228
1229         /* add_wait_queue is the barrier after __set_current_state. */
1230         __set_current_state(TASK_INTERRUPTIBLE);
1231         add_wait_queue(&q.waiters, &wait);
1232         /*
1233          * !plist_node_empty() is safe here without any lock.
1234          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1235          */
1236         if (likely(!plist_node_empty(&q.list))) {
1237                 if (!abs_time)
1238                         schedule();
1239                 else {
1240                         hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC,
1241                                                 HRTIMER_MODE_ABS);
1242                         hrtimer_init_sleeper(&t, current);
1243                         t.timer.expires = *abs_time;
1244
1245                         hrtimer_start(&t.timer, t.timer.expires,
1246                                                 HRTIMER_MODE_ABS);
1247                         if (!hrtimer_active(&t.timer))
1248                                 t.task = NULL;
1249
1250                         /*
1251                          * the timer could have already expired, in which
1252                          * case current would be flagged for rescheduling.
1253                          * Don't bother calling schedule.
1254                          */
1255                         if (likely(t.task))
1256                                 schedule();
1257
1258                         hrtimer_cancel(&t.timer);
1259
1260                         /* Flag if a timeout occured */
1261                         rem = (t.task == NULL);
1262
1263                         destroy_hrtimer_on_stack(&t.timer);
1264                 }
1265         }
1266         __set_current_state(TASK_RUNNING);
1267
1268         /*
1269          * NOTE: we don't remove ourselves from the waitqueue because
1270          * we are the only user of it.
1271          */
1272
1273         /* If we were woken (and unqueued), we succeeded, whatever. */
1274         if (!unqueue_me(&q))
1275                 return 0;
1276         if (rem)
1277                 return -ETIMEDOUT;
1278
1279         /*
1280          * We expect signal_pending(current), but another thread may
1281          * have handled it for us already.
1282          */
1283         if (!abs_time)
1284                 return -ERESTARTSYS;
1285         else {
1286                 struct restart_block *restart;
1287                 restart = &current_thread_info()->restart_block;
1288                 restart->fn = futex_wait_restart;
1289                 restart->futex.uaddr = (u32 *)uaddr;
1290                 restart->futex.val = val;
1291                 restart->futex.time = abs_time->tv64;
1292                 restart->futex.bitset = bitset;
1293                 restart->futex.flags = 0;
1294
1295                 if (fshared)
1296                         restart->futex.flags |= FLAGS_SHARED;
1297                 return -ERESTART_RESTARTBLOCK;
1298         }
1299
1300  out_unlock_release_sem:
1301         queue_unlock(&q, hb);
1302
1303  out_release_sem:
1304         put_futex_key(fshared, &q.key);
1305         return ret;
1306 }
1307
1308
1309 static long futex_wait_restart(struct restart_block *restart)
1310 {
1311         u32 __user *uaddr = (u32 __user *)restart->futex.uaddr;
1312         struct rw_semaphore *fshared = NULL;
1313         ktime_t t;
1314
1315         t.tv64 = restart->futex.time;
1316         restart->fn = do_no_restart_syscall;
1317         if (restart->futex.flags & FLAGS_SHARED)
1318                 fshared = &current->mm->mmap_sem;
1319         return (long)futex_wait(uaddr, fshared, restart->futex.val, &t,
1320                                 restart->futex.bitset);
1321 }
1322
1323
1324 /*
1325  * Userspace tried a 0 -> TID atomic transition of the futex value
1326  * and failed. The kernel side here does the whole locking operation:
1327  * if there are waiters then it will block, it does PI, etc. (Due to
1328  * races the kernel might see a 0 value of the futex too.)
1329  */
1330 static int futex_lock_pi(u32 __user *uaddr, struct rw_semaphore *fshared,
1331                          int detect, ktime_t *time, int trylock)
1332 {
1333         struct hrtimer_sleeper timeout, *to = NULL;
1334         struct task_struct *curr = current;
1335         struct futex_hash_bucket *hb;
1336         u32 uval, newval, curval;
1337         struct futex_q q;
1338         int ret, lock_taken, ownerdied = 0, attempt = 0;
1339
1340         if (refill_pi_state_cache())
1341                 return -ENOMEM;
1342
1343         if (time) {
1344                 to = &timeout;
1345                 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
1346                                       HRTIMER_MODE_ABS);
1347                 hrtimer_init_sleeper(to, current);
1348                 to->timer.expires = *time;
1349         }
1350
1351         q.pi_state = NULL;
1352  retry:
1353         q.key = FUTEX_KEY_INIT;
1354         ret = get_futex_key(uaddr, fshared, &q.key);
1355         if (unlikely(ret != 0))
1356                 goto out_release_sem;
1357
1358  retry_unlocked:
1359         hb = queue_lock(&q);
1360
1361  retry_locked:
1362         ret = lock_taken = 0;
1363
1364         /*
1365          * To avoid races, we attempt to take the lock here again
1366          * (by doing a 0 -> TID atomic cmpxchg), while holding all
1367          * the locks. It will most likely not succeed.
1368          */
1369         newval = task_pid_vnr(current);
1370
1371         curval = cmpxchg_futex_value_locked(uaddr, 0, newval);
1372
1373         if (unlikely(curval == -EFAULT))
1374                 goto uaddr_faulted;
1375
1376         /*
1377          * Detect deadlocks. In case of REQUEUE_PI this is a valid
1378          * situation and we return success to user space.
1379          */
1380         if (unlikely((curval & FUTEX_TID_MASK) == task_pid_vnr(current))) {
1381                 ret = -EDEADLK;
1382                 goto out_unlock_release_sem;
1383         }
1384
1385         /*
1386          * Surprise - we got the lock. Just return to userspace:
1387          */
1388         if (unlikely(!curval))
1389                 goto out_unlock_release_sem;
1390
1391         uval = curval;
1392
1393         /*
1394          * Set the WAITERS flag, so the owner will know it has someone
1395          * to wake at next unlock
1396          */
1397         newval = curval | FUTEX_WAITERS;
1398
1399         /*
1400          * There are two cases, where a futex might have no owner (the
1401          * owner TID is 0): OWNER_DIED. We take over the futex in this
1402          * case. We also do an unconditional take over, when the owner
1403          * of the futex died.
1404          *
1405          * This is safe as we are protected by the hash bucket lock !
1406          */
1407         if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) {
1408                 /* Keep the OWNER_DIED bit */
1409                 newval = (curval & ~FUTEX_TID_MASK) | task_pid_vnr(current);
1410                 ownerdied = 0;
1411                 lock_taken = 1;
1412         }
1413
1414         curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1415
1416         if (unlikely(curval == -EFAULT))
1417                 goto uaddr_faulted;
1418         if (unlikely(curval != uval))
1419                 goto retry_locked;
1420
1421         /*
1422          * We took the lock due to owner died take over.
1423          */
1424         if (unlikely(lock_taken))
1425                 goto out_unlock_release_sem;
1426
1427         /*
1428          * We dont have the lock. Look up the PI state (or create it if
1429          * we are the first waiter):
1430          */
1431         ret = lookup_pi_state(uval, hb, &q.key, &q.pi_state);
1432
1433         if (unlikely(ret)) {
1434                 switch (ret) {
1435
1436                 case -EAGAIN:
1437                         /*
1438                          * Task is exiting and we just wait for the
1439                          * exit to complete.
1440                          */
1441                         queue_unlock(&q, hb);
1442                         cond_resched();
1443                         goto retry;
1444
1445                 case -ESRCH:
1446                         /*
1447                          * No owner found for this futex. Check if the
1448                          * OWNER_DIED bit is set to figure out whether
1449                          * this is a robust futex or not.
1450                          */
1451                         if (get_futex_value_locked(&curval, uaddr))
1452                                 goto uaddr_faulted;
1453
1454                         /*
1455                          * We simply start over in case of a robust
1456                          * futex. The code above will take the futex
1457                          * and return happy.
1458                          */
1459                         if (curval & FUTEX_OWNER_DIED) {
1460                                 ownerdied = 1;
1461                                 goto retry_locked;
1462                         }
1463                 default:
1464                         goto out_unlock_release_sem;
1465                 }
1466         }
1467
1468         /*
1469          * Only actually queue now that the atomic ops are done:
1470          */
1471         queue_me(&q, hb);
1472
1473         WARN_ON(!q.pi_state);
1474         /*
1475          * Block on the PI mutex:
1476          */
1477         if (!trylock)
1478                 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1479         else {
1480                 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1481                 /* Fixup the trylock return value: */
1482                 ret = ret ? 0 : -EWOULDBLOCK;
1483         }
1484
1485         spin_lock(q.lock_ptr);
1486
1487         if (!ret) {
1488                 /*
1489                  * Got the lock. We might not be the anticipated owner
1490                  * if we did a lock-steal - fix up the PI-state in
1491                  * that case:
1492                  */
1493                 if (q.pi_state->owner != curr)
1494                         ret = fixup_pi_state_owner(uaddr, &q, curr, fshared);
1495         } else {
1496                 /*
1497                  * Catch the rare case, where the lock was released
1498                  * when we were on the way back before we locked the
1499                  * hash bucket.
1500                  */
1501                 if (q.pi_state->owner == curr) {
1502                         /*
1503                          * Try to get the rt_mutex now. This might
1504                          * fail as some other task acquired the
1505                          * rt_mutex after we removed ourself from the
1506                          * rt_mutex waiters list.
1507                          */
1508                         if (rt_mutex_trylock(&q.pi_state->pi_mutex))
1509                                 ret = 0;
1510                         else {
1511                                 /*
1512                                  * pi_state is incorrect, some other
1513                                  * task did a lock steal and we
1514                                  * returned due to timeout or signal
1515                                  * without taking the rt_mutex. Too
1516                                  * late. We can access the
1517                                  * rt_mutex_owner without locking, as
1518                                  * the other task is now blocked on
1519                                  * the hash bucket lock. Fix the state
1520                                  * up.
1521                                  */
1522                                 struct task_struct *owner;
1523                                 int res;
1524
1525                                 owner = rt_mutex_owner(&q.pi_state->pi_mutex);
1526                                 res = fixup_pi_state_owner(uaddr, &q, owner,
1527                                                            fshared);
1528
1529                                 /* propagate -EFAULT, if the fixup failed */
1530                                 if (res)
1531                                         ret = res;
1532                         }
1533                 } else {
1534                         /*
1535                          * Paranoia check. If we did not take the lock
1536                          * in the trylock above, then we should not be
1537                          * the owner of the rtmutex, neither the real
1538                          * nor the pending one:
1539                          */
1540                         if (rt_mutex_owner(&q.pi_state->pi_mutex) == curr)
1541                                 printk(KERN_ERR "futex_lock_pi: ret = %d "
1542                                        "pi-mutex: %p pi-state %p\n", ret,
1543                                        q.pi_state->pi_mutex.owner,
1544                                        q.pi_state->owner);
1545                 }
1546         }
1547
1548         /* Unqueue and drop the lock */
1549         unqueue_me_pi(&q);
1550
1551         if (to)
1552                 destroy_hrtimer_on_stack(&to->timer);
1553         return ret != -EINTR ? ret : -ERESTARTNOINTR;
1554
1555  out_unlock_release_sem:
1556         queue_unlock(&q, hb);
1557
1558  out_release_sem:
1559         put_futex_key(fshared, &q.key);
1560         if (to)
1561                 destroy_hrtimer_on_stack(&to->timer);
1562         return ret;
1563
1564  uaddr_faulted:
1565         /*
1566          * We have to r/w  *(int __user *)uaddr, but we can't modify it
1567          * non-atomically.  Therefore, if get_user below is not
1568          * enough, we need to handle the fault ourselves, while
1569          * still holding the mmap_sem.
1570          *
1571          * ... and hb->lock. :-) --ANK
1572          */
1573         queue_unlock(&q, hb);
1574
1575         if (attempt++) {
1576                 ret = futex_handle_fault((unsigned long)uaddr, fshared,
1577                                          attempt);
1578                 if (ret)
1579                         goto out_release_sem;
1580                 goto retry_unlocked;
1581         }
1582
1583         ret = get_user(uval, uaddr);
1584         if (!ret && (uval != -EFAULT))
1585                 goto retry;
1586
1587         if (to)
1588                 destroy_hrtimer_on_stack(&to->timer);
1589         return ret;
1590 }
1591
1592 /*
1593  * Userspace attempted a TID -> 0 atomic transition, and failed.
1594  * This is the in-kernel slowpath: we look up the PI state (if any),
1595  * and do the rt-mutex unlock.
1596  */
1597 static int futex_unlock_pi(u32 __user *uaddr, struct rw_semaphore *fshared)
1598 {
1599         struct futex_hash_bucket *hb;
1600         struct futex_q *this, *next;
1601         u32 uval;
1602         struct plist_head *head;
1603         union futex_key key = FUTEX_KEY_INIT;
1604         int ret, attempt = 0;
1605
1606 retry:
1607         if (get_user(uval, uaddr))
1608                 return -EFAULT;
1609         /*
1610          * We release only a lock we actually own:
1611          */
1612         if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current))
1613                 return -EPERM;
1614
1615         ret = get_futex_key(uaddr, fshared, &key);
1616         if (unlikely(ret != 0))
1617                 goto out;
1618
1619         hb = hash_futex(&key);
1620 retry_unlocked:
1621         spin_lock(&hb->lock);
1622
1623         /*
1624          * To avoid races, try to do the TID -> 0 atomic transition
1625          * again. If it succeeds then we can return without waking
1626          * anyone else up:
1627          */
1628         if (!(uval & FUTEX_OWNER_DIED))
1629                 uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0);
1630
1631
1632         if (unlikely(uval == -EFAULT))
1633                 goto pi_faulted;
1634         /*
1635          * Rare case: we managed to release the lock atomically,
1636          * no need to wake anyone else up:
1637          */
1638         if (unlikely(uval == task_pid_vnr(current)))
1639                 goto out_unlock;
1640
1641         /*
1642          * Ok, other tasks may need to be woken up - check waiters
1643          * and do the wakeup if necessary:
1644          */
1645         head = &hb->chain;
1646
1647         plist_for_each_entry_safe(this, next, head, list) {
1648                 if (!match_futex (&this->key, &key))
1649                         continue;
1650                 ret = wake_futex_pi(uaddr, uval, this);
1651                 /*
1652                  * The atomic access to the futex value
1653                  * generated a pagefault, so retry the
1654                  * user-access and the wakeup:
1655                  */
1656                 if (ret == -EFAULT)
1657                         goto pi_faulted;
1658                 goto out_unlock;
1659         }
1660         /*
1661          * No waiters - kernel unlocks the futex:
1662          */
1663         if (!(uval & FUTEX_OWNER_DIED)) {
1664                 ret = unlock_futex_pi(uaddr, uval);
1665                 if (ret == -EFAULT)
1666                         goto pi_faulted;
1667         }
1668
1669 out_unlock:
1670         spin_unlock(&hb->lock);
1671 out:
1672         put_futex_key(fshared, &key);
1673
1674         return ret;
1675
1676 pi_faulted:
1677         /*
1678          * We have to r/w  *(int __user *)uaddr, but we can't modify it
1679          * non-atomically.  Therefore, if get_user below is not
1680          * enough, we need to handle the fault ourselves, while
1681          * still holding the mmap_sem.
1682          *
1683          * ... and hb->lock. --ANK
1684          */
1685         spin_unlock(&hb->lock);
1686
1687         if (attempt++) {
1688                 ret = futex_handle_fault((unsigned long)uaddr, fshared,
1689                                          attempt);
1690                 if (ret)
1691                         goto out;
1692                 uval = 0;
1693                 goto retry_unlocked;
1694         }
1695
1696         ret = get_user(uval, uaddr);
1697         if (!ret && (uval != -EFAULT))
1698                 goto retry;
1699
1700         return ret;
1701 }
1702
1703 /*
1704  * Support for robust futexes: the kernel cleans up held futexes at
1705  * thread exit time.
1706  *
1707  * Implementation: user-space maintains a per-thread list of locks it
1708  * is holding. Upon do_exit(), the kernel carefully walks this list,
1709  * and marks all locks that are owned by this thread with the
1710  * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
1711  * always manipulated with the lock held, so the list is private and
1712  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
1713  * field, to allow the kernel to clean up if the thread dies after
1714  * acquiring the lock, but just before it could have added itself to
1715  * the list. There can only be one such pending lock.
1716  */
1717
1718 /**
1719  * sys_set_robust_list - set the robust-futex list head of a task
1720  * @head: pointer to the list-head
1721  * @len: length of the list-head, as userspace expects
1722  */
1723 asmlinkage long
1724 sys_set_robust_list(struct robust_list_head __user *head,
1725                     size_t len)
1726 {
1727         if (!futex_cmpxchg_enabled)
1728                 return -ENOSYS;
1729         /*
1730          * The kernel knows only one size for now:
1731          */
1732         if (unlikely(len != sizeof(*head)))
1733                 return -EINVAL;
1734
1735         current->robust_list = head;
1736
1737         return 0;
1738 }
1739
1740 /**
1741  * sys_get_robust_list - get the robust-futex list head of a task
1742  * @pid: pid of the process [zero for current task]
1743  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
1744  * @len_ptr: pointer to a length field, the kernel fills in the header size
1745  */
1746 asmlinkage long
1747 sys_get_robust_list(int pid, struct robust_list_head __user * __user *head_ptr,
1748                     size_t __user *len_ptr)
1749 {
1750         struct robust_list_head __user *head;
1751         unsigned long ret;
1752
1753         if (!futex_cmpxchg_enabled)
1754                 return -ENOSYS;
1755
1756         if (!pid)
1757                 head = current->robust_list;
1758         else {
1759                 struct task_struct *p;
1760
1761                 ret = -ESRCH;
1762                 rcu_read_lock();
1763                 p = find_task_by_vpid(pid);
1764                 if (!p)
1765                         goto err_unlock;
1766                 ret = -EPERM;
1767                 if ((current->euid != p->euid) && (current->euid != p->uid) &&
1768                                 !capable(CAP_SYS_PTRACE))
1769                         goto err_unlock;
1770                 head = p->robust_list;
1771                 rcu_read_unlock();
1772         }
1773
1774         if (put_user(sizeof(*head), len_ptr))
1775                 return -EFAULT;
1776         return put_user(head, head_ptr);
1777
1778 err_unlock:
1779         rcu_read_unlock();
1780
1781         return ret;
1782 }
1783
1784 /*
1785  * Process a futex-list entry, check whether it's owned by the
1786  * dying task, and do notification if so:
1787  */
1788 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
1789 {
1790         u32 uval, nval, mval;
1791
1792 retry:
1793         if (get_user(uval, uaddr))
1794                 return -1;
1795
1796         if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
1797                 /*
1798                  * Ok, this dying thread is truly holding a futex
1799                  * of interest. Set the OWNER_DIED bit atomically
1800                  * via cmpxchg, and if the value had FUTEX_WAITERS
1801                  * set, wake up a waiter (if any). (We have to do a
1802                  * futex_wake() even if OWNER_DIED is already set -
1803                  * to handle the rare but possible case of recursive
1804                  * thread-death.) The rest of the cleanup is done in
1805                  * userspace.
1806                  */
1807                 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
1808                 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
1809
1810                 if (nval == -EFAULT)
1811                         return -1;
1812
1813                 if (nval != uval)
1814                         goto retry;
1815
1816                 /*
1817                  * Wake robust non-PI futexes here. The wakeup of
1818                  * PI futexes happens in exit_pi_state():
1819                  */
1820                 if (!pi && (uval & FUTEX_WAITERS))
1821                         futex_wake(uaddr, &curr->mm->mmap_sem, 1,
1822                                    FUTEX_BITSET_MATCH_ANY);
1823         }
1824         return 0;
1825 }
1826
1827 /*
1828  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
1829  */
1830 static inline int fetch_robust_entry(struct robust_list __user **entry,
1831                                      struct robust_list __user * __user *head,
1832                                      int *pi)
1833 {
1834         unsigned long uentry;
1835
1836         if (get_user(uentry, (unsigned long __user *)head))
1837                 return -EFAULT;
1838
1839         *entry = (void __user *)(uentry & ~1UL);
1840         *pi = uentry & 1;
1841
1842         return 0;
1843 }
1844
1845 /*
1846  * Walk curr->robust_list (very carefully, it's a userspace list!)
1847  * and mark any locks found there dead, and notify any waiters.
1848  *
1849  * We silently return on any sign of list-walking problem.
1850  */
1851 void exit_robust_list(struct task_struct *curr)
1852 {
1853         struct robust_list_head __user *head = curr->robust_list;
1854         struct robust_list __user *entry, *next_entry, *pending;
1855         unsigned int limit = ROBUST_LIST_LIMIT, pi, next_pi, pip;
1856         unsigned long futex_offset;
1857         int rc;
1858
1859         if (!futex_cmpxchg_enabled)
1860                 return;
1861
1862         /*
1863          * Fetch the list head (which was registered earlier, via
1864          * sys_set_robust_list()):
1865          */
1866         if (fetch_robust_entry(&entry, &head->list.next, &pi))
1867                 return;
1868         /*
1869          * Fetch the relative futex offset:
1870          */
1871         if (get_user(futex_offset, &head->futex_offset))
1872                 return;
1873         /*
1874          * Fetch any possibly pending lock-add first, and handle it
1875          * if it exists:
1876          */
1877         if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
1878                 return;
1879
1880         next_entry = NULL;      /* avoid warning with gcc */
1881         while (entry != &head->list) {
1882                 /*
1883                  * Fetch the next entry in the list before calling
1884                  * handle_futex_death:
1885                  */
1886                 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
1887                 /*
1888                  * A pending lock might already be on the list, so
1889                  * don't process it twice:
1890                  */
1891                 if (entry != pending)
1892                         if (handle_futex_death((void __user *)entry + futex_offset,
1893                                                 curr, pi))
1894                                 return;
1895                 if (rc)
1896                         return;
1897                 entry = next_entry;
1898                 pi = next_pi;
1899                 /*
1900                  * Avoid excessively long or circular lists:
1901                  */
1902                 if (!--limit)
1903                         break;
1904
1905                 cond_resched();
1906         }
1907
1908         if (pending)
1909                 handle_futex_death((void __user *)pending + futex_offset,
1910                                    curr, pip);
1911 }
1912
1913 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
1914                 u32 __user *uaddr2, u32 val2, u32 val3)
1915 {
1916         int ret = -ENOSYS;
1917         int cmd = op & FUTEX_CMD_MASK;
1918         struct rw_semaphore *fshared = NULL;
1919
1920         if (!(op & FUTEX_PRIVATE_FLAG))
1921                 fshared = &current->mm->mmap_sem;
1922
1923         switch (cmd) {
1924         case FUTEX_WAIT:
1925                 val3 = FUTEX_BITSET_MATCH_ANY;
1926         case FUTEX_WAIT_BITSET:
1927                 ret = futex_wait(uaddr, fshared, val, timeout, val3);
1928                 break;
1929         case FUTEX_WAKE:
1930                 val3 = FUTEX_BITSET_MATCH_ANY;
1931         case FUTEX_WAKE_BITSET:
1932                 ret = futex_wake(uaddr, fshared, val, val3);
1933                 break;
1934         case FUTEX_REQUEUE:
1935                 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL);
1936                 break;
1937         case FUTEX_CMP_REQUEUE:
1938                 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3);
1939                 break;
1940         case FUTEX_WAKE_OP:
1941                 ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3);
1942                 break;
1943         case FUTEX_LOCK_PI:
1944                 if (futex_cmpxchg_enabled)
1945                         ret = futex_lock_pi(uaddr, fshared, val, timeout, 0);
1946                 break;
1947         case FUTEX_UNLOCK_PI:
1948                 if (futex_cmpxchg_enabled)
1949                         ret = futex_unlock_pi(uaddr, fshared);
1950                 break;
1951         case FUTEX_TRYLOCK_PI:
1952                 if (futex_cmpxchg_enabled)
1953                         ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1);
1954                 break;
1955         default:
1956                 ret = -ENOSYS;
1957         }
1958         return ret;
1959 }
1960
1961
1962 asmlinkage long sys_futex(u32 __user *uaddr, int op, u32 val,
1963                           struct timespec __user *utime, u32 __user *uaddr2,
1964                           u32 val3)
1965 {
1966         struct timespec ts;
1967         ktime_t t, *tp = NULL;
1968         u32 val2 = 0;
1969         int cmd = op & FUTEX_CMD_MASK;
1970
1971         if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
1972                       cmd == FUTEX_WAIT_BITSET)) {
1973                 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
1974                         return -EFAULT;
1975                 if (!timespec_valid(&ts))
1976                         return -EINVAL;
1977
1978                 t = timespec_to_ktime(ts);
1979                 if (cmd == FUTEX_WAIT)
1980                         t = ktime_add_safe(ktime_get(), t);
1981                 tp = &t;
1982         }
1983         /*
1984          * requeue parameter in 'utime' if cmd == FUTEX_REQUEUE.
1985          * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
1986          */
1987         if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
1988             cmd == FUTEX_WAKE_OP)
1989                 val2 = (u32) (unsigned long) utime;
1990
1991         return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
1992 }
1993
1994 static int __init futex_init(void)
1995 {
1996         u32 curval;
1997         int i;
1998
1999         /*
2000          * This will fail and we want it. Some arch implementations do
2001          * runtime detection of the futex_atomic_cmpxchg_inatomic()
2002          * functionality. We want to know that before we call in any
2003          * of the complex code paths. Also we want to prevent
2004          * registration of robust lists in that case. NULL is
2005          * guaranteed to fault and we get -EFAULT on functional
2006          * implementation, the non functional ones will return
2007          * -ENOSYS.
2008          */
2009         curval = cmpxchg_futex_value_locked(NULL, 0, 0);
2010         if (curval == -EFAULT)
2011                 futex_cmpxchg_enabled = 1;
2012
2013         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
2014                 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
2015                 spin_lock_init(&futex_queues[i].lock);
2016         }
2017
2018         return 0;
2019 }
2020 __initcall(futex_init);