/*1* Fast Userspace Mutexes (which I call "Futexes!").2* (C) Rusty Russell, IBM 20023*4* Generalized futexes, futex requeueing, misc fixes by Ingo Molnar5* (C) Copyright 2003 Red Hat Inc, All Rights Reserved6*7* Removed page pinning, fix privately mapped COW pages and other cleanups8* (C) Copyright 2003, 2004 Jamie Lokier9*10* Robust futex support started by Ingo Molnar11* (C) Copyright 2006 Red Hat Inc, All Rights Reserved12* Thanks to Thomas Gleixner for suggestions, analysis and fixes.13*14* PI-futex support started by Ingo Molnar and Thomas Gleixner15* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <[email protected]>16* Copyright (C) 2006 Timesys Corp., Thomas Gleixner <[email protected]>17*18* PRIVATE futexes by Eric Dumazet19* Copyright (C) 2007 Eric Dumazet <[email protected]>20*21* Requeue-PI support by Darren Hart <[email protected]>22* Copyright (C) IBM Corporation, 200923* Thanks to Thomas Gleixner for conceptual design and careful reviews.24*25* Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly26* enough at me, Linus for the original (flawed) idea, Matthew27* Kirkwood for proof-of-concept implementation.28*29* "The futexes are also cursed."30* "But they come in a choice of three flavours!"31*32* This program is free software; you can redistribute it and/or modify33* it under the terms of the GNU General Public License as published by34* the Free Software Foundation; either version 2 of the License, or35* (at your option) any later version.36*37* This program is distributed in the hope that it will be useful,38* but WITHOUT ANY WARRANTY; without even the implied warranty of39* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the40* GNU General Public License for more details.41*42* You should have received a copy of the GNU General Public License43* along with this program; if not, write to the Free Software44* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA45*/46#include <linux/slab.h>47#include <linux/poll.h>48#include <linux/fs.h>49#include <linux/file.h>50#include <linux/jhash.h>51#include <linux/init.h>52#include <linux/futex.h>53#include <linux/mount.h>54#include <linux/pagemap.h>55#include <linux/syscalls.h>56#include <linux/signal.h>57#include <linux/module.h>58#include <linux/magic.h>59#include <linux/pid.h>60#include <linux/nsproxy.h>6162#include <asm/futex.h>6364#include "rtmutex_common.h"6566int __read_mostly futex_cmpxchg_enabled;6768#define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)6970/*71* Futex flags used to encode options to functions and preserve them across72* restarts.73*/74#define FLAGS_SHARED 0x0175#define FLAGS_CLOCKRT 0x0276#define FLAGS_HAS_TIMEOUT 0x047778/*79* Priority Inheritance state:80*/81struct futex_pi_state {82/*83* list of 'owned' pi_state instances - these have to be84* cleaned up in do_exit() if the task exits prematurely:85*/86struct list_head list;8788/*89* The PI object:90*/91struct rt_mutex pi_mutex;9293struct task_struct *owner;94atomic_t refcount;9596union futex_key key;97};9899/**100* struct futex_q - The hashed futex queue entry, one per waiting task101* @list: priority-sorted list of tasks waiting on this futex102* @task: the task waiting on the futex103* @lock_ptr: the hash bucket lock104* @key: the key the futex is hashed on105* @pi_state: optional priority inheritance state106* @rt_waiter: rt_waiter storage for use with requeue_pi107* @requeue_pi_key: the requeue_pi target futex key108* @bitset: bitset for the optional bitmasked wakeup109*110* We use this hashed waitqueue, instead of a normal wait_queue_t, so111* we can wake only the relevant ones (hashed queues may be shared).112*113* A futex_q has a woken state, just like tasks have TASK_RUNNING.114* It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.115* The order of wakeup is always to make the first condition true, then116* the second.117*118* PI futexes are typically woken before they are removed from the hash list via119* the rt_mutex code. See unqueue_me_pi().120*/121struct futex_q {122struct plist_node list;123124struct task_struct *task;125spinlock_t *lock_ptr;126union futex_key key;127struct futex_pi_state *pi_state;128struct rt_mutex_waiter *rt_waiter;129union futex_key *requeue_pi_key;130u32 bitset;131};132133static const struct futex_q futex_q_init = {134/* list gets initialized in queue_me()*/135.key = FUTEX_KEY_INIT,136.bitset = FUTEX_BITSET_MATCH_ANY137};138139/*140* Hash buckets are shared by all the futex_keys that hash to the same141* location. Each key may have multiple futex_q structures, one for each task142* waiting on a futex.143*/144struct futex_hash_bucket {145spinlock_t lock;146struct plist_head chain;147};148149static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];150151/*152* We hash on the keys returned from get_futex_key (see below).153*/154static struct futex_hash_bucket *hash_futex(union futex_key *key)155{156u32 hash = jhash2((u32*)&key->both.word,157(sizeof(key->both.word)+sizeof(key->both.ptr))/4,158key->both.offset);159return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];160}161162/*163* Return 1 if two futex_keys are equal, 0 otherwise.164*/165static inline int match_futex(union futex_key *key1, union futex_key *key2)166{167return (key1 && key2168&& key1->both.word == key2->both.word169&& key1->both.ptr == key2->both.ptr170&& key1->both.offset == key2->both.offset);171}172173/*174* Take a reference to the resource addressed by a key.175* Can be called while holding spinlocks.176*177*/178static void get_futex_key_refs(union futex_key *key)179{180if (!key->both.ptr)181return;182183switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {184case FUT_OFF_INODE:185ihold(key->shared.inode);186break;187case FUT_OFF_MMSHARED:188atomic_inc(&key->private.mm->mm_count);189break;190}191}192193/*194* Drop a reference to the resource addressed by a key.195* The hash bucket spinlock must not be held.196*/197static void drop_futex_key_refs(union futex_key *key)198{199if (!key->both.ptr) {200/* If we're here then we tried to put a key we failed to get */201WARN_ON_ONCE(1);202return;203}204205switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {206case FUT_OFF_INODE:207iput(key->shared.inode);208break;209case FUT_OFF_MMSHARED:210mmdrop(key->private.mm);211break;212}213}214215/**216* get_futex_key() - Get parameters which are the keys for a futex217* @uaddr: virtual address of the futex218* @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED219* @key: address where result is stored.220*221* Returns a negative error code or 0222* The key words are stored in *key on success.223*224* For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,225* offset_within_page). For private mappings, it's (uaddr, current->mm).226* We can usually work out the index without swapping in the page.227*228* lock_page() might sleep, the caller should not hold a spinlock.229*/230static int231get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key)232{233unsigned long address = (unsigned long)uaddr;234struct mm_struct *mm = current->mm;235struct page *page, *page_head;236int err;237238/*239* The futex address must be "naturally" aligned.240*/241key->both.offset = address % PAGE_SIZE;242if (unlikely((address % sizeof(u32)) != 0))243return -EINVAL;244address -= key->both.offset;245246/*247* PROCESS_PRIVATE futexes are fast.248* As the mm cannot disappear under us and the 'key' only needs249* virtual address, we dont even have to find the underlying vma.250* Note : We do have to check 'uaddr' is a valid user address,251* but access_ok() should be faster than find_vma()252*/253if (!fshared) {254if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))))255return -EFAULT;256key->private.mm = mm;257key->private.address = address;258get_futex_key_refs(key);259return 0;260}261262again:263err = get_user_pages_fast(address, 1, 1, &page);264if (err < 0)265return err;266267#ifdef CONFIG_TRANSPARENT_HUGEPAGE268page_head = page;269if (unlikely(PageTail(page))) {270put_page(page);271/* serialize against __split_huge_page_splitting() */272local_irq_disable();273if (likely(__get_user_pages_fast(address, 1, 1, &page) == 1)) {274page_head = compound_head(page);275/*276* page_head is valid pointer but we must pin277* it before taking the PG_lock and/or278* PG_compound_lock. The moment we re-enable279* irqs __split_huge_page_splitting() can280* return and the head page can be freed from281* under us. We can't take the PG_lock and/or282* PG_compound_lock on a page that could be283* freed from under us.284*/285if (page != page_head) {286get_page(page_head);287put_page(page);288}289local_irq_enable();290} else {291local_irq_enable();292goto again;293}294}295#else296page_head = compound_head(page);297if (page != page_head) {298get_page(page_head);299put_page(page);300}301#endif302303lock_page(page_head);304if (!page_head->mapping) {305unlock_page(page_head);306put_page(page_head);307goto again;308}309310/*311* Private mappings are handled in a simple way.312*313* NOTE: When userspace waits on a MAP_SHARED mapping, even if314* it's a read-only handle, it's expected that futexes attach to315* the object not the particular process.316*/317if (PageAnon(page_head)) {318key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */319key->private.mm = mm;320key->private.address = address;321} else {322key->both.offset |= FUT_OFF_INODE; /* inode-based key */323key->shared.inode = page_head->mapping->host;324key->shared.pgoff = page_head->index;325}326327get_futex_key_refs(key);328329unlock_page(page_head);330put_page(page_head);331return 0;332}333334static inline void put_futex_key(union futex_key *key)335{336drop_futex_key_refs(key);337}338339/**340* fault_in_user_writeable() - Fault in user address and verify RW access341* @uaddr: pointer to faulting user space address342*343* Slow path to fixup the fault we just took in the atomic write344* access to @uaddr.345*346* We have no generic implementation of a non-destructive write to the347* user address. We know that we faulted in the atomic pagefault348* disabled section so we can as well avoid the #PF overhead by349* calling get_user_pages() right away.350*/351static int fault_in_user_writeable(u32 __user *uaddr)352{353struct mm_struct *mm = current->mm;354int ret;355356down_read(&mm->mmap_sem);357ret = get_user_pages(current, mm, (unsigned long)uaddr,3581, 1, 0, NULL, NULL);359up_read(&mm->mmap_sem);360361return ret < 0 ? ret : 0;362}363364/**365* futex_top_waiter() - Return the highest priority waiter on a futex366* @hb: the hash bucket the futex_q's reside in367* @key: the futex key (to distinguish it from other futex futex_q's)368*369* Must be called with the hb lock held.370*/371static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,372union futex_key *key)373{374struct futex_q *this;375376plist_for_each_entry(this, &hb->chain, list) {377if (match_futex(&this->key, key))378return this;379}380return NULL;381}382383static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,384u32 uval, u32 newval)385{386int ret;387388pagefault_disable();389ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);390pagefault_enable();391392return ret;393}394395static int get_futex_value_locked(u32 *dest, u32 __user *from)396{397int ret;398399pagefault_disable();400ret = __copy_from_user_inatomic(dest, from, sizeof(u32));401pagefault_enable();402403return ret ? -EFAULT : 0;404}405406407/*408* PI code:409*/410static int refill_pi_state_cache(void)411{412struct futex_pi_state *pi_state;413414if (likely(current->pi_state_cache))415return 0;416417pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);418419if (!pi_state)420return -ENOMEM;421422INIT_LIST_HEAD(&pi_state->list);423/* pi_mutex gets initialized later */424pi_state->owner = NULL;425atomic_set(&pi_state->refcount, 1);426pi_state->key = FUTEX_KEY_INIT;427428current->pi_state_cache = pi_state;429430return 0;431}432433static struct futex_pi_state * alloc_pi_state(void)434{435struct futex_pi_state *pi_state = current->pi_state_cache;436437WARN_ON(!pi_state);438current->pi_state_cache = NULL;439440return pi_state;441}442443static void free_pi_state(struct futex_pi_state *pi_state)444{445if (!atomic_dec_and_test(&pi_state->refcount))446return;447448/*449* If pi_state->owner is NULL, the owner is most probably dying450* and has cleaned up the pi_state already451*/452if (pi_state->owner) {453raw_spin_lock_irq(&pi_state->owner->pi_lock);454list_del_init(&pi_state->list);455raw_spin_unlock_irq(&pi_state->owner->pi_lock);456457rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);458}459460if (current->pi_state_cache)461kfree(pi_state);462else {463/*464* pi_state->list is already empty.465* clear pi_state->owner.466* refcount is at 0 - put it back to 1.467*/468pi_state->owner = NULL;469atomic_set(&pi_state->refcount, 1);470current->pi_state_cache = pi_state;471}472}473474/*475* Look up the task based on what TID userspace gave us.476* We dont trust it.477*/478static struct task_struct * futex_find_get_task(pid_t pid)479{480struct task_struct *p;481482rcu_read_lock();483p = find_task_by_vpid(pid);484if (p)485get_task_struct(p);486487rcu_read_unlock();488489return p;490}491492/*493* This task is holding PI mutexes at exit time => bad.494* Kernel cleans up PI-state, but userspace is likely hosed.495* (Robust-futex cleanup is separate and might save the day for userspace.)496*/497void exit_pi_state_list(struct task_struct *curr)498{499struct list_head *next, *head = &curr->pi_state_list;500struct futex_pi_state *pi_state;501struct futex_hash_bucket *hb;502union futex_key key = FUTEX_KEY_INIT;503504if (!futex_cmpxchg_enabled)505return;506/*507* We are a ZOMBIE and nobody can enqueue itself on508* pi_state_list anymore, but we have to be careful509* versus waiters unqueueing themselves:510*/511raw_spin_lock_irq(&curr->pi_lock);512while (!list_empty(head)) {513514next = head->next;515pi_state = list_entry(next, struct futex_pi_state, list);516key = pi_state->key;517hb = hash_futex(&key);518raw_spin_unlock_irq(&curr->pi_lock);519520spin_lock(&hb->lock);521522raw_spin_lock_irq(&curr->pi_lock);523/*524* We dropped the pi-lock, so re-check whether this525* task still owns the PI-state:526*/527if (head->next != next) {528spin_unlock(&hb->lock);529continue;530}531532WARN_ON(pi_state->owner != curr);533WARN_ON(list_empty(&pi_state->list));534list_del_init(&pi_state->list);535pi_state->owner = NULL;536raw_spin_unlock_irq(&curr->pi_lock);537538rt_mutex_unlock(&pi_state->pi_mutex);539540spin_unlock(&hb->lock);541542raw_spin_lock_irq(&curr->pi_lock);543}544raw_spin_unlock_irq(&curr->pi_lock);545}546547static int548lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,549union futex_key *key, struct futex_pi_state **ps)550{551struct futex_pi_state *pi_state = NULL;552struct futex_q *this, *next;553struct plist_head *head;554struct task_struct *p;555pid_t pid = uval & FUTEX_TID_MASK;556557head = &hb->chain;558559plist_for_each_entry_safe(this, next, head, list) {560if (match_futex(&this->key, key)) {561/*562* Another waiter already exists - bump up563* the refcount and return its pi_state:564*/565pi_state = this->pi_state;566/*567* Userspace might have messed up non-PI and PI futexes568*/569if (unlikely(!pi_state))570return -EINVAL;571572WARN_ON(!atomic_read(&pi_state->refcount));573574/*575* When pi_state->owner is NULL then the owner died576* and another waiter is on the fly. pi_state->owner577* is fixed up by the task which acquires578* pi_state->rt_mutex.579*580* We do not check for pid == 0 which can happen when581* the owner died and robust_list_exit() cleared the582* TID.583*/584if (pid && pi_state->owner) {585/*586* Bail out if user space manipulated the587* futex value.588*/589if (pid != task_pid_vnr(pi_state->owner))590return -EINVAL;591}592593atomic_inc(&pi_state->refcount);594*ps = pi_state;595596return 0;597}598}599600/*601* We are the first waiter - try to look up the real owner and attach602* the new pi_state to it, but bail out when TID = 0603*/604if (!pid)605return -ESRCH;606p = futex_find_get_task(pid);607if (!p)608return -ESRCH;609610/*611* We need to look at the task state flags to figure out,612* whether the task is exiting. To protect against the do_exit613* change of the task flags, we do this protected by614* p->pi_lock:615*/616raw_spin_lock_irq(&p->pi_lock);617if (unlikely(p->flags & PF_EXITING)) {618/*619* The task is on the way out. When PF_EXITPIDONE is620* set, we know that the task has finished the621* cleanup:622*/623int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;624625raw_spin_unlock_irq(&p->pi_lock);626put_task_struct(p);627return ret;628}629630pi_state = alloc_pi_state();631632/*633* Initialize the pi_mutex in locked state and make 'p'634* the owner of it:635*/636rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);637638/* Store the key for possible exit cleanups: */639pi_state->key = *key;640641WARN_ON(!list_empty(&pi_state->list));642list_add(&pi_state->list, &p->pi_state_list);643pi_state->owner = p;644raw_spin_unlock_irq(&p->pi_lock);645646put_task_struct(p);647648*ps = pi_state;649650return 0;651}652653/**654* futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex655* @uaddr: the pi futex user address656* @hb: the pi futex hash bucket657* @key: the futex key associated with uaddr and hb658* @ps: the pi_state pointer where we store the result of the659* lookup660* @task: the task to perform the atomic lock work for. This will661* be "current" except in the case of requeue pi.662* @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)663*664* Returns:665* 0 - ready to wait666* 1 - acquired the lock667* <0 - error668*669* The hb->lock and futex_key refs shall be held by the caller.670*/671static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,672union futex_key *key,673struct futex_pi_state **ps,674struct task_struct *task, int set_waiters)675{676int lock_taken, ret, ownerdied = 0;677u32 uval, newval, curval, vpid = task_pid_vnr(task);678679retry:680ret = lock_taken = 0;681682/*683* To avoid races, we attempt to take the lock here again684* (by doing a 0 -> TID atomic cmpxchg), while holding all685* the locks. It will most likely not succeed.686*/687newval = vpid;688if (set_waiters)689newval |= FUTEX_WAITERS;690691if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, 0, newval)))692return -EFAULT;693694/*695* Detect deadlocks.696*/697if ((unlikely((curval & FUTEX_TID_MASK) == vpid)))698return -EDEADLK;699700/*701* Surprise - we got the lock. Just return to userspace:702*/703if (unlikely(!curval))704return 1;705706uval = curval;707708/*709* Set the FUTEX_WAITERS flag, so the owner will know it has someone710* to wake at the next unlock.711*/712newval = curval | FUTEX_WAITERS;713714/*715* There are two cases, where a futex might have no owner (the716* owner TID is 0): OWNER_DIED. We take over the futex in this717* case. We also do an unconditional take over, when the owner718* of the futex died.719*720* This is safe as we are protected by the hash bucket lock !721*/722if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) {723/* Keep the OWNER_DIED bit */724newval = (curval & ~FUTEX_TID_MASK) | vpid;725ownerdied = 0;726lock_taken = 1;727}728729if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))730return -EFAULT;731if (unlikely(curval != uval))732goto retry;733734/*735* We took the lock due to owner died take over.736*/737if (unlikely(lock_taken))738return 1;739740/*741* We dont have the lock. Look up the PI state (or create it if742* we are the first waiter):743*/744ret = lookup_pi_state(uval, hb, key, ps);745746if (unlikely(ret)) {747switch (ret) {748case -ESRCH:749/*750* No owner found for this futex. Check if the751* OWNER_DIED bit is set to figure out whether752* this is a robust futex or not.753*/754if (get_futex_value_locked(&curval, uaddr))755return -EFAULT;756757/*758* We simply start over in case of a robust759* futex. The code above will take the futex760* and return happy.761*/762if (curval & FUTEX_OWNER_DIED) {763ownerdied = 1;764goto retry;765}766default:767break;768}769}770771return ret;772}773774/**775* __unqueue_futex() - Remove the futex_q from its futex_hash_bucket776* @q: The futex_q to unqueue777*778* The q->lock_ptr must not be NULL and must be held by the caller.779*/780static void __unqueue_futex(struct futex_q *q)781{782struct futex_hash_bucket *hb;783784if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))785|| WARN_ON(plist_node_empty(&q->list)))786return;787788hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);789plist_del(&q->list, &hb->chain);790}791792/*793* The hash bucket lock must be held when this is called.794* Afterwards, the futex_q must not be accessed.795*/796static void wake_futex(struct futex_q *q)797{798struct task_struct *p = q->task;799800/*801* We set q->lock_ptr = NULL _before_ we wake up the task. If802* a non-futex wake up happens on another CPU then the task803* might exit and p would dereference a non-existing task804* struct. Prevent this by holding a reference on p across the805* wake up.806*/807get_task_struct(p);808809__unqueue_futex(q);810/*811* The waiting task can free the futex_q as soon as812* q->lock_ptr = NULL is written, without taking any locks. A813* memory barrier is required here to prevent the following814* store to lock_ptr from getting ahead of the plist_del.815*/816smp_wmb();817q->lock_ptr = NULL;818819wake_up_state(p, TASK_NORMAL);820put_task_struct(p);821}822823static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)824{825struct task_struct *new_owner;826struct futex_pi_state *pi_state = this->pi_state;827u32 curval, newval;828829if (!pi_state)830return -EINVAL;831832/*833* If current does not own the pi_state then the futex is834* inconsistent and user space fiddled with the futex value.835*/836if (pi_state->owner != current)837return -EINVAL;838839raw_spin_lock(&pi_state->pi_mutex.wait_lock);840new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);841842/*843* It is possible that the next waiter (the one that brought844* this owner to the kernel) timed out and is no longer845* waiting on the lock.846*/847if (!new_owner)848new_owner = this->task;849850/*851* We pass it to the next owner. (The WAITERS bit is always852* kept enabled while there is PI state around. We must also853* preserve the owner died bit.)854*/855if (!(uval & FUTEX_OWNER_DIED)) {856int ret = 0;857858newval = FUTEX_WAITERS | task_pid_vnr(new_owner);859860if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))861ret = -EFAULT;862else if (curval != uval)863ret = -EINVAL;864if (ret) {865raw_spin_unlock(&pi_state->pi_mutex.wait_lock);866return ret;867}868}869870raw_spin_lock_irq(&pi_state->owner->pi_lock);871WARN_ON(list_empty(&pi_state->list));872list_del_init(&pi_state->list);873raw_spin_unlock_irq(&pi_state->owner->pi_lock);874875raw_spin_lock_irq(&new_owner->pi_lock);876WARN_ON(!list_empty(&pi_state->list));877list_add(&pi_state->list, &new_owner->pi_state_list);878pi_state->owner = new_owner;879raw_spin_unlock_irq(&new_owner->pi_lock);880881raw_spin_unlock(&pi_state->pi_mutex.wait_lock);882rt_mutex_unlock(&pi_state->pi_mutex);883884return 0;885}886887static int unlock_futex_pi(u32 __user *uaddr, u32 uval)888{889u32 oldval;890891/*892* There is no waiter, so we unlock the futex. The owner died893* bit has not to be preserved here. We are the owner:894*/895if (cmpxchg_futex_value_locked(&oldval, uaddr, uval, 0))896return -EFAULT;897if (oldval != uval)898return -EAGAIN;899900return 0;901}902903/*904* Express the locking dependencies for lockdep:905*/906static inline void907double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)908{909if (hb1 <= hb2) {910spin_lock(&hb1->lock);911if (hb1 < hb2)912spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);913} else { /* hb1 > hb2 */914spin_lock(&hb2->lock);915spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);916}917}918919static inline void920double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)921{922spin_unlock(&hb1->lock);923if (hb1 != hb2)924spin_unlock(&hb2->lock);925}926927/*928* Wake up waiters matching bitset queued on this futex (uaddr).929*/930static int931futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)932{933struct futex_hash_bucket *hb;934struct futex_q *this, *next;935struct plist_head *head;936union futex_key key = FUTEX_KEY_INIT;937int ret;938939if (!bitset)940return -EINVAL;941942ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key);943if (unlikely(ret != 0))944goto out;945946hb = hash_futex(&key);947spin_lock(&hb->lock);948head = &hb->chain;949950plist_for_each_entry_safe(this, next, head, list) {951if (match_futex (&this->key, &key)) {952if (this->pi_state || this->rt_waiter) {953ret = -EINVAL;954break;955}956957/* Check if one of the bits is set in both bitsets */958if (!(this->bitset & bitset))959continue;960961wake_futex(this);962if (++ret >= nr_wake)963break;964}965}966967spin_unlock(&hb->lock);968put_futex_key(&key);969out:970return ret;971}972973/*974* Wake up all waiters hashed on the physical page that is mapped975* to this virtual address:976*/977static int978futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,979int nr_wake, int nr_wake2, int op)980{981union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;982struct futex_hash_bucket *hb1, *hb2;983struct plist_head *head;984struct futex_q *this, *next;985int ret, op_ret;986987retry:988ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1);989if (unlikely(ret != 0))990goto out;991ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2);992if (unlikely(ret != 0))993goto out_put_key1;994995hb1 = hash_futex(&key1);996hb2 = hash_futex(&key2);997998retry_private:999double_lock_hb(hb1, hb2);1000op_ret = futex_atomic_op_inuser(op, uaddr2);1001if (unlikely(op_ret < 0)) {10021003double_unlock_hb(hb1, hb2);10041005#ifndef CONFIG_MMU1006/*1007* we don't get EFAULT from MMU faults if we don't have an MMU,1008* but we might get them from range checking1009*/1010ret = op_ret;1011goto out_put_keys;1012#endif10131014if (unlikely(op_ret != -EFAULT)) {1015ret = op_ret;1016goto out_put_keys;1017}10181019ret = fault_in_user_writeable(uaddr2);1020if (ret)1021goto out_put_keys;10221023if (!(flags & FLAGS_SHARED))1024goto retry_private;10251026put_futex_key(&key2);1027put_futex_key(&key1);1028goto retry;1029}10301031head = &hb1->chain;10321033plist_for_each_entry_safe(this, next, head, list) {1034if (match_futex (&this->key, &key1)) {1035wake_futex(this);1036if (++ret >= nr_wake)1037break;1038}1039}10401041if (op_ret > 0) {1042head = &hb2->chain;10431044op_ret = 0;1045plist_for_each_entry_safe(this, next, head, list) {1046if (match_futex (&this->key, &key2)) {1047wake_futex(this);1048if (++op_ret >= nr_wake2)1049break;1050}1051}1052ret += op_ret;1053}10541055double_unlock_hb(hb1, hb2);1056out_put_keys:1057put_futex_key(&key2);1058out_put_key1:1059put_futex_key(&key1);1060out:1061return ret;1062}10631064/**1065* requeue_futex() - Requeue a futex_q from one hb to another1066* @q: the futex_q to requeue1067* @hb1: the source hash_bucket1068* @hb2: the target hash_bucket1069* @key2: the new key for the requeued futex_q1070*/1071static inline1072void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,1073struct futex_hash_bucket *hb2, union futex_key *key2)1074{10751076/*1077* If key1 and key2 hash to the same bucket, no need to1078* requeue.1079*/1080if (likely(&hb1->chain != &hb2->chain)) {1081plist_del(&q->list, &hb1->chain);1082plist_add(&q->list, &hb2->chain);1083q->lock_ptr = &hb2->lock;1084}1085get_futex_key_refs(key2);1086q->key = *key2;1087}10881089/**1090* requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue1091* @q: the futex_q1092* @key: the key of the requeue target futex1093* @hb: the hash_bucket of the requeue target futex1094*1095* During futex_requeue, with requeue_pi=1, it is possible to acquire the1096* target futex if it is uncontended or via a lock steal. Set the futex_q key1097* to the requeue target futex so the waiter can detect the wakeup on the right1098* futex, but remove it from the hb and NULL the rt_waiter so it can detect1099* atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock1100* to protect access to the pi_state to fixup the owner later. Must be called1101* with both q->lock_ptr and hb->lock held.1102*/1103static inline1104void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,1105struct futex_hash_bucket *hb)1106{1107get_futex_key_refs(key);1108q->key = *key;11091110__unqueue_futex(q);11111112WARN_ON(!q->rt_waiter);1113q->rt_waiter = NULL;11141115q->lock_ptr = &hb->lock;11161117wake_up_state(q->task, TASK_NORMAL);1118}11191120/**1121* futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter1122* @pifutex: the user address of the to futex1123* @hb1: the from futex hash bucket, must be locked by the caller1124* @hb2: the to futex hash bucket, must be locked by the caller1125* @key1: the from futex key1126* @key2: the to futex key1127* @ps: address to store the pi_state pointer1128* @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)1129*1130* Try and get the lock on behalf of the top waiter if we can do it atomically.1131* Wake the top waiter if we succeed. If the caller specified set_waiters,1132* then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.1133* hb1 and hb2 must be held by the caller.1134*1135* Returns:1136* 0 - failed to acquire the lock atomicly1137* 1 - acquired the lock1138* <0 - error1139*/1140static int futex_proxy_trylock_atomic(u32 __user *pifutex,1141struct futex_hash_bucket *hb1,1142struct futex_hash_bucket *hb2,1143union futex_key *key1, union futex_key *key2,1144struct futex_pi_state **ps, int set_waiters)1145{1146struct futex_q *top_waiter = NULL;1147u32 curval;1148int ret;11491150if (get_futex_value_locked(&curval, pifutex))1151return -EFAULT;11521153/*1154* Find the top_waiter and determine if there are additional waiters.1155* If the caller intends to requeue more than 1 waiter to pifutex,1156* force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,1157* as we have means to handle the possible fault. If not, don't set1158* the bit unecessarily as it will force the subsequent unlock to enter1159* the kernel.1160*/1161top_waiter = futex_top_waiter(hb1, key1);11621163/* There are no waiters, nothing for us to do. */1164if (!top_waiter)1165return 0;11661167/* Ensure we requeue to the expected futex. */1168if (!match_futex(top_waiter->requeue_pi_key, key2))1169return -EINVAL;11701171/*1172* Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in1173* the contended case or if set_waiters is 1. The pi_state is returned1174* in ps in contended cases.1175*/1176ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,1177set_waiters);1178if (ret == 1)1179requeue_pi_wake_futex(top_waiter, key2, hb2);11801181return ret;1182}11831184/**1185* futex_requeue() - Requeue waiters from uaddr1 to uaddr21186* @uaddr1: source futex user address1187* @flags: futex flags (FLAGS_SHARED, etc.)1188* @uaddr2: target futex user address1189* @nr_wake: number of waiters to wake (must be 1 for requeue_pi)1190* @nr_requeue: number of waiters to requeue (0-INT_MAX)1191* @cmpval: @uaddr1 expected value (or %NULL)1192* @requeue_pi: if we are attempting to requeue from a non-pi futex to a1193* pi futex (pi to pi requeue is not supported)1194*1195* Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire1196* uaddr2 atomically on behalf of the top waiter.1197*1198* Returns:1199* >=0 - on success, the number of tasks requeued or woken1200* <0 - on error1201*/1202static int futex_requeue(u32 __user *uaddr1, unsigned int flags,1203u32 __user *uaddr2, int nr_wake, int nr_requeue,1204u32 *cmpval, int requeue_pi)1205{1206union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;1207int drop_count = 0, task_count = 0, ret;1208struct futex_pi_state *pi_state = NULL;1209struct futex_hash_bucket *hb1, *hb2;1210struct plist_head *head1;1211struct futex_q *this, *next;1212u32 curval2;12131214if (requeue_pi) {1215/*1216* requeue_pi requires a pi_state, try to allocate it now1217* without any locks in case it fails.1218*/1219if (refill_pi_state_cache())1220return -ENOMEM;1221/*1222* requeue_pi must wake as many tasks as it can, up to nr_wake1223* + nr_requeue, since it acquires the rt_mutex prior to1224* returning to userspace, so as to not leave the rt_mutex with1225* waiters and no owner. However, second and third wake-ups1226* cannot be predicted as they involve race conditions with the1227* first wake and a fault while looking up the pi_state. Both1228* pthread_cond_signal() and pthread_cond_broadcast() should1229* use nr_wake=1.1230*/1231if (nr_wake != 1)1232return -EINVAL;1233}12341235retry:1236if (pi_state != NULL) {1237/*1238* We will have to lookup the pi_state again, so free this one1239* to keep the accounting correct.1240*/1241free_pi_state(pi_state);1242pi_state = NULL;1243}12441245ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1);1246if (unlikely(ret != 0))1247goto out;1248ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2);1249if (unlikely(ret != 0))1250goto out_put_key1;12511252hb1 = hash_futex(&key1);1253hb2 = hash_futex(&key2);12541255retry_private:1256double_lock_hb(hb1, hb2);12571258if (likely(cmpval != NULL)) {1259u32 curval;12601261ret = get_futex_value_locked(&curval, uaddr1);12621263if (unlikely(ret)) {1264double_unlock_hb(hb1, hb2);12651266ret = get_user(curval, uaddr1);1267if (ret)1268goto out_put_keys;12691270if (!(flags & FLAGS_SHARED))1271goto retry_private;12721273put_futex_key(&key2);1274put_futex_key(&key1);1275goto retry;1276}1277if (curval != *cmpval) {1278ret = -EAGAIN;1279goto out_unlock;1280}1281}12821283if (requeue_pi && (task_count - nr_wake < nr_requeue)) {1284/*1285* Attempt to acquire uaddr2 and wake the top waiter. If we1286* intend to requeue waiters, force setting the FUTEX_WAITERS1287* bit. We force this here where we are able to easily handle1288* faults rather in the requeue loop below.1289*/1290ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,1291&key2, &pi_state, nr_requeue);12921293/*1294* At this point the top_waiter has either taken uaddr2 or is1295* waiting on it. If the former, then the pi_state will not1296* exist yet, look it up one more time to ensure we have a1297* reference to it.1298*/1299if (ret == 1) {1300WARN_ON(pi_state);1301drop_count++;1302task_count++;1303ret = get_futex_value_locked(&curval2, uaddr2);1304if (!ret)1305ret = lookup_pi_state(curval2, hb2, &key2,1306&pi_state);1307}13081309switch (ret) {1310case 0:1311break;1312case -EFAULT:1313double_unlock_hb(hb1, hb2);1314put_futex_key(&key2);1315put_futex_key(&key1);1316ret = fault_in_user_writeable(uaddr2);1317if (!ret)1318goto retry;1319goto out;1320case -EAGAIN:1321/* The owner was exiting, try again. */1322double_unlock_hb(hb1, hb2);1323put_futex_key(&key2);1324put_futex_key(&key1);1325cond_resched();1326goto retry;1327default:1328goto out_unlock;1329}1330}13311332head1 = &hb1->chain;1333plist_for_each_entry_safe(this, next, head1, list) {1334if (task_count - nr_wake >= nr_requeue)1335break;13361337if (!match_futex(&this->key, &key1))1338continue;13391340/*1341* FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always1342* be paired with each other and no other futex ops.1343*/1344if ((requeue_pi && !this->rt_waiter) ||1345(!requeue_pi && this->rt_waiter)) {1346ret = -EINVAL;1347break;1348}13491350/*1351* Wake nr_wake waiters. For requeue_pi, if we acquired the1352* lock, we already woke the top_waiter. If not, it will be1353* woken by futex_unlock_pi().1354*/1355if (++task_count <= nr_wake && !requeue_pi) {1356wake_futex(this);1357continue;1358}13591360/* Ensure we requeue to the expected futex for requeue_pi. */1361if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {1362ret = -EINVAL;1363break;1364}13651366/*1367* Requeue nr_requeue waiters and possibly one more in the case1368* of requeue_pi if we couldn't acquire the lock atomically.1369*/1370if (requeue_pi) {1371/* Prepare the waiter to take the rt_mutex. */1372atomic_inc(&pi_state->refcount);1373this->pi_state = pi_state;1374ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,1375this->rt_waiter,1376this->task, 1);1377if (ret == 1) {1378/* We got the lock. */1379requeue_pi_wake_futex(this, &key2, hb2);1380drop_count++;1381continue;1382} else if (ret) {1383/* -EDEADLK */1384this->pi_state = NULL;1385free_pi_state(pi_state);1386goto out_unlock;1387}1388}1389requeue_futex(this, hb1, hb2, &key2);1390drop_count++;1391}13921393out_unlock:1394double_unlock_hb(hb1, hb2);13951396/*1397* drop_futex_key_refs() must be called outside the spinlocks. During1398* the requeue we moved futex_q's from the hash bucket at key1 to the1399* one at key2 and updated their key pointer. We no longer need to1400* hold the references to key1.1401*/1402while (--drop_count >= 0)1403drop_futex_key_refs(&key1);14041405out_put_keys:1406put_futex_key(&key2);1407out_put_key1:1408put_futex_key(&key1);1409out:1410if (pi_state != NULL)1411free_pi_state(pi_state);1412return ret ? ret : task_count;1413}14141415/* The key must be already stored in q->key. */1416static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)1417__acquires(&hb->lock)1418{1419struct futex_hash_bucket *hb;14201421hb = hash_futex(&q->key);1422q->lock_ptr = &hb->lock;14231424spin_lock(&hb->lock);1425return hb;1426}14271428static inline void1429queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)1430__releases(&hb->lock)1431{1432spin_unlock(&hb->lock);1433}14341435/**1436* queue_me() - Enqueue the futex_q on the futex_hash_bucket1437* @q: The futex_q to enqueue1438* @hb: The destination hash bucket1439*1440* The hb->lock must be held by the caller, and is released here. A call to1441* queue_me() is typically paired with exactly one call to unqueue_me(). The1442* exceptions involve the PI related operations, which may use unqueue_me_pi()1443* or nothing if the unqueue is done as part of the wake process and the unqueue1444* state is implicit in the state of woken task (see futex_wait_requeue_pi() for1445* an example).1446*/1447static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)1448__releases(&hb->lock)1449{1450int prio;14511452/*1453* The priority used to register this element is1454* - either the real thread-priority for the real-time threads1455* (i.e. threads with a priority lower than MAX_RT_PRIO)1456* - or MAX_RT_PRIO for non-RT threads.1457* Thus, all RT-threads are woken first in priority order, and1458* the others are woken last, in FIFO order.1459*/1460prio = min(current->normal_prio, MAX_RT_PRIO);14611462plist_node_init(&q->list, prio);1463plist_add(&q->list, &hb->chain);1464q->task = current;1465spin_unlock(&hb->lock);1466}14671468/**1469* unqueue_me() - Remove the futex_q from its futex_hash_bucket1470* @q: The futex_q to unqueue1471*1472* The q->lock_ptr must not be held by the caller. A call to unqueue_me() must1473* be paired with exactly one earlier call to queue_me().1474*1475* Returns:1476* 1 - if the futex_q was still queued (and we removed unqueued it)1477* 0 - if the futex_q was already removed by the waking thread1478*/1479static int unqueue_me(struct futex_q *q)1480{1481spinlock_t *lock_ptr;1482int ret = 0;14831484/* In the common case we don't take the spinlock, which is nice. */1485retry:1486lock_ptr = q->lock_ptr;1487barrier();1488if (lock_ptr != NULL) {1489spin_lock(lock_ptr);1490/*1491* q->lock_ptr can change between reading it and1492* spin_lock(), causing us to take the wrong lock. This1493* corrects the race condition.1494*1495* Reasoning goes like this: if we have the wrong lock,1496* q->lock_ptr must have changed (maybe several times)1497* between reading it and the spin_lock(). It can1498* change again after the spin_lock() but only if it was1499* already changed before the spin_lock(). It cannot,1500* however, change back to the original value. Therefore1501* we can detect whether we acquired the correct lock.1502*/1503if (unlikely(lock_ptr != q->lock_ptr)) {1504spin_unlock(lock_ptr);1505goto retry;1506}1507__unqueue_futex(q);15081509BUG_ON(q->pi_state);15101511spin_unlock(lock_ptr);1512ret = 1;1513}15141515drop_futex_key_refs(&q->key);1516return ret;1517}15181519/*1520* PI futexes can not be requeued and must remove themself from the1521* hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry1522* and dropped here.1523*/1524static void unqueue_me_pi(struct futex_q *q)1525__releases(q->lock_ptr)1526{1527__unqueue_futex(q);15281529BUG_ON(!q->pi_state);1530free_pi_state(q->pi_state);1531q->pi_state = NULL;15321533spin_unlock(q->lock_ptr);1534}15351536/*1537* Fixup the pi_state owner with the new owner.1538*1539* Must be called with hash bucket lock held and mm->sem held for non1540* private futexes.1541*/1542static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,1543struct task_struct *newowner)1544{1545u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;1546struct futex_pi_state *pi_state = q->pi_state;1547struct task_struct *oldowner = pi_state->owner;1548u32 uval, curval, newval;1549int ret;15501551/* Owner died? */1552if (!pi_state->owner)1553newtid |= FUTEX_OWNER_DIED;15541555/*1556* We are here either because we stole the rtmutex from the1557* previous highest priority waiter or we are the highest priority1558* waiter but failed to get the rtmutex the first time.1559* We have to replace the newowner TID in the user space variable.1560* This must be atomic as we have to preserve the owner died bit here.1561*1562* Note: We write the user space value _before_ changing the pi_state1563* because we can fault here. Imagine swapped out pages or a fork1564* that marked all the anonymous memory readonly for cow.1565*1566* Modifying pi_state _before_ the user space value would1567* leave the pi_state in an inconsistent state when we fault1568* here, because we need to drop the hash bucket lock to1569* handle the fault. This might be observed in the PID check1570* in lookup_pi_state.1571*/1572retry:1573if (get_futex_value_locked(&uval, uaddr))1574goto handle_fault;15751576while (1) {1577newval = (uval & FUTEX_OWNER_DIED) | newtid;15781579if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))1580goto handle_fault;1581if (curval == uval)1582break;1583uval = curval;1584}15851586/*1587* We fixed up user space. Now we need to fix the pi_state1588* itself.1589*/1590if (pi_state->owner != NULL) {1591raw_spin_lock_irq(&pi_state->owner->pi_lock);1592WARN_ON(list_empty(&pi_state->list));1593list_del_init(&pi_state->list);1594raw_spin_unlock_irq(&pi_state->owner->pi_lock);1595}15961597pi_state->owner = newowner;15981599raw_spin_lock_irq(&newowner->pi_lock);1600WARN_ON(!list_empty(&pi_state->list));1601list_add(&pi_state->list, &newowner->pi_state_list);1602raw_spin_unlock_irq(&newowner->pi_lock);1603return 0;16041605/*1606* To handle the page fault we need to drop the hash bucket1607* lock here. That gives the other task (either the highest priority1608* waiter itself or the task which stole the rtmutex) the1609* chance to try the fixup of the pi_state. So once we are1610* back from handling the fault we need to check the pi_state1611* after reacquiring the hash bucket lock and before trying to1612* do another fixup. When the fixup has been done already we1613* simply return.1614*/1615handle_fault:1616spin_unlock(q->lock_ptr);16171618ret = fault_in_user_writeable(uaddr);16191620spin_lock(q->lock_ptr);16211622/*1623* Check if someone else fixed it for us:1624*/1625if (pi_state->owner != oldowner)1626return 0;16271628if (ret)1629return ret;16301631goto retry;1632}16331634static long futex_wait_restart(struct restart_block *restart);16351636/**1637* fixup_owner() - Post lock pi_state and corner case management1638* @uaddr: user address of the futex1639* @q: futex_q (contains pi_state and access to the rt_mutex)1640* @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)1641*1642* After attempting to lock an rt_mutex, this function is called to cleanup1643* the pi_state owner as well as handle race conditions that may allow us to1644* acquire the lock. Must be called with the hb lock held.1645*1646* Returns:1647* 1 - success, lock taken1648* 0 - success, lock not taken1649* <0 - on error (-EFAULT)1650*/1651static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)1652{1653struct task_struct *owner;1654int ret = 0;16551656if (locked) {1657/*1658* Got the lock. We might not be the anticipated owner if we1659* did a lock-steal - fix up the PI-state in that case:1660*/1661if (q->pi_state->owner != current)1662ret = fixup_pi_state_owner(uaddr, q, current);1663goto out;1664}16651666/*1667* Catch the rare case, where the lock was released when we were on the1668* way back before we locked the hash bucket.1669*/1670if (q->pi_state->owner == current) {1671/*1672* Try to get the rt_mutex now. This might fail as some other1673* task acquired the rt_mutex after we removed ourself from the1674* rt_mutex waiters list.1675*/1676if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {1677locked = 1;1678goto out;1679}16801681/*1682* pi_state is incorrect, some other task did a lock steal and1683* we returned due to timeout or signal without taking the1684* rt_mutex. Too late.1685*/1686raw_spin_lock(&q->pi_state->pi_mutex.wait_lock);1687owner = rt_mutex_owner(&q->pi_state->pi_mutex);1688if (!owner)1689owner = rt_mutex_next_owner(&q->pi_state->pi_mutex);1690raw_spin_unlock(&q->pi_state->pi_mutex.wait_lock);1691ret = fixup_pi_state_owner(uaddr, q, owner);1692goto out;1693}16941695/*1696* Paranoia check. If we did not take the lock, then we should not be1697* the owner of the rt_mutex.1698*/1699if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)1700printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "1701"pi-state %p\n", ret,1702q->pi_state->pi_mutex.owner,1703q->pi_state->owner);17041705out:1706return ret ? ret : locked;1707}17081709/**1710* futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal1711* @hb: the futex hash bucket, must be locked by the caller1712* @q: the futex_q to queue up on1713* @timeout: the prepared hrtimer_sleeper, or null for no timeout1714*/1715static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,1716struct hrtimer_sleeper *timeout)1717{1718/*1719* The task state is guaranteed to be set before another task can1720* wake it. set_current_state() is implemented using set_mb() and1721* queue_me() calls spin_unlock() upon completion, both serializing1722* access to the hash list and forcing another memory barrier.1723*/1724set_current_state(TASK_INTERRUPTIBLE);1725queue_me(q, hb);17261727/* Arm the timer */1728if (timeout) {1729hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);1730if (!hrtimer_active(&timeout->timer))1731timeout->task = NULL;1732}17331734/*1735* If we have been removed from the hash list, then another task1736* has tried to wake us, and we can skip the call to schedule().1737*/1738if (likely(!plist_node_empty(&q->list))) {1739/*1740* If the timer has already expired, current will already be1741* flagged for rescheduling. Only call schedule if there1742* is no timeout, or if it has yet to expire.1743*/1744if (!timeout || timeout->task)1745schedule();1746}1747__set_current_state(TASK_RUNNING);1748}17491750/**1751* futex_wait_setup() - Prepare to wait on a futex1752* @uaddr: the futex userspace address1753* @val: the expected value1754* @flags: futex flags (FLAGS_SHARED, etc.)1755* @q: the associated futex_q1756* @hb: storage for hash_bucket pointer to be returned to caller1757*1758* Setup the futex_q and locate the hash_bucket. Get the futex value and1759* compare it with the expected value. Handle atomic faults internally.1760* Return with the hb lock held and a q.key reference on success, and unlocked1761* with no q.key reference on failure.1762*1763* Returns:1764* 0 - uaddr contains val and hb has been locked1765* <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlcoked1766*/1767static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,1768struct futex_q *q, struct futex_hash_bucket **hb)1769{1770u32 uval;1771int ret;17721773/*1774* Access the page AFTER the hash-bucket is locked.1775* Order is important:1776*1777* Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);1778* Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }1779*1780* The basic logical guarantee of a futex is that it blocks ONLY1781* if cond(var) is known to be true at the time of blocking, for1782* any cond. If we locked the hash-bucket after testing *uaddr, that1783* would open a race condition where we could block indefinitely with1784* cond(var) false, which would violate the guarantee.1785*1786* On the other hand, we insert q and release the hash-bucket only1787* after testing *uaddr. This guarantees that futex_wait() will NOT1788* absorb a wakeup if *uaddr does not match the desired values1789* while the syscall executes.1790*/1791retry:1792ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key);1793if (unlikely(ret != 0))1794return ret;17951796retry_private:1797*hb = queue_lock(q);17981799ret = get_futex_value_locked(&uval, uaddr);18001801if (ret) {1802queue_unlock(q, *hb);18031804ret = get_user(uval, uaddr);1805if (ret)1806goto out;18071808if (!(flags & FLAGS_SHARED))1809goto retry_private;18101811put_futex_key(&q->key);1812goto retry;1813}18141815if (uval != val) {1816queue_unlock(q, *hb);1817ret = -EWOULDBLOCK;1818}18191820out:1821if (ret)1822put_futex_key(&q->key);1823return ret;1824}18251826static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,1827ktime_t *abs_time, u32 bitset)1828{1829struct hrtimer_sleeper timeout, *to = NULL;1830struct restart_block *restart;1831struct futex_hash_bucket *hb;1832struct futex_q q = futex_q_init;1833int ret;18341835if (!bitset)1836return -EINVAL;1837q.bitset = bitset;18381839if (abs_time) {1840to = &timeout;18411842hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?1843CLOCK_REALTIME : CLOCK_MONOTONIC,1844HRTIMER_MODE_ABS);1845hrtimer_init_sleeper(to, current);1846hrtimer_set_expires_range_ns(&to->timer, *abs_time,1847current->timer_slack_ns);1848}18491850retry:1851/*1852* Prepare to wait on uaddr. On success, holds hb lock and increments1853* q.key refs.1854*/1855ret = futex_wait_setup(uaddr, val, flags, &q, &hb);1856if (ret)1857goto out;18581859/* queue_me and wait for wakeup, timeout, or a signal. */1860futex_wait_queue_me(hb, &q, to);18611862/* If we were woken (and unqueued), we succeeded, whatever. */1863ret = 0;1864/* unqueue_me() drops q.key ref */1865if (!unqueue_me(&q))1866goto out;1867ret = -ETIMEDOUT;1868if (to && !to->task)1869goto out;18701871/*1872* We expect signal_pending(current), but we might be the1873* victim of a spurious wakeup as well.1874*/1875if (!signal_pending(current))1876goto retry;18771878ret = -ERESTARTSYS;1879if (!abs_time)1880goto out;18811882restart = ¤t_thread_info()->restart_block;1883restart->fn = futex_wait_restart;1884restart->futex.uaddr = uaddr;1885restart->futex.val = val;1886restart->futex.time = abs_time->tv64;1887restart->futex.bitset = bitset;1888restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;18891890ret = -ERESTART_RESTARTBLOCK;18911892out:1893if (to) {1894hrtimer_cancel(&to->timer);1895destroy_hrtimer_on_stack(&to->timer);1896}1897return ret;1898}189919001901static long futex_wait_restart(struct restart_block *restart)1902{1903u32 __user *uaddr = restart->futex.uaddr;1904ktime_t t, *tp = NULL;19051906if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {1907t.tv64 = restart->futex.time;1908tp = &t;1909}1910restart->fn = do_no_restart_syscall;19111912return (long)futex_wait(uaddr, restart->futex.flags,1913restart->futex.val, tp, restart->futex.bitset);1914}191519161917/*1918* Userspace tried a 0 -> TID atomic transition of the futex value1919* and failed. The kernel side here does the whole locking operation:1920* if there are waiters then it will block, it does PI, etc. (Due to1921* races the kernel might see a 0 value of the futex too.)1922*/1923static int futex_lock_pi(u32 __user *uaddr, unsigned int flags, int detect,1924ktime_t *time, int trylock)1925{1926struct hrtimer_sleeper timeout, *to = NULL;1927struct futex_hash_bucket *hb;1928struct futex_q q = futex_q_init;1929int res, ret;19301931if (refill_pi_state_cache())1932return -ENOMEM;19331934if (time) {1935to = &timeout;1936hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,1937HRTIMER_MODE_ABS);1938hrtimer_init_sleeper(to, current);1939hrtimer_set_expires(&to->timer, *time);1940}19411942retry:1943ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key);1944if (unlikely(ret != 0))1945goto out;19461947retry_private:1948hb = queue_lock(&q);19491950ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);1951if (unlikely(ret)) {1952switch (ret) {1953case 1:1954/* We got the lock. */1955ret = 0;1956goto out_unlock_put_key;1957case -EFAULT:1958goto uaddr_faulted;1959case -EAGAIN:1960/*1961* Task is exiting and we just wait for the1962* exit to complete.1963*/1964queue_unlock(&q, hb);1965put_futex_key(&q.key);1966cond_resched();1967goto retry;1968default:1969goto out_unlock_put_key;1970}1971}19721973/*1974* Only actually queue now that the atomic ops are done:1975*/1976queue_me(&q, hb);19771978WARN_ON(!q.pi_state);1979/*1980* Block on the PI mutex:1981*/1982if (!trylock)1983ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);1984else {1985ret = rt_mutex_trylock(&q.pi_state->pi_mutex);1986/* Fixup the trylock return value: */1987ret = ret ? 0 : -EWOULDBLOCK;1988}19891990spin_lock(q.lock_ptr);1991/*1992* Fixup the pi_state owner and possibly acquire the lock if we1993* haven't already.1994*/1995res = fixup_owner(uaddr, &q, !ret);1996/*1997* If fixup_owner() returned an error, proprogate that. If it acquired1998* the lock, clear our -ETIMEDOUT or -EINTR.1999*/2000if (res)2001ret = (res < 0) ? res : 0;20022003/*2004* If fixup_owner() faulted and was unable to handle the fault, unlock2005* it and return the fault to userspace.2006*/2007if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))2008rt_mutex_unlock(&q.pi_state->pi_mutex);20092010/* Unqueue and drop the lock */2011unqueue_me_pi(&q);20122013goto out_put_key;20142015out_unlock_put_key:2016queue_unlock(&q, hb);20172018out_put_key:2019put_futex_key(&q.key);2020out:2021if (to)2022destroy_hrtimer_on_stack(&to->timer);2023return ret != -EINTR ? ret : -ERESTARTNOINTR;20242025uaddr_faulted:2026queue_unlock(&q, hb);20272028ret = fault_in_user_writeable(uaddr);2029if (ret)2030goto out_put_key;20312032if (!(flags & FLAGS_SHARED))2033goto retry_private;20342035put_futex_key(&q.key);2036goto retry;2037}20382039/*2040* Userspace attempted a TID -> 0 atomic transition, and failed.2041* This is the in-kernel slowpath: we look up the PI state (if any),2042* and do the rt-mutex unlock.2043*/2044static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)2045{2046struct futex_hash_bucket *hb;2047struct futex_q *this, *next;2048struct plist_head *head;2049union futex_key key = FUTEX_KEY_INIT;2050u32 uval, vpid = task_pid_vnr(current);2051int ret;20522053retry:2054if (get_user(uval, uaddr))2055return -EFAULT;2056/*2057* We release only a lock we actually own:2058*/2059if ((uval & FUTEX_TID_MASK) != vpid)2060return -EPERM;20612062ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key);2063if (unlikely(ret != 0))2064goto out;20652066hb = hash_futex(&key);2067spin_lock(&hb->lock);20682069/*2070* To avoid races, try to do the TID -> 0 atomic transition2071* again. If it succeeds then we can return without waking2072* anyone else up:2073*/2074if (!(uval & FUTEX_OWNER_DIED) &&2075cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0))2076goto pi_faulted;2077/*2078* Rare case: we managed to release the lock atomically,2079* no need to wake anyone else up:2080*/2081if (unlikely(uval == vpid))2082goto out_unlock;20832084/*2085* Ok, other tasks may need to be woken up - check waiters2086* and do the wakeup if necessary:2087*/2088head = &hb->chain;20892090plist_for_each_entry_safe(this, next, head, list) {2091if (!match_futex (&this->key, &key))2092continue;2093ret = wake_futex_pi(uaddr, uval, this);2094/*2095* The atomic access to the futex value2096* generated a pagefault, so retry the2097* user-access and the wakeup:2098*/2099if (ret == -EFAULT)2100goto pi_faulted;2101goto out_unlock;2102}2103/*2104* No waiters - kernel unlocks the futex:2105*/2106if (!(uval & FUTEX_OWNER_DIED)) {2107ret = unlock_futex_pi(uaddr, uval);2108if (ret == -EFAULT)2109goto pi_faulted;2110}21112112out_unlock:2113spin_unlock(&hb->lock);2114put_futex_key(&key);21152116out:2117return ret;21182119pi_faulted:2120spin_unlock(&hb->lock);2121put_futex_key(&key);21222123ret = fault_in_user_writeable(uaddr);2124if (!ret)2125goto retry;21262127return ret;2128}21292130/**2131* handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex2132* @hb: the hash_bucket futex_q was original enqueued on2133* @q: the futex_q woken while waiting to be requeued2134* @key2: the futex_key of the requeue target futex2135* @timeout: the timeout associated with the wait (NULL if none)2136*2137* Detect if the task was woken on the initial futex as opposed to the requeue2138* target futex. If so, determine if it was a timeout or a signal that caused2139* the wakeup and return the appropriate error code to the caller. Must be2140* called with the hb lock held.2141*2142* Returns2143* 0 - no early wakeup detected2144* <0 - -ETIMEDOUT or -ERESTARTNOINTR2145*/2146static inline2147int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,2148struct futex_q *q, union futex_key *key2,2149struct hrtimer_sleeper *timeout)2150{2151int ret = 0;21522153/*2154* With the hb lock held, we avoid races while we process the wakeup.2155* We only need to hold hb (and not hb2) to ensure atomicity as the2156* wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.2157* It can't be requeued from uaddr2 to something else since we don't2158* support a PI aware source futex for requeue.2159*/2160if (!match_futex(&q->key, key2)) {2161WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));2162/*2163* We were woken prior to requeue by a timeout or a signal.2164* Unqueue the futex_q and determine which it was.2165*/2166plist_del(&q->list, &hb->chain);21672168/* Handle spurious wakeups gracefully */2169ret = -EWOULDBLOCK;2170if (timeout && !timeout->task)2171ret = -ETIMEDOUT;2172else if (signal_pending(current))2173ret = -ERESTARTNOINTR;2174}2175return ret;2176}21772178/**2179* futex_wait_requeue_pi() - Wait on uaddr and take uaddr22180* @uaddr: the futex we initially wait on (non-pi)2181* @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be2182* the same type, no requeueing from private to shared, etc.2183* @val: the expected value of uaddr2184* @abs_time: absolute timeout2185* @bitset: 32 bit wakeup bitset set by userspace, defaults to all2186* @clockrt: whether to use CLOCK_REALTIME (1) or CLOCK_MONOTONIC (0)2187* @uaddr2: the pi futex we will take prior to returning to user-space2188*2189* The caller will wait on uaddr and will be requeued by futex_requeue() to2190* uaddr2 which must be PI aware. Normal wakeup will wake on uaddr2 and2191* complete the acquisition of the rt_mutex prior to returning to userspace.2192* This ensures the rt_mutex maintains an owner when it has waiters; without2193* one, the pi logic wouldn't know which task to boost/deboost, if there was a2194* need to.2195*2196* We call schedule in futex_wait_queue_me() when we enqueue and return there2197* via the following:2198* 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()2199* 2) wakeup on uaddr2 after a requeue2200* 3) signal2201* 4) timeout2202*2203* If 3, cleanup and return -ERESTARTNOINTR.2204*2205* If 2, we may then block on trying to take the rt_mutex and return via:2206* 5) successful lock2207* 6) signal2208* 7) timeout2209* 8) other lock acquisition failure2210*2211* If 6, return -EWOULDBLOCK (restarting the syscall would do the same).2212*2213* If 4 or 7, we cleanup and return with -ETIMEDOUT.2214*2215* Returns:2216* 0 - On success2217* <0 - On error2218*/2219static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,2220u32 val, ktime_t *abs_time, u32 bitset,2221u32 __user *uaddr2)2222{2223struct hrtimer_sleeper timeout, *to = NULL;2224struct rt_mutex_waiter rt_waiter;2225struct rt_mutex *pi_mutex = NULL;2226struct futex_hash_bucket *hb;2227union futex_key key2 = FUTEX_KEY_INIT;2228struct futex_q q = futex_q_init;2229int res, ret;22302231if (!bitset)2232return -EINVAL;22332234if (abs_time) {2235to = &timeout;2236hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?2237CLOCK_REALTIME : CLOCK_MONOTONIC,2238HRTIMER_MODE_ABS);2239hrtimer_init_sleeper(to, current);2240hrtimer_set_expires_range_ns(&to->timer, *abs_time,2241current->timer_slack_ns);2242}22432244/*2245* The waiter is allocated on our stack, manipulated by the requeue2246* code while we sleep on uaddr.2247*/2248debug_rt_mutex_init_waiter(&rt_waiter);2249rt_waiter.task = NULL;22502251ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2);2252if (unlikely(ret != 0))2253goto out;22542255q.bitset = bitset;2256q.rt_waiter = &rt_waiter;2257q.requeue_pi_key = &key2;22582259/*2260* Prepare to wait on uaddr. On success, increments q.key (key1) ref2261* count.2262*/2263ret = futex_wait_setup(uaddr, val, flags, &q, &hb);2264if (ret)2265goto out_key2;22662267/* Queue the futex_q, drop the hb lock, wait for wakeup. */2268futex_wait_queue_me(hb, &q, to);22692270spin_lock(&hb->lock);2271ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);2272spin_unlock(&hb->lock);2273if (ret)2274goto out_put_keys;22752276/*2277* In order for us to be here, we know our q.key == key2, and since2278* we took the hb->lock above, we also know that futex_requeue() has2279* completed and we no longer have to concern ourselves with a wakeup2280* race with the atomic proxy lock acquisition by the requeue code. The2281* futex_requeue dropped our key1 reference and incremented our key22282* reference count.2283*/22842285/* Check if the requeue code acquired the second futex for us. */2286if (!q.rt_waiter) {2287/*2288* Got the lock. We might not be the anticipated owner if we2289* did a lock-steal - fix up the PI-state in that case.2290*/2291if (q.pi_state && (q.pi_state->owner != current)) {2292spin_lock(q.lock_ptr);2293ret = fixup_pi_state_owner(uaddr2, &q, current);2294spin_unlock(q.lock_ptr);2295}2296} else {2297/*2298* We have been woken up by futex_unlock_pi(), a timeout, or a2299* signal. futex_unlock_pi() will not destroy the lock_ptr nor2300* the pi_state.2301*/2302WARN_ON(!&q.pi_state);2303pi_mutex = &q.pi_state->pi_mutex;2304ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);2305debug_rt_mutex_free_waiter(&rt_waiter);23062307spin_lock(q.lock_ptr);2308/*2309* Fixup the pi_state owner and possibly acquire the lock if we2310* haven't already.2311*/2312res = fixup_owner(uaddr2, &q, !ret);2313/*2314* If fixup_owner() returned an error, proprogate that. If it2315* acquired the lock, clear -ETIMEDOUT or -EINTR.2316*/2317if (res)2318ret = (res < 0) ? res : 0;23192320/* Unqueue and drop the lock. */2321unqueue_me_pi(&q);2322}23232324/*2325* If fixup_pi_state_owner() faulted and was unable to handle the2326* fault, unlock the rt_mutex and return the fault to userspace.2327*/2328if (ret == -EFAULT) {2329if (rt_mutex_owner(pi_mutex) == current)2330rt_mutex_unlock(pi_mutex);2331} else if (ret == -EINTR) {2332/*2333* We've already been requeued, but cannot restart by calling2334* futex_lock_pi() directly. We could restart this syscall, but2335* it would detect that the user space "val" changed and return2336* -EWOULDBLOCK. Save the overhead of the restart and return2337* -EWOULDBLOCK directly.2338*/2339ret = -EWOULDBLOCK;2340}23412342out_put_keys:2343put_futex_key(&q.key);2344out_key2:2345put_futex_key(&key2);23462347out:2348if (to) {2349hrtimer_cancel(&to->timer);2350destroy_hrtimer_on_stack(&to->timer);2351}2352return ret;2353}23542355/*2356* Support for robust futexes: the kernel cleans up held futexes at2357* thread exit time.2358*2359* Implementation: user-space maintains a per-thread list of locks it2360* is holding. Upon do_exit(), the kernel carefully walks this list,2361* and marks all locks that are owned by this thread with the2362* FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is2363* always manipulated with the lock held, so the list is private and2364* per-thread. Userspace also maintains a per-thread 'list_op_pending'2365* field, to allow the kernel to clean up if the thread dies after2366* acquiring the lock, but just before it could have added itself to2367* the list. There can only be one such pending lock.2368*/23692370/**2371* sys_set_robust_list() - Set the robust-futex list head of a task2372* @head: pointer to the list-head2373* @len: length of the list-head, as userspace expects2374*/2375SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,2376size_t, len)2377{2378if (!futex_cmpxchg_enabled)2379return -ENOSYS;2380/*2381* The kernel knows only one size for now:2382*/2383if (unlikely(len != sizeof(*head)))2384return -EINVAL;23852386current->robust_list = head;23872388return 0;2389}23902391/**2392* sys_get_robust_list() - Get the robust-futex list head of a task2393* @pid: pid of the process [zero for current task]2394* @head_ptr: pointer to a list-head pointer, the kernel fills it in2395* @len_ptr: pointer to a length field, the kernel fills in the header size2396*/2397SYSCALL_DEFINE3(get_robust_list, int, pid,2398struct robust_list_head __user * __user *, head_ptr,2399size_t __user *, len_ptr)2400{2401struct robust_list_head __user *head;2402unsigned long ret;2403const struct cred *cred = current_cred(), *pcred;24042405if (!futex_cmpxchg_enabled)2406return -ENOSYS;24072408if (!pid)2409head = current->robust_list;2410else {2411struct task_struct *p;24122413ret = -ESRCH;2414rcu_read_lock();2415p = find_task_by_vpid(pid);2416if (!p)2417goto err_unlock;2418ret = -EPERM;2419pcred = __task_cred(p);2420/* If victim is in different user_ns, then uids are not2421comparable, so we must have CAP_SYS_PTRACE */2422if (cred->user->user_ns != pcred->user->user_ns) {2423if (!ns_capable(pcred->user->user_ns, CAP_SYS_PTRACE))2424goto err_unlock;2425goto ok;2426}2427/* If victim is in same user_ns, then uids are comparable */2428if (cred->euid != pcred->euid &&2429cred->euid != pcred->uid &&2430!ns_capable(pcred->user->user_ns, CAP_SYS_PTRACE))2431goto err_unlock;2432ok:2433head = p->robust_list;2434rcu_read_unlock();2435}24362437if (put_user(sizeof(*head), len_ptr))2438return -EFAULT;2439return put_user(head, head_ptr);24402441err_unlock:2442rcu_read_unlock();24432444return ret;2445}24462447/*2448* Process a futex-list entry, check whether it's owned by the2449* dying task, and do notification if so:2450*/2451int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)2452{2453u32 uval, nval, mval;24542455retry:2456if (get_user(uval, uaddr))2457return -1;24582459if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {2460/*2461* Ok, this dying thread is truly holding a futex2462* of interest. Set the OWNER_DIED bit atomically2463* via cmpxchg, and if the value had FUTEX_WAITERS2464* set, wake up a waiter (if any). (We have to do a2465* futex_wake() even if OWNER_DIED is already set -2466* to handle the rare but possible case of recursive2467* thread-death.) The rest of the cleanup is done in2468* userspace.2469*/2470mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;2471/*2472* We are not holding a lock here, but we want to have2473* the pagefault_disable/enable() protection because2474* we want to handle the fault gracefully. If the2475* access fails we try to fault in the futex with R/W2476* verification via get_user_pages. get_user() above2477* does not guarantee R/W access. If that fails we2478* give up and leave the futex locked.2479*/2480if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {2481if (fault_in_user_writeable(uaddr))2482return -1;2483goto retry;2484}2485if (nval != uval)2486goto retry;24872488/*2489* Wake robust non-PI futexes here. The wakeup of2490* PI futexes happens in exit_pi_state():2491*/2492if (!pi && (uval & FUTEX_WAITERS))2493futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);2494}2495return 0;2496}24972498/*2499* Fetch a robust-list pointer. Bit 0 signals PI futexes:2500*/2501static inline int fetch_robust_entry(struct robust_list __user **entry,2502struct robust_list __user * __user *head,2503unsigned int *pi)2504{2505unsigned long uentry;25062507if (get_user(uentry, (unsigned long __user *)head))2508return -EFAULT;25092510*entry = (void __user *)(uentry & ~1UL);2511*pi = uentry & 1;25122513return 0;2514}25152516/*2517* Walk curr->robust_list (very carefully, it's a userspace list!)2518* and mark any locks found there dead, and notify any waiters.2519*2520* We silently return on any sign of list-walking problem.2521*/2522void exit_robust_list(struct task_struct *curr)2523{2524struct robust_list_head __user *head = curr->robust_list;2525struct robust_list __user *entry, *next_entry, *pending;2526unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;2527unsigned int uninitialized_var(next_pi);2528unsigned long futex_offset;2529int rc;25302531if (!futex_cmpxchg_enabled)2532return;25332534/*2535* Fetch the list head (which was registered earlier, via2536* sys_set_robust_list()):2537*/2538if (fetch_robust_entry(&entry, &head->list.next, &pi))2539return;2540/*2541* Fetch the relative futex offset:2542*/2543if (get_user(futex_offset, &head->futex_offset))2544return;2545/*2546* Fetch any possibly pending lock-add first, and handle it2547* if it exists:2548*/2549if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))2550return;25512552next_entry = NULL; /* avoid warning with gcc */2553while (entry != &head->list) {2554/*2555* Fetch the next entry in the list before calling2556* handle_futex_death:2557*/2558rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);2559/*2560* A pending lock might already be on the list, so2561* don't process it twice:2562*/2563if (entry != pending)2564if (handle_futex_death((void __user *)entry + futex_offset,2565curr, pi))2566return;2567if (rc)2568return;2569entry = next_entry;2570pi = next_pi;2571/*2572* Avoid excessively long or circular lists:2573*/2574if (!--limit)2575break;25762577cond_resched();2578}25792580if (pending)2581handle_futex_death((void __user *)pending + futex_offset,2582curr, pip);2583}25842585long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,2586u32 __user *uaddr2, u32 val2, u32 val3)2587{2588int ret = -ENOSYS, cmd = op & FUTEX_CMD_MASK;2589unsigned int flags = 0;25902591if (!(op & FUTEX_PRIVATE_FLAG))2592flags |= FLAGS_SHARED;25932594if (op & FUTEX_CLOCK_REALTIME) {2595flags |= FLAGS_CLOCKRT;2596if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)2597return -ENOSYS;2598}25992600switch (cmd) {2601case FUTEX_WAIT:2602val3 = FUTEX_BITSET_MATCH_ANY;2603case FUTEX_WAIT_BITSET:2604ret = futex_wait(uaddr, flags, val, timeout, val3);2605break;2606case FUTEX_WAKE:2607val3 = FUTEX_BITSET_MATCH_ANY;2608case FUTEX_WAKE_BITSET:2609ret = futex_wake(uaddr, flags, val, val3);2610break;2611case FUTEX_REQUEUE:2612ret = futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);2613break;2614case FUTEX_CMP_REQUEUE:2615ret = futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);2616break;2617case FUTEX_WAKE_OP:2618ret = futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);2619break;2620case FUTEX_LOCK_PI:2621if (futex_cmpxchg_enabled)2622ret = futex_lock_pi(uaddr, flags, val, timeout, 0);2623break;2624case FUTEX_UNLOCK_PI:2625if (futex_cmpxchg_enabled)2626ret = futex_unlock_pi(uaddr, flags);2627break;2628case FUTEX_TRYLOCK_PI:2629if (futex_cmpxchg_enabled)2630ret = futex_lock_pi(uaddr, flags, 0, timeout, 1);2631break;2632case FUTEX_WAIT_REQUEUE_PI:2633val3 = FUTEX_BITSET_MATCH_ANY;2634ret = futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,2635uaddr2);2636break;2637case FUTEX_CMP_REQUEUE_PI:2638ret = futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);2639break;2640default:2641ret = -ENOSYS;2642}2643return ret;2644}264526462647SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,2648struct timespec __user *, utime, u32 __user *, uaddr2,2649u32, val3)2650{2651struct timespec ts;2652ktime_t t, *tp = NULL;2653u32 val2 = 0;2654int cmd = op & FUTEX_CMD_MASK;26552656if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||2657cmd == FUTEX_WAIT_BITSET ||2658cmd == FUTEX_WAIT_REQUEUE_PI)) {2659if (copy_from_user(&ts, utime, sizeof(ts)) != 0)2660return -EFAULT;2661if (!timespec_valid(&ts))2662return -EINVAL;26632664t = timespec_to_ktime(ts);2665if (cmd == FUTEX_WAIT)2666t = ktime_add_safe(ktime_get(), t);2667tp = &t;2668}2669/*2670* requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.2671* number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.2672*/2673if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||2674cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)2675val2 = (u32) (unsigned long) utime;26762677return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);2678}26792680static int __init futex_init(void)2681{2682u32 curval;2683int i;26842685/*2686* This will fail and we want it. Some arch implementations do2687* runtime detection of the futex_atomic_cmpxchg_inatomic()2688* functionality. We want to know that before we call in any2689* of the complex code paths. Also we want to prevent2690* registration of robust lists in that case. NULL is2691* guaranteed to fault and we get -EFAULT on functional2692* implementation, the non-functional ones will return2693* -ENOSYS.2694*/2695if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)2696futex_cmpxchg_enabled = 1;26972698for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {2699plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);2700spin_lock_init(&futex_queues[i].lock);2701}27022703return 0;2704}2705__initcall(futex_init);270627072708