Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  *  Fast Userspace Mutexes (which I call "Futexes!").
0004  *  (C) Rusty Russell, IBM 2002
0005  *
0006  *  Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
0007  *  (C) Copyright 2003 Red Hat Inc, All Rights Reserved
0008  *
0009  *  Removed page pinning, fix privately mapped COW pages and other cleanups
0010  *  (C) Copyright 2003, 2004 Jamie Lokier
0011  *
0012  *  Robust futex support started by Ingo Molnar
0013  *  (C) Copyright 2006 Red Hat Inc, All Rights Reserved
0014  *  Thanks to Thomas Gleixner for suggestions, analysis and fixes.
0015  *
0016  *  PI-futex support started by Ingo Molnar and Thomas Gleixner
0017  *  Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
0018  *  Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
0019  *
0020  *  PRIVATE futexes by Eric Dumazet
0021  *  Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
0022  *
0023  *  Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
0024  *  Copyright (C) IBM Corporation, 2009
0025  *  Thanks to Thomas Gleixner for conceptual design and careful reviews.
0026  *
0027  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
0028  *  enough at me, Linus for the original (flawed) idea, Matthew
0029  *  Kirkwood for proof-of-concept implementation.
0030  *
0031  *  "The futexes are also cursed."
0032  *  "But they come in a choice of three flavours!"
0033  */
0034 #include <linux/compat.h>
0035 #include <linux/jhash.h>
0036 #include <linux/pagemap.h>
0037 #include <linux/memblock.h>
0038 #include <linux/fault-inject.h>
0039 #include <linux/slab.h>
0040 
0041 #include "futex.h"
0042 #include "../locking/rtmutex_common.h"
0043 
0044 /*
0045  * The base of the bucket array and its size are always used together
0046  * (after initialization only in futex_hash()), so ensure that they
0047  * reside in the same cacheline.
0048  */
0049 static struct {
0050     struct futex_hash_bucket *queues;
0051     unsigned long            hashsize;
0052 } __futex_data __read_mostly __aligned(2*sizeof(long));
0053 #define futex_queues   (__futex_data.queues)
0054 #define futex_hashsize (__futex_data.hashsize)
0055 
0056 
0057 /*
0058  * Fault injections for futexes.
0059  */
0060 #ifdef CONFIG_FAIL_FUTEX
0061 
0062 static struct {
0063     struct fault_attr attr;
0064 
0065     bool ignore_private;
0066 } fail_futex = {
0067     .attr = FAULT_ATTR_INITIALIZER,
0068     .ignore_private = false,
0069 };
0070 
0071 static int __init setup_fail_futex(char *str)
0072 {
0073     return setup_fault_attr(&fail_futex.attr, str);
0074 }
0075 __setup("fail_futex=", setup_fail_futex);
0076 
0077 bool should_fail_futex(bool fshared)
0078 {
0079     if (fail_futex.ignore_private && !fshared)
0080         return false;
0081 
0082     return should_fail(&fail_futex.attr, 1);
0083 }
0084 
0085 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
0086 
0087 static int __init fail_futex_debugfs(void)
0088 {
0089     umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
0090     struct dentry *dir;
0091 
0092     dir = fault_create_debugfs_attr("fail_futex", NULL,
0093                     &fail_futex.attr);
0094     if (IS_ERR(dir))
0095         return PTR_ERR(dir);
0096 
0097     debugfs_create_bool("ignore-private", mode, dir,
0098                 &fail_futex.ignore_private);
0099     return 0;
0100 }
0101 
0102 late_initcall(fail_futex_debugfs);
0103 
0104 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
0105 
0106 #endif /* CONFIG_FAIL_FUTEX */
0107 
0108 /**
0109  * futex_hash - Return the hash bucket in the global hash
0110  * @key:    Pointer to the futex key for which the hash is calculated
0111  *
0112  * We hash on the keys returned from get_futex_key (see below) and return the
0113  * corresponding hash bucket in the global hash.
0114  */
0115 struct futex_hash_bucket *futex_hash(union futex_key *key)
0116 {
0117     u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
0118               key->both.offset);
0119 
0120     return &futex_queues[hash & (futex_hashsize - 1)];
0121 }
0122 
0123 
0124 /**
0125  * futex_setup_timer - set up the sleeping hrtimer.
0126  * @time:   ptr to the given timeout value
0127  * @timeout:    the hrtimer_sleeper structure to be set up
0128  * @flags:  futex flags
0129  * @range_ns:   optional range in ns
0130  *
0131  * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
0132  *     value given
0133  */
0134 struct hrtimer_sleeper *
0135 futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
0136           int flags, u64 range_ns)
0137 {
0138     if (!time)
0139         return NULL;
0140 
0141     hrtimer_init_sleeper_on_stack(timeout, (flags & FLAGS_CLOCKRT) ?
0142                       CLOCK_REALTIME : CLOCK_MONOTONIC,
0143                       HRTIMER_MODE_ABS);
0144     /*
0145      * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
0146      * effectively the same as calling hrtimer_set_expires().
0147      */
0148     hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
0149 
0150     return timeout;
0151 }
0152 
0153 /*
0154  * Generate a machine wide unique identifier for this inode.
0155  *
0156  * This relies on u64 not wrapping in the life-time of the machine; which with
0157  * 1ns resolution means almost 585 years.
0158  *
0159  * This further relies on the fact that a well formed program will not unmap
0160  * the file while it has a (shared) futex waiting on it. This mapping will have
0161  * a file reference which pins the mount and inode.
0162  *
0163  * If for some reason an inode gets evicted and read back in again, it will get
0164  * a new sequence number and will _NOT_ match, even though it is the exact same
0165  * file.
0166  *
0167  * It is important that futex_match() will never have a false-positive, esp.
0168  * for PI futexes that can mess up the state. The above argues that false-negatives
0169  * are only possible for malformed programs.
0170  */
0171 static u64 get_inode_sequence_number(struct inode *inode)
0172 {
0173     static atomic64_t i_seq;
0174     u64 old;
0175 
0176     /* Does the inode already have a sequence number? */
0177     old = atomic64_read(&inode->i_sequence);
0178     if (likely(old))
0179         return old;
0180 
0181     for (;;) {
0182         u64 new = atomic64_add_return(1, &i_seq);
0183         if (WARN_ON_ONCE(!new))
0184             continue;
0185 
0186         old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
0187         if (old)
0188             return old;
0189         return new;
0190     }
0191 }
0192 
0193 /**
0194  * get_futex_key() - Get parameters which are the keys for a futex
0195  * @uaddr:  virtual address of the futex
0196  * @fshared:    false for a PROCESS_PRIVATE futex, true for PROCESS_SHARED
0197  * @key:    address where result is stored.
0198  * @rw:     mapping needs to be read/write (values: FUTEX_READ,
0199  *              FUTEX_WRITE)
0200  *
0201  * Return: a negative error code or 0
0202  *
0203  * The key words are stored in @key on success.
0204  *
0205  * For shared mappings (when @fshared), the key is:
0206  *
0207  *   ( inode->i_sequence, page->index, offset_within_page )
0208  *
0209  * [ also see get_inode_sequence_number() ]
0210  *
0211  * For private mappings (or when !@fshared), the key is:
0212  *
0213  *   ( current->mm, address, 0 )
0214  *
0215  * This allows (cross process, where applicable) identification of the futex
0216  * without keeping the page pinned for the duration of the FUTEX_WAIT.
0217  *
0218  * lock_page() might sleep, the caller should not hold a spinlock.
0219  */
0220 int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,
0221           enum futex_access rw)
0222 {
0223     unsigned long address = (unsigned long)uaddr;
0224     struct mm_struct *mm = current->mm;
0225     struct page *page, *tail;
0226     struct address_space *mapping;
0227     int err, ro = 0;
0228 
0229     /*
0230      * The futex address must be "naturally" aligned.
0231      */
0232     key->both.offset = address % PAGE_SIZE;
0233     if (unlikely((address % sizeof(u32)) != 0))
0234         return -EINVAL;
0235     address -= key->both.offset;
0236 
0237     if (unlikely(!access_ok(uaddr, sizeof(u32))))
0238         return -EFAULT;
0239 
0240     if (unlikely(should_fail_futex(fshared)))
0241         return -EFAULT;
0242 
0243     /*
0244      * PROCESS_PRIVATE futexes are fast.
0245      * As the mm cannot disappear under us and the 'key' only needs
0246      * virtual address, we dont even have to find the underlying vma.
0247      * Note : We do have to check 'uaddr' is a valid user address,
0248      *        but access_ok() should be faster than find_vma()
0249      */
0250     if (!fshared) {
0251         key->private.mm = mm;
0252         key->private.address = address;
0253         return 0;
0254     }
0255 
0256 again:
0257     /* Ignore any VERIFY_READ mapping (futex common case) */
0258     if (unlikely(should_fail_futex(true)))
0259         return -EFAULT;
0260 
0261     err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
0262     /*
0263      * If write access is not required (eg. FUTEX_WAIT), try
0264      * and get read-only access.
0265      */
0266     if (err == -EFAULT && rw == FUTEX_READ) {
0267         err = get_user_pages_fast(address, 1, 0, &page);
0268         ro = 1;
0269     }
0270     if (err < 0)
0271         return err;
0272     else
0273         err = 0;
0274 
0275     /*
0276      * The treatment of mapping from this point on is critical. The page
0277      * lock protects many things but in this context the page lock
0278      * stabilizes mapping, prevents inode freeing in the shared
0279      * file-backed region case and guards against movement to swap cache.
0280      *
0281      * Strictly speaking the page lock is not needed in all cases being
0282      * considered here and page lock forces unnecessarily serialization
0283      * From this point on, mapping will be re-verified if necessary and
0284      * page lock will be acquired only if it is unavoidable
0285      *
0286      * Mapping checks require the head page for any compound page so the
0287      * head page and mapping is looked up now. For anonymous pages, it
0288      * does not matter if the page splits in the future as the key is
0289      * based on the address. For filesystem-backed pages, the tail is
0290      * required as the index of the page determines the key. For
0291      * base pages, there is no tail page and tail == page.
0292      */
0293     tail = page;
0294     page = compound_head(page);
0295     mapping = READ_ONCE(page->mapping);
0296 
0297     /*
0298      * If page->mapping is NULL, then it cannot be a PageAnon
0299      * page; but it might be the ZERO_PAGE or in the gate area or
0300      * in a special mapping (all cases which we are happy to fail);
0301      * or it may have been a good file page when get_user_pages_fast
0302      * found it, but truncated or holepunched or subjected to
0303      * invalidate_complete_page2 before we got the page lock (also
0304      * cases which we are happy to fail).  And we hold a reference,
0305      * so refcount care in invalidate_inode_page's remove_mapping
0306      * prevents drop_caches from setting mapping to NULL beneath us.
0307      *
0308      * The case we do have to guard against is when memory pressure made
0309      * shmem_writepage move it from filecache to swapcache beneath us:
0310      * an unlikely race, but we do need to retry for page->mapping.
0311      */
0312     if (unlikely(!mapping)) {
0313         int shmem_swizzled;
0314 
0315         /*
0316          * Page lock is required to identify which special case above
0317          * applies. If this is really a shmem page then the page lock
0318          * will prevent unexpected transitions.
0319          */
0320         lock_page(page);
0321         shmem_swizzled = PageSwapCache(page) || page->mapping;
0322         unlock_page(page);
0323         put_page(page);
0324 
0325         if (shmem_swizzled)
0326             goto again;
0327 
0328         return -EFAULT;
0329     }
0330 
0331     /*
0332      * Private mappings are handled in a simple way.
0333      *
0334      * If the futex key is stored on an anonymous page, then the associated
0335      * object is the mm which is implicitly pinned by the calling process.
0336      *
0337      * NOTE: When userspace waits on a MAP_SHARED mapping, even if
0338      * it's a read-only handle, it's expected that futexes attach to
0339      * the object not the particular process.
0340      */
0341     if (PageAnon(page)) {
0342         /*
0343          * A RO anonymous page will never change and thus doesn't make
0344          * sense for futex operations.
0345          */
0346         if (unlikely(should_fail_futex(true)) || ro) {
0347             err = -EFAULT;
0348             goto out;
0349         }
0350 
0351         key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
0352         key->private.mm = mm;
0353         key->private.address = address;
0354 
0355     } else {
0356         struct inode *inode;
0357 
0358         /*
0359          * The associated futex object in this case is the inode and
0360          * the page->mapping must be traversed. Ordinarily this should
0361          * be stabilised under page lock but it's not strictly
0362          * necessary in this case as we just want to pin the inode, not
0363          * update the radix tree or anything like that.
0364          *
0365          * The RCU read lock is taken as the inode is finally freed
0366          * under RCU. If the mapping still matches expectations then the
0367          * mapping->host can be safely accessed as being a valid inode.
0368          */
0369         rcu_read_lock();
0370 
0371         if (READ_ONCE(page->mapping) != mapping) {
0372             rcu_read_unlock();
0373             put_page(page);
0374 
0375             goto again;
0376         }
0377 
0378         inode = READ_ONCE(mapping->host);
0379         if (!inode) {
0380             rcu_read_unlock();
0381             put_page(page);
0382 
0383             goto again;
0384         }
0385 
0386         key->both.offset |= FUT_OFF_INODE; /* inode-based key */
0387         key->shared.i_seq = get_inode_sequence_number(inode);
0388         key->shared.pgoff = page_to_pgoff(tail);
0389         rcu_read_unlock();
0390     }
0391 
0392 out:
0393     put_page(page);
0394     return err;
0395 }
0396 
0397 /**
0398  * fault_in_user_writeable() - Fault in user address and verify RW access
0399  * @uaddr:  pointer to faulting user space address
0400  *
0401  * Slow path to fixup the fault we just took in the atomic write
0402  * access to @uaddr.
0403  *
0404  * We have no generic implementation of a non-destructive write to the
0405  * user address. We know that we faulted in the atomic pagefault
0406  * disabled section so we can as well avoid the #PF overhead by
0407  * calling get_user_pages() right away.
0408  */
0409 int fault_in_user_writeable(u32 __user *uaddr)
0410 {
0411     struct mm_struct *mm = current->mm;
0412     int ret;
0413 
0414     mmap_read_lock(mm);
0415     ret = fixup_user_fault(mm, (unsigned long)uaddr,
0416                    FAULT_FLAG_WRITE, NULL);
0417     mmap_read_unlock(mm);
0418 
0419     return ret < 0 ? ret : 0;
0420 }
0421 
0422 /**
0423  * futex_top_waiter() - Return the highest priority waiter on a futex
0424  * @hb:     the hash bucket the futex_q's reside in
0425  * @key:    the futex key (to distinguish it from other futex futex_q's)
0426  *
0427  * Must be called with the hb lock held.
0428  */
0429 struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key)
0430 {
0431     struct futex_q *this;
0432 
0433     plist_for_each_entry(this, &hb->chain, list) {
0434         if (futex_match(&this->key, key))
0435             return this;
0436     }
0437     return NULL;
0438 }
0439 
0440 int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr, u32 uval, u32 newval)
0441 {
0442     int ret;
0443 
0444     pagefault_disable();
0445     ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
0446     pagefault_enable();
0447 
0448     return ret;
0449 }
0450 
0451 int futex_get_value_locked(u32 *dest, u32 __user *from)
0452 {
0453     int ret;
0454 
0455     pagefault_disable();
0456     ret = __get_user(*dest, from);
0457     pagefault_enable();
0458 
0459     return ret ? -EFAULT : 0;
0460 }
0461 
0462 /**
0463  * wait_for_owner_exiting - Block until the owner has exited
0464  * @ret: owner's current futex lock status
0465  * @exiting:    Pointer to the exiting task
0466  *
0467  * Caller must hold a refcount on @exiting.
0468  */
0469 void wait_for_owner_exiting(int ret, struct task_struct *exiting)
0470 {
0471     if (ret != -EBUSY) {
0472         WARN_ON_ONCE(exiting);
0473         return;
0474     }
0475 
0476     if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
0477         return;
0478 
0479     mutex_lock(&exiting->futex_exit_mutex);
0480     /*
0481      * No point in doing state checking here. If the waiter got here
0482      * while the task was in exec()->exec_futex_release() then it can
0483      * have any FUTEX_STATE_* value when the waiter has acquired the
0484      * mutex. OK, if running, EXITING or DEAD if it reached exit()
0485      * already. Highly unlikely and not a problem. Just one more round
0486      * through the futex maze.
0487      */
0488     mutex_unlock(&exiting->futex_exit_mutex);
0489 
0490     put_task_struct(exiting);
0491 }
0492 
0493 /**
0494  * __futex_unqueue() - Remove the futex_q from its futex_hash_bucket
0495  * @q:  The futex_q to unqueue
0496  *
0497  * The q->lock_ptr must not be NULL and must be held by the caller.
0498  */
0499 void __futex_unqueue(struct futex_q *q)
0500 {
0501     struct futex_hash_bucket *hb;
0502 
0503     if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
0504         return;
0505     lockdep_assert_held(q->lock_ptr);
0506 
0507     hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
0508     plist_del(&q->list, &hb->chain);
0509     futex_hb_waiters_dec(hb);
0510 }
0511 
0512 /* The key must be already stored in q->key. */
0513 struct futex_hash_bucket *futex_q_lock(struct futex_q *q)
0514     __acquires(&hb->lock)
0515 {
0516     struct futex_hash_bucket *hb;
0517 
0518     hb = futex_hash(&q->key);
0519 
0520     /*
0521      * Increment the counter before taking the lock so that
0522      * a potential waker won't miss a to-be-slept task that is
0523      * waiting for the spinlock. This is safe as all futex_q_lock()
0524      * users end up calling futex_queue(). Similarly, for housekeeping,
0525      * decrement the counter at futex_q_unlock() when some error has
0526      * occurred and we don't end up adding the task to the list.
0527      */
0528     futex_hb_waiters_inc(hb); /* implies smp_mb(); (A) */
0529 
0530     q->lock_ptr = &hb->lock;
0531 
0532     spin_lock(&hb->lock);
0533     return hb;
0534 }
0535 
0536 void futex_q_unlock(struct futex_hash_bucket *hb)
0537     __releases(&hb->lock)
0538 {
0539     spin_unlock(&hb->lock);
0540     futex_hb_waiters_dec(hb);
0541 }
0542 
0543 void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb)
0544 {
0545     int prio;
0546 
0547     /*
0548      * The priority used to register this element is
0549      * - either the real thread-priority for the real-time threads
0550      * (i.e. threads with a priority lower than MAX_RT_PRIO)
0551      * - or MAX_RT_PRIO for non-RT threads.
0552      * Thus, all RT-threads are woken first in priority order, and
0553      * the others are woken last, in FIFO order.
0554      */
0555     prio = min(current->normal_prio, MAX_RT_PRIO);
0556 
0557     plist_node_init(&q->list, prio);
0558     plist_add(&q->list, &hb->chain);
0559     q->task = current;
0560 }
0561 
0562 /**
0563  * futex_unqueue() - Remove the futex_q from its futex_hash_bucket
0564  * @q:  The futex_q to unqueue
0565  *
0566  * The q->lock_ptr must not be held by the caller. A call to futex_unqueue() must
0567  * be paired with exactly one earlier call to futex_queue().
0568  *
0569  * Return:
0570  *  - 1 - if the futex_q was still queued (and we removed unqueued it);
0571  *  - 0 - if the futex_q was already removed by the waking thread
0572  */
0573 int futex_unqueue(struct futex_q *q)
0574 {
0575     spinlock_t *lock_ptr;
0576     int ret = 0;
0577 
0578     /* In the common case we don't take the spinlock, which is nice. */
0579 retry:
0580     /*
0581      * q->lock_ptr can change between this read and the following spin_lock.
0582      * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
0583      * optimizing lock_ptr out of the logic below.
0584      */
0585     lock_ptr = READ_ONCE(q->lock_ptr);
0586     if (lock_ptr != NULL) {
0587         spin_lock(lock_ptr);
0588         /*
0589          * q->lock_ptr can change between reading it and
0590          * spin_lock(), causing us to take the wrong lock.  This
0591          * corrects the race condition.
0592          *
0593          * Reasoning goes like this: if we have the wrong lock,
0594          * q->lock_ptr must have changed (maybe several times)
0595          * between reading it and the spin_lock().  It can
0596          * change again after the spin_lock() but only if it was
0597          * already changed before the spin_lock().  It cannot,
0598          * however, change back to the original value.  Therefore
0599          * we can detect whether we acquired the correct lock.
0600          */
0601         if (unlikely(lock_ptr != q->lock_ptr)) {
0602             spin_unlock(lock_ptr);
0603             goto retry;
0604         }
0605         __futex_unqueue(q);
0606 
0607         BUG_ON(q->pi_state);
0608 
0609         spin_unlock(lock_ptr);
0610         ret = 1;
0611     }
0612 
0613     return ret;
0614 }
0615 
0616 /*
0617  * PI futexes can not be requeued and must remove themselves from the
0618  * hash bucket. The hash bucket lock (i.e. lock_ptr) is held.
0619  */
0620 void futex_unqueue_pi(struct futex_q *q)
0621 {
0622     __futex_unqueue(q);
0623 
0624     BUG_ON(!q->pi_state);
0625     put_pi_state(q->pi_state);
0626     q->pi_state = NULL;
0627 }
0628 
0629 /* Constants for the pending_op argument of handle_futex_death */
0630 #define HANDLE_DEATH_PENDING    true
0631 #define HANDLE_DEATH_LIST   false
0632 
0633 /*
0634  * Process a futex-list entry, check whether it's owned by the
0635  * dying task, and do notification if so:
0636  */
0637 static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
0638                   bool pi, bool pending_op)
0639 {
0640     u32 uval, nval, mval;
0641     int err;
0642 
0643     /* Futex address must be 32bit aligned */
0644     if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
0645         return -1;
0646 
0647 retry:
0648     if (get_user(uval, uaddr))
0649         return -1;
0650 
0651     /*
0652      * Special case for regular (non PI) futexes. The unlock path in
0653      * user space has two race scenarios:
0654      *
0655      * 1. The unlock path releases the user space futex value and
0656      *    before it can execute the futex() syscall to wake up
0657      *    waiters it is killed.
0658      *
0659      * 2. A woken up waiter is killed before it can acquire the
0660      *    futex in user space.
0661      *
0662      * In both cases the TID validation below prevents a wakeup of
0663      * potential waiters which can cause these waiters to block
0664      * forever.
0665      *
0666      * In both cases the following conditions are met:
0667      *
0668      *  1) task->robust_list->list_op_pending != NULL
0669      *     @pending_op == true
0670      *  2) User space futex value == 0
0671      *  3) Regular futex: @pi == false
0672      *
0673      * If these conditions are met, it is safe to attempt waking up a
0674      * potential waiter without touching the user space futex value and
0675      * trying to set the OWNER_DIED bit. The user space futex value is
0676      * uncontended and the rest of the user space mutex state is
0677      * consistent, so a woken waiter will just take over the
0678      * uncontended futex. Setting the OWNER_DIED bit would create
0679      * inconsistent state and malfunction of the user space owner died
0680      * handling.
0681      */
0682     if (pending_op && !pi && !uval) {
0683         futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
0684         return 0;
0685     }
0686 
0687     if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
0688         return 0;
0689 
0690     /*
0691      * Ok, this dying thread is truly holding a futex
0692      * of interest. Set the OWNER_DIED bit atomically
0693      * via cmpxchg, and if the value had FUTEX_WAITERS
0694      * set, wake up a waiter (if any). (We have to do a
0695      * futex_wake() even if OWNER_DIED is already set -
0696      * to handle the rare but possible case of recursive
0697      * thread-death.) The rest of the cleanup is done in
0698      * userspace.
0699      */
0700     mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
0701 
0702     /*
0703      * We are not holding a lock here, but we want to have
0704      * the pagefault_disable/enable() protection because
0705      * we want to handle the fault gracefully. If the
0706      * access fails we try to fault in the futex with R/W
0707      * verification via get_user_pages. get_user() above
0708      * does not guarantee R/W access. If that fails we
0709      * give up and leave the futex locked.
0710      */
0711     if ((err = futex_cmpxchg_value_locked(&nval, uaddr, uval, mval))) {
0712         switch (err) {
0713         case -EFAULT:
0714             if (fault_in_user_writeable(uaddr))
0715                 return -1;
0716             goto retry;
0717 
0718         case -EAGAIN:
0719             cond_resched();
0720             goto retry;
0721 
0722         default:
0723             WARN_ON_ONCE(1);
0724             return err;
0725         }
0726     }
0727 
0728     if (nval != uval)
0729         goto retry;
0730 
0731     /*
0732      * Wake robust non-PI futexes here. The wakeup of
0733      * PI futexes happens in exit_pi_state():
0734      */
0735     if (!pi && (uval & FUTEX_WAITERS))
0736         futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
0737 
0738     return 0;
0739 }
0740 
0741 /*
0742  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
0743  */
0744 static inline int fetch_robust_entry(struct robust_list __user **entry,
0745                      struct robust_list __user * __user *head,
0746                      unsigned int *pi)
0747 {
0748     unsigned long uentry;
0749 
0750     if (get_user(uentry, (unsigned long __user *)head))
0751         return -EFAULT;
0752 
0753     *entry = (void __user *)(uentry & ~1UL);
0754     *pi = uentry & 1;
0755 
0756     return 0;
0757 }
0758 
0759 /*
0760  * Walk curr->robust_list (very carefully, it's a userspace list!)
0761  * and mark any locks found there dead, and notify any waiters.
0762  *
0763  * We silently return on any sign of list-walking problem.
0764  */
0765 static void exit_robust_list(struct task_struct *curr)
0766 {
0767     struct robust_list_head __user *head = curr->robust_list;
0768     struct robust_list __user *entry, *next_entry, *pending;
0769     unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
0770     unsigned int next_pi;
0771     unsigned long futex_offset;
0772     int rc;
0773 
0774     /*
0775      * Fetch the list head (which was registered earlier, via
0776      * sys_set_robust_list()):
0777      */
0778     if (fetch_robust_entry(&entry, &head->list.next, &pi))
0779         return;
0780     /*
0781      * Fetch the relative futex offset:
0782      */
0783     if (get_user(futex_offset, &head->futex_offset))
0784         return;
0785     /*
0786      * Fetch any possibly pending lock-add first, and handle it
0787      * if it exists:
0788      */
0789     if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
0790         return;
0791 
0792     next_entry = NULL;  /* avoid warning with gcc */
0793     while (entry != &head->list) {
0794         /*
0795          * Fetch the next entry in the list before calling
0796          * handle_futex_death:
0797          */
0798         rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
0799         /*
0800          * A pending lock might already be on the list, so
0801          * don't process it twice:
0802          */
0803         if (entry != pending) {
0804             if (handle_futex_death((void __user *)entry + futex_offset,
0805                         curr, pi, HANDLE_DEATH_LIST))
0806                 return;
0807         }
0808         if (rc)
0809             return;
0810         entry = next_entry;
0811         pi = next_pi;
0812         /*
0813          * Avoid excessively long or circular lists:
0814          */
0815         if (!--limit)
0816             break;
0817 
0818         cond_resched();
0819     }
0820 
0821     if (pending) {
0822         handle_futex_death((void __user *)pending + futex_offset,
0823                    curr, pip, HANDLE_DEATH_PENDING);
0824     }
0825 }
0826 
0827 #ifdef CONFIG_COMPAT
0828 static void __user *futex_uaddr(struct robust_list __user *entry,
0829                 compat_long_t futex_offset)
0830 {
0831     compat_uptr_t base = ptr_to_compat(entry);
0832     void __user *uaddr = compat_ptr(base + futex_offset);
0833 
0834     return uaddr;
0835 }
0836 
0837 /*
0838  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
0839  */
0840 static inline int
0841 compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
0842            compat_uptr_t __user *head, unsigned int *pi)
0843 {
0844     if (get_user(*uentry, head))
0845         return -EFAULT;
0846 
0847     *entry = compat_ptr((*uentry) & ~1);
0848     *pi = (unsigned int)(*uentry) & 1;
0849 
0850     return 0;
0851 }
0852 
0853 /*
0854  * Walk curr->robust_list (very carefully, it's a userspace list!)
0855  * and mark any locks found there dead, and notify any waiters.
0856  *
0857  * We silently return on any sign of list-walking problem.
0858  */
0859 static void compat_exit_robust_list(struct task_struct *curr)
0860 {
0861     struct compat_robust_list_head __user *head = curr->compat_robust_list;
0862     struct robust_list __user *entry, *next_entry, *pending;
0863     unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
0864     unsigned int next_pi;
0865     compat_uptr_t uentry, next_uentry, upending;
0866     compat_long_t futex_offset;
0867     int rc;
0868 
0869     /*
0870      * Fetch the list head (which was registered earlier, via
0871      * sys_set_robust_list()):
0872      */
0873     if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
0874         return;
0875     /*
0876      * Fetch the relative futex offset:
0877      */
0878     if (get_user(futex_offset, &head->futex_offset))
0879         return;
0880     /*
0881      * Fetch any possibly pending lock-add first, and handle it
0882      * if it exists:
0883      */
0884     if (compat_fetch_robust_entry(&upending, &pending,
0885                    &head->list_op_pending, &pip))
0886         return;
0887 
0888     next_entry = NULL;  /* avoid warning with gcc */
0889     while (entry != (struct robust_list __user *) &head->list) {
0890         /*
0891          * Fetch the next entry in the list before calling
0892          * handle_futex_death:
0893          */
0894         rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
0895             (compat_uptr_t __user *)&entry->next, &next_pi);
0896         /*
0897          * A pending lock might already be on the list, so
0898          * dont process it twice:
0899          */
0900         if (entry != pending) {
0901             void __user *uaddr = futex_uaddr(entry, futex_offset);
0902 
0903             if (handle_futex_death(uaddr, curr, pi,
0904                            HANDLE_DEATH_LIST))
0905                 return;
0906         }
0907         if (rc)
0908             return;
0909         uentry = next_uentry;
0910         entry = next_entry;
0911         pi = next_pi;
0912         /*
0913          * Avoid excessively long or circular lists:
0914          */
0915         if (!--limit)
0916             break;
0917 
0918         cond_resched();
0919     }
0920     if (pending) {
0921         void __user *uaddr = futex_uaddr(pending, futex_offset);
0922 
0923         handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
0924     }
0925 }
0926 #endif
0927 
0928 #ifdef CONFIG_FUTEX_PI
0929 
0930 /*
0931  * This task is holding PI mutexes at exit time => bad.
0932  * Kernel cleans up PI-state, but userspace is likely hosed.
0933  * (Robust-futex cleanup is separate and might save the day for userspace.)
0934  */
0935 static void exit_pi_state_list(struct task_struct *curr)
0936 {
0937     struct list_head *next, *head = &curr->pi_state_list;
0938     struct futex_pi_state *pi_state;
0939     struct futex_hash_bucket *hb;
0940     union futex_key key = FUTEX_KEY_INIT;
0941 
0942     /*
0943      * We are a ZOMBIE and nobody can enqueue itself on
0944      * pi_state_list anymore, but we have to be careful
0945      * versus waiters unqueueing themselves:
0946      */
0947     raw_spin_lock_irq(&curr->pi_lock);
0948     while (!list_empty(head)) {
0949         next = head->next;
0950         pi_state = list_entry(next, struct futex_pi_state, list);
0951         key = pi_state->key;
0952         hb = futex_hash(&key);
0953 
0954         /*
0955          * We can race against put_pi_state() removing itself from the
0956          * list (a waiter going away). put_pi_state() will first
0957          * decrement the reference count and then modify the list, so
0958          * its possible to see the list entry but fail this reference
0959          * acquire.
0960          *
0961          * In that case; drop the locks to let put_pi_state() make
0962          * progress and retry the loop.
0963          */
0964         if (!refcount_inc_not_zero(&pi_state->refcount)) {
0965             raw_spin_unlock_irq(&curr->pi_lock);
0966             cpu_relax();
0967             raw_spin_lock_irq(&curr->pi_lock);
0968             continue;
0969         }
0970         raw_spin_unlock_irq(&curr->pi_lock);
0971 
0972         spin_lock(&hb->lock);
0973         raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
0974         raw_spin_lock(&curr->pi_lock);
0975         /*
0976          * We dropped the pi-lock, so re-check whether this
0977          * task still owns the PI-state:
0978          */
0979         if (head->next != next) {
0980             /* retain curr->pi_lock for the loop invariant */
0981             raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
0982             spin_unlock(&hb->lock);
0983             put_pi_state(pi_state);
0984             continue;
0985         }
0986 
0987         WARN_ON(pi_state->owner != curr);
0988         WARN_ON(list_empty(&pi_state->list));
0989         list_del_init(&pi_state->list);
0990         pi_state->owner = NULL;
0991 
0992         raw_spin_unlock(&curr->pi_lock);
0993         raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
0994         spin_unlock(&hb->lock);
0995 
0996         rt_mutex_futex_unlock(&pi_state->pi_mutex);
0997         put_pi_state(pi_state);
0998 
0999         raw_spin_lock_irq(&curr->pi_lock);
1000     }
1001     raw_spin_unlock_irq(&curr->pi_lock);
1002 }
1003 #else
1004 static inline void exit_pi_state_list(struct task_struct *curr) { }
1005 #endif
1006 
1007 static void futex_cleanup(struct task_struct *tsk)
1008 {
1009     if (unlikely(tsk->robust_list)) {
1010         exit_robust_list(tsk);
1011         tsk->robust_list = NULL;
1012     }
1013 
1014 #ifdef CONFIG_COMPAT
1015     if (unlikely(tsk->compat_robust_list)) {
1016         compat_exit_robust_list(tsk);
1017         tsk->compat_robust_list = NULL;
1018     }
1019 #endif
1020 
1021     if (unlikely(!list_empty(&tsk->pi_state_list)))
1022         exit_pi_state_list(tsk);
1023 }
1024 
1025 /**
1026  * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
1027  * @tsk:    task to set the state on
1028  *
1029  * Set the futex exit state of the task lockless. The futex waiter code
1030  * observes that state when a task is exiting and loops until the task has
1031  * actually finished the futex cleanup. The worst case for this is that the
1032  * waiter runs through the wait loop until the state becomes visible.
1033  *
1034  * This is called from the recursive fault handling path in make_task_dead().
1035  *
1036  * This is best effort. Either the futex exit code has run already or
1037  * not. If the OWNER_DIED bit has been set on the futex then the waiter can
1038  * take it over. If not, the problem is pushed back to user space. If the
1039  * futex exit code did not run yet, then an already queued waiter might
1040  * block forever, but there is nothing which can be done about that.
1041  */
1042 void futex_exit_recursive(struct task_struct *tsk)
1043 {
1044     /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
1045     if (tsk->futex_state == FUTEX_STATE_EXITING)
1046         mutex_unlock(&tsk->futex_exit_mutex);
1047     tsk->futex_state = FUTEX_STATE_DEAD;
1048 }
1049 
1050 static void futex_cleanup_begin(struct task_struct *tsk)
1051 {
1052     /*
1053      * Prevent various race issues against a concurrent incoming waiter
1054      * including live locks by forcing the waiter to block on
1055      * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
1056      * attach_to_pi_owner().
1057      */
1058     mutex_lock(&tsk->futex_exit_mutex);
1059 
1060     /*
1061      * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
1062      *
1063      * This ensures that all subsequent checks of tsk->futex_state in
1064      * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
1065      * tsk->pi_lock held.
1066      *
1067      * It guarantees also that a pi_state which was queued right before
1068      * the state change under tsk->pi_lock by a concurrent waiter must
1069      * be observed in exit_pi_state_list().
1070      */
1071     raw_spin_lock_irq(&tsk->pi_lock);
1072     tsk->futex_state = FUTEX_STATE_EXITING;
1073     raw_spin_unlock_irq(&tsk->pi_lock);
1074 }
1075 
1076 static void futex_cleanup_end(struct task_struct *tsk, int state)
1077 {
1078     /*
1079      * Lockless store. The only side effect is that an observer might
1080      * take another loop until it becomes visible.
1081      */
1082     tsk->futex_state = state;
1083     /*
1084      * Drop the exit protection. This unblocks waiters which observed
1085      * FUTEX_STATE_EXITING to reevaluate the state.
1086      */
1087     mutex_unlock(&tsk->futex_exit_mutex);
1088 }
1089 
1090 void futex_exec_release(struct task_struct *tsk)
1091 {
1092     /*
1093      * The state handling is done for consistency, but in the case of
1094      * exec() there is no way to prevent further damage as the PID stays
1095      * the same. But for the unlikely and arguably buggy case that a
1096      * futex is held on exec(), this provides at least as much state
1097      * consistency protection which is possible.
1098      */
1099     futex_cleanup_begin(tsk);
1100     futex_cleanup(tsk);
1101     /*
1102      * Reset the state to FUTEX_STATE_OK. The task is alive and about
1103      * exec a new binary.
1104      */
1105     futex_cleanup_end(tsk, FUTEX_STATE_OK);
1106 }
1107 
1108 void futex_exit_release(struct task_struct *tsk)
1109 {
1110     futex_cleanup_begin(tsk);
1111     futex_cleanup(tsk);
1112     futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
1113 }
1114 
1115 static int __init futex_init(void)
1116 {
1117     unsigned int futex_shift;
1118     unsigned long i;
1119 
1120 #if CONFIG_BASE_SMALL
1121     futex_hashsize = 16;
1122 #else
1123     futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
1124 #endif
1125 
1126     futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
1127                            futex_hashsize, 0,
1128                            futex_hashsize < 256 ? HASH_SMALL : 0,
1129                            &futex_shift, NULL,
1130                            futex_hashsize, futex_hashsize);
1131     futex_hashsize = 1UL << futex_shift;
1132 
1133     for (i = 0; i < futex_hashsize; i++) {
1134         atomic_set(&futex_queues[i].waiters, 0);
1135         plist_head_init(&futex_queues[i].chain);
1136         spin_lock_init(&futex_queues[i].lock);
1137     }
1138 
1139     return 0;
1140 }
1141 core_initcall(futex_init);