Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

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