// SPDX-License-Identifier: GPL-2.0-or-later1/*2* Fast Userspace Mutexes (which I call "Futexes!").3* (C) Rusty Russell, IBM 20024*5* Generalized futexes, futex requeueing, misc fixes by Ingo Molnar6* (C) Copyright 2003 Red Hat Inc, All Rights Reserved7*8* Removed page pinning, fix privately mapped COW pages and other cleanups9* (C) Copyright 2003, 2004 Jamie Lokier10*11* Robust futex support started by Ingo Molnar12* (C) Copyright 2006 Red Hat Inc, All Rights Reserved13* Thanks to Thomas Gleixner for suggestions, analysis and fixes.14*15* PI-futex support started by Ingo Molnar and Thomas Gleixner16* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <[email protected]>17* Copyright (C) 2006 Timesys Corp., Thomas Gleixner <[email protected]>18*19* PRIVATE futexes by Eric Dumazet20* Copyright (C) 2007 Eric Dumazet <[email protected]>21*22* Requeue-PI support by Darren Hart <[email protected]>23* Copyright (C) IBM Corporation, 200924* Thanks to Thomas Gleixner for conceptual design and careful reviews.25*26* Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly27* enough at me, Linus for the original (flawed) idea, Matthew28* Kirkwood for proof-of-concept implementation.29*30* "The futexes are also cursed."31* "But they come in a choice of three flavours!"32*/33#include <linux/compat.h>34#include <linux/jhash.h>35#include <linux/pagemap.h>36#include <linux/debugfs.h>37#include <linux/plist.h>38#include <linux/gfp.h>39#include <linux/vmalloc.h>40#include <linux/memblock.h>41#include <linux/fault-inject.h>42#include <linux/slab.h>43#include <linux/prctl.h>44#include <linux/mempolicy.h>45#include <linux/mmap_lock.h>4647#include "futex.h"48#include "../locking/rtmutex_common.h"4950/*51* The base of the bucket array and its size are always used together52* (after initialization only in futex_hash()), so ensure that they53* reside in the same cacheline.54*/55static struct {56unsigned long hashmask;57unsigned int hashshift;58struct futex_hash_bucket *queues[MAX_NUMNODES];59} __futex_data __read_mostly __aligned(2*sizeof(long));6061#define futex_hashmask (__futex_data.hashmask)62#define futex_hashshift (__futex_data.hashshift)63#define futex_queues (__futex_data.queues)6465struct futex_private_hash {66int state;67unsigned int hash_mask;68struct rcu_head rcu;69void *mm;70bool custom;71struct futex_hash_bucket queues[];72};7374/*75* Fault injections for futexes.76*/77#ifdef CONFIG_FAIL_FUTEX7879static struct {80struct fault_attr attr;8182bool ignore_private;83} fail_futex = {84.attr = FAULT_ATTR_INITIALIZER,85.ignore_private = false,86};8788static int __init setup_fail_futex(char *str)89{90return setup_fault_attr(&fail_futex.attr, str);91}92__setup("fail_futex=", setup_fail_futex);9394bool should_fail_futex(bool fshared)95{96if (fail_futex.ignore_private && !fshared)97return false;9899return should_fail(&fail_futex.attr, 1);100}101102#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS103104static int __init fail_futex_debugfs(void)105{106umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;107struct dentry *dir;108109dir = fault_create_debugfs_attr("fail_futex", NULL,110&fail_futex.attr);111if (IS_ERR(dir))112return PTR_ERR(dir);113114debugfs_create_bool("ignore-private", mode, dir,115&fail_futex.ignore_private);116return 0;117}118119late_initcall(fail_futex_debugfs);120121#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */122123#endif /* CONFIG_FAIL_FUTEX */124125static struct futex_hash_bucket *126__futex_hash(union futex_key *key, struct futex_private_hash *fph);127128#ifdef CONFIG_FUTEX_PRIVATE_HASH129static bool futex_ref_get(struct futex_private_hash *fph);130static bool futex_ref_put(struct futex_private_hash *fph);131static bool futex_ref_is_dead(struct futex_private_hash *fph);132133enum { FR_PERCPU = 0, FR_ATOMIC };134135static inline bool futex_key_is_private(union futex_key *key)136{137/*138* Relies on get_futex_key() to set either bit for shared139* futexes -- see comment with union futex_key.140*/141return !(key->both.offset & (FUT_OFF_INODE | FUT_OFF_MMSHARED));142}143144static bool futex_private_hash_get(struct futex_private_hash *fph)145{146return futex_ref_get(fph);147}148149void futex_private_hash_put(struct futex_private_hash *fph)150{151if (futex_ref_put(fph))152wake_up_var(fph->mm);153}154155/**156* futex_hash_get - Get an additional reference for the local hash.157* @hb: ptr to the private local hash.158*159* Obtain an additional reference for the already obtained hash bucket. The160* caller must already own an reference.161*/162void futex_hash_get(struct futex_hash_bucket *hb)163{164struct futex_private_hash *fph = hb->priv;165166if (!fph)167return;168WARN_ON_ONCE(!futex_private_hash_get(fph));169}170171void futex_hash_put(struct futex_hash_bucket *hb)172{173struct futex_private_hash *fph = hb->priv;174175if (!fph)176return;177futex_private_hash_put(fph);178}179180static struct futex_hash_bucket *181__futex_hash_private(union futex_key *key, struct futex_private_hash *fph)182{183u32 hash;184185if (!futex_key_is_private(key))186return NULL;187188if (!fph)189fph = rcu_dereference(key->private.mm->futex_phash);190if (!fph || !fph->hash_mask)191return NULL;192193hash = jhash2((void *)&key->private.address,194sizeof(key->private.address) / 4,195key->both.offset);196return &fph->queues[hash & fph->hash_mask];197}198199static void futex_rehash_private(struct futex_private_hash *old,200struct futex_private_hash *new)201{202struct futex_hash_bucket *hb_old, *hb_new;203unsigned int slots = old->hash_mask + 1;204unsigned int i;205206for (i = 0; i < slots; i++) {207struct futex_q *this, *tmp;208209hb_old = &old->queues[i];210211spin_lock(&hb_old->lock);212plist_for_each_entry_safe(this, tmp, &hb_old->chain, list) {213214plist_del(&this->list, &hb_old->chain);215futex_hb_waiters_dec(hb_old);216217WARN_ON_ONCE(this->lock_ptr != &hb_old->lock);218219hb_new = __futex_hash(&this->key, new);220futex_hb_waiters_inc(hb_new);221/*222* The new pointer isn't published yet but an already223* moved user can be unqueued due to timeout or signal.224*/225spin_lock_nested(&hb_new->lock, SINGLE_DEPTH_NESTING);226plist_add(&this->list, &hb_new->chain);227this->lock_ptr = &hb_new->lock;228spin_unlock(&hb_new->lock);229}230spin_unlock(&hb_old->lock);231}232}233234static bool __futex_pivot_hash(struct mm_struct *mm,235struct futex_private_hash *new)236{237struct futex_private_hash *fph;238239WARN_ON_ONCE(mm->futex_phash_new);240241fph = rcu_dereference_protected(mm->futex_phash,242lockdep_is_held(&mm->futex_hash_lock));243if (fph) {244if (!futex_ref_is_dead(fph)) {245mm->futex_phash_new = new;246return false;247}248249futex_rehash_private(fph, new);250}251new->state = FR_PERCPU;252scoped_guard(rcu) {253mm->futex_batches = get_state_synchronize_rcu();254rcu_assign_pointer(mm->futex_phash, new);255}256kvfree_rcu(fph, rcu);257return true;258}259260static void futex_pivot_hash(struct mm_struct *mm)261{262scoped_guard(mutex, &mm->futex_hash_lock) {263struct futex_private_hash *fph;264265fph = mm->futex_phash_new;266if (fph) {267mm->futex_phash_new = NULL;268__futex_pivot_hash(mm, fph);269}270}271}272273struct futex_private_hash *futex_private_hash(void)274{275struct mm_struct *mm = current->mm;276/*277* Ideally we don't loop. If there is a replacement in progress278* then a new private hash is already prepared and a reference can't be279* obtained once the last user dropped it's.280* In that case we block on mm_struct::futex_hash_lock and either have281* to perform the replacement or wait while someone else is doing the282* job. Eitherway, on the second iteration we acquire a reference on the283* new private hash or loop again because a new replacement has been284* requested.285*/286again:287scoped_guard(rcu) {288struct futex_private_hash *fph;289290fph = rcu_dereference(mm->futex_phash);291if (!fph)292return NULL;293294if (futex_private_hash_get(fph))295return fph;296}297futex_pivot_hash(mm);298goto again;299}300301struct futex_hash_bucket *futex_hash(union futex_key *key)302{303struct futex_private_hash *fph;304struct futex_hash_bucket *hb;305306again:307scoped_guard(rcu) {308hb = __futex_hash(key, NULL);309fph = hb->priv;310311if (!fph || futex_private_hash_get(fph))312return hb;313}314futex_pivot_hash(key->private.mm);315goto again;316}317318#else /* !CONFIG_FUTEX_PRIVATE_HASH */319320static struct futex_hash_bucket *321__futex_hash_private(union futex_key *key, struct futex_private_hash *fph)322{323return NULL;324}325326struct futex_hash_bucket *futex_hash(union futex_key *key)327{328return __futex_hash(key, NULL);329}330331#endif /* CONFIG_FUTEX_PRIVATE_HASH */332333#ifdef CONFIG_FUTEX_MPOL334335static int __futex_key_to_node(struct mm_struct *mm, unsigned long addr)336{337struct vm_area_struct *vma = vma_lookup(mm, addr);338struct mempolicy *mpol;339int node = FUTEX_NO_NODE;340341if (!vma)342return FUTEX_NO_NODE;343344mpol = vma_policy(vma);345if (!mpol)346return FUTEX_NO_NODE;347348switch (mpol->mode) {349case MPOL_PREFERRED:350node = first_node(mpol->nodes);351break;352case MPOL_PREFERRED_MANY:353case MPOL_BIND:354if (mpol->home_node != NUMA_NO_NODE)355node = mpol->home_node;356break;357default:358break;359}360361return node;362}363364static int futex_key_to_node_opt(struct mm_struct *mm, unsigned long addr)365{366int seq, node;367368guard(rcu)();369370if (!mmap_lock_speculate_try_begin(mm, &seq))371return -EBUSY;372373node = __futex_key_to_node(mm, addr);374375if (mmap_lock_speculate_retry(mm, seq))376return -EAGAIN;377378return node;379}380381static int futex_mpol(struct mm_struct *mm, unsigned long addr)382{383int node;384385node = futex_key_to_node_opt(mm, addr);386if (node >= FUTEX_NO_NODE)387return node;388389guard(mmap_read_lock)(mm);390return __futex_key_to_node(mm, addr);391}392393#else /* !CONFIG_FUTEX_MPOL */394395static int futex_mpol(struct mm_struct *mm, unsigned long addr)396{397return FUTEX_NO_NODE;398}399400#endif /* CONFIG_FUTEX_MPOL */401402/**403* __futex_hash - Return the hash bucket404* @key: Pointer to the futex key for which the hash is calculated405* @fph: Pointer to private hash if known406*407* We hash on the keys returned from get_futex_key (see below) and return the408* corresponding hash bucket.409* If the FUTEX is PROCESS_PRIVATE then a per-process hash bucket (from the410* private hash) is returned if existing. Otherwise a hash bucket from the411* global hash is returned.412*/413static struct futex_hash_bucket *414__futex_hash(union futex_key *key, struct futex_private_hash *fph)415{416int node = key->both.node;417u32 hash;418419if (node == FUTEX_NO_NODE) {420struct futex_hash_bucket *hb;421422hb = __futex_hash_private(key, fph);423if (hb)424return hb;425}426427hash = jhash2((u32 *)key,428offsetof(typeof(*key), both.offset) / sizeof(u32),429key->both.offset);430431if (node == FUTEX_NO_NODE) {432/*433* In case of !FLAGS_NUMA, use some unused hash bits to pick a434* node -- this ensures regular futexes are interleaved across435* the nodes and avoids having to allocate multiple436* hash-tables.437*438* NOTE: this isn't perfectly uniform, but it is fast and439* handles sparse node masks.440*/441node = (hash >> futex_hashshift) % nr_node_ids;442if (!node_possible(node)) {443node = find_next_bit_wrap(node_possible_map.bits,444nr_node_ids, node);445}446}447448return &futex_queues[node][hash & futex_hashmask];449}450451/**452* futex_setup_timer - set up the sleeping hrtimer.453* @time: ptr to the given timeout value454* @timeout: the hrtimer_sleeper structure to be set up455* @flags: futex flags456* @range_ns: optional range in ns457*458* Return: Initialized hrtimer_sleeper structure or NULL if no timeout459* value given460*/461struct hrtimer_sleeper *462futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,463int flags, u64 range_ns)464{465if (!time)466return NULL;467468hrtimer_setup_sleeper_on_stack(timeout,469(flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC,470HRTIMER_MODE_ABS);471/*472* If range_ns is 0, calling hrtimer_set_expires_range_ns() is473* effectively the same as calling hrtimer_set_expires().474*/475hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);476477return timeout;478}479480/*481* Generate a machine wide unique identifier for this inode.482*483* This relies on u64 not wrapping in the life-time of the machine; which with484* 1ns resolution means almost 585 years.485*486* This further relies on the fact that a well formed program will not unmap487* the file while it has a (shared) futex waiting on it. This mapping will have488* a file reference which pins the mount and inode.489*490* If for some reason an inode gets evicted and read back in again, it will get491* a new sequence number and will _NOT_ match, even though it is the exact same492* file.493*494* It is important that futex_match() will never have a false-positive, esp.495* for PI futexes that can mess up the state. The above argues that false-negatives496* are only possible for malformed programs.497*/498static u64 get_inode_sequence_number(struct inode *inode)499{500static atomic64_t i_seq;501u64 old;502503/* Does the inode already have a sequence number? */504old = atomic64_read(&inode->i_sequence);505if (likely(old))506return old;507508for (;;) {509u64 new = atomic64_inc_return(&i_seq);510if (WARN_ON_ONCE(!new))511continue;512513old = 0;514if (!atomic64_try_cmpxchg_relaxed(&inode->i_sequence, &old, new))515return old;516return new;517}518}519520/**521* get_futex_key() - Get parameters which are the keys for a futex522* @uaddr: virtual address of the futex523* @flags: FLAGS_*524* @key: address where result is stored.525* @rw: mapping needs to be read/write (values: FUTEX_READ,526* FUTEX_WRITE)527*528* Return: a negative error code or 0529*530* The key words are stored in @key on success.531*532* For shared mappings (when @fshared), the key is:533*534* ( inode->i_sequence, page offset within mapping, offset_within_page )535*536* [ also see get_inode_sequence_number() ]537*538* For private mappings (or when !@fshared), the key is:539*540* ( current->mm, address, 0 )541*542* This allows (cross process, where applicable) identification of the futex543* without keeping the page pinned for the duration of the FUTEX_WAIT.544*545* lock_page() might sleep, the caller should not hold a spinlock.546*/547int get_futex_key(u32 __user *uaddr, unsigned int flags, union futex_key *key,548enum futex_access rw)549{550unsigned long address = (unsigned long)uaddr;551struct mm_struct *mm = current->mm;552struct page *page;553struct folio *folio;554struct address_space *mapping;555int node, err, size, ro = 0;556bool node_updated = false;557bool fshared;558559fshared = flags & FLAGS_SHARED;560size = futex_size(flags);561if (flags & FLAGS_NUMA)562size *= 2;563564/*565* The futex address must be "naturally" aligned.566*/567key->both.offset = address % PAGE_SIZE;568if (unlikely((address % size) != 0))569return -EINVAL;570address -= key->both.offset;571572if (unlikely(!access_ok(uaddr, size)))573return -EFAULT;574575if (unlikely(should_fail_futex(fshared)))576return -EFAULT;577578node = FUTEX_NO_NODE;579580if (flags & FLAGS_NUMA) {581u32 __user *naddr = (void *)uaddr + size / 2;582583if (futex_get_value(&node, naddr))584return -EFAULT;585586if ((node != FUTEX_NO_NODE) &&587((unsigned int)node >= MAX_NUMNODES || !node_possible(node)))588return -EINVAL;589}590591if (node == FUTEX_NO_NODE && (flags & FLAGS_MPOL)) {592node = futex_mpol(mm, address);593node_updated = true;594}595596if (flags & FLAGS_NUMA) {597u32 __user *naddr = (void *)uaddr + size / 2;598599if (node == FUTEX_NO_NODE) {600node = numa_node_id();601node_updated = true;602}603if (node_updated && futex_put_value(node, naddr))604return -EFAULT;605}606607key->both.node = node;608609/*610* PROCESS_PRIVATE futexes are fast.611* As the mm cannot disappear under us and the 'key' only needs612* virtual address, we dont even have to find the underlying vma.613* Note : We do have to check 'uaddr' is a valid user address,614* but access_ok() should be faster than find_vma()615*/616if (!fshared) {617/*618* On no-MMU, shared futexes are treated as private, therefore619* we must not include the current process in the key. Since620* there is only one address space, the address is a unique key621* on its own.622*/623if (IS_ENABLED(CONFIG_MMU))624key->private.mm = mm;625else626key->private.mm = NULL;627628key->private.address = address;629return 0;630}631632again:633/* Ignore any VERIFY_READ mapping (futex common case) */634if (unlikely(should_fail_futex(true)))635return -EFAULT;636637err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);638/*639* If write access is not required (eg. FUTEX_WAIT), try640* and get read-only access.641*/642if (err == -EFAULT && rw == FUTEX_READ) {643err = get_user_pages_fast(address, 1, 0, &page);644ro = 1;645}646if (err < 0)647return err;648else649err = 0;650651/*652* The treatment of mapping from this point on is critical. The folio653* lock protects many things but in this context the folio lock654* stabilizes mapping, prevents inode freeing in the shared655* file-backed region case and guards against movement to swap cache.656*657* Strictly speaking the folio lock is not needed in all cases being658* considered here and folio lock forces unnecessarily serialization.659* From this point on, mapping will be re-verified if necessary and660* folio lock will be acquired only if it is unavoidable661*662* Mapping checks require the folio so it is looked up now. For663* anonymous pages, it does not matter if the folio is split664* in the future as the key is based on the address. For665* filesystem-backed pages, the precise page is required as the666* index of the page determines the key.667*/668folio = page_folio(page);669mapping = READ_ONCE(folio->mapping);670671/*672* If folio->mapping is NULL, then it cannot be an anonymous673* page; but it might be the ZERO_PAGE or in the gate area or674* in a special mapping (all cases which we are happy to fail);675* or it may have been a good file page when get_user_pages_fast676* found it, but truncated or holepunched or subjected to677* invalidate_complete_page2 before we got the folio lock (also678* cases which we are happy to fail). And we hold a reference,679* so refcount care in invalidate_inode_page's remove_mapping680* prevents drop_caches from setting mapping to NULL beneath us.681*682* The case we do have to guard against is when memory pressure made683* shmem_writepage move it from filecache to swapcache beneath us:684* an unlikely race, but we do need to retry for folio->mapping.685*/686if (unlikely(!mapping)) {687int shmem_swizzled;688689/*690* Folio lock is required to identify which special case above691* applies. If this is really a shmem page then the folio lock692* will prevent unexpected transitions.693*/694folio_lock(folio);695shmem_swizzled = folio_test_swapcache(folio) || folio->mapping;696folio_unlock(folio);697folio_put(folio);698699if (shmem_swizzled)700goto again;701702return -EFAULT;703}704705/*706* Private mappings are handled in a simple way.707*708* If the futex key is stored in anonymous memory, then the associated709* object is the mm which is implicitly pinned by the calling process.710*711* NOTE: When userspace waits on a MAP_SHARED mapping, even if712* it's a read-only handle, it's expected that futexes attach to713* the object not the particular process.714*/715if (folio_test_anon(folio)) {716/*717* A RO anonymous page will never change and thus doesn't make718* sense for futex operations.719*/720if (unlikely(should_fail_futex(true)) || ro) {721err = -EFAULT;722goto out;723}724725key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */726key->private.mm = mm;727key->private.address = address;728729} else {730struct inode *inode;731732/*733* The associated futex object in this case is the inode and734* the folio->mapping must be traversed. Ordinarily this should735* be stabilised under folio lock but it's not strictly736* necessary in this case as we just want to pin the inode, not737* update i_pages or anything like that.738*739* The RCU read lock is taken as the inode is finally freed740* under RCU. If the mapping still matches expectations then the741* mapping->host can be safely accessed as being a valid inode.742*/743rcu_read_lock();744745if (READ_ONCE(folio->mapping) != mapping) {746rcu_read_unlock();747folio_put(folio);748749goto again;750}751752inode = READ_ONCE(mapping->host);753if (!inode) {754rcu_read_unlock();755folio_put(folio);756757goto again;758}759760key->both.offset |= FUT_OFF_INODE; /* inode-based key */761key->shared.i_seq = get_inode_sequence_number(inode);762key->shared.pgoff = page_pgoff(folio, page);763rcu_read_unlock();764}765766out:767folio_put(folio);768return err;769}770771/**772* fault_in_user_writeable() - Fault in user address and verify RW access773* @uaddr: pointer to faulting user space address774*775* Slow path to fixup the fault we just took in the atomic write776* access to @uaddr.777*778* We have no generic implementation of a non-destructive write to the779* user address. We know that we faulted in the atomic pagefault780* disabled section so we can as well avoid the #PF overhead by781* calling get_user_pages() right away.782*/783int fault_in_user_writeable(u32 __user *uaddr)784{785struct mm_struct *mm = current->mm;786int ret;787788mmap_read_lock(mm);789ret = fixup_user_fault(mm, (unsigned long)uaddr,790FAULT_FLAG_WRITE, NULL);791mmap_read_unlock(mm);792793return ret < 0 ? ret : 0;794}795796/**797* futex_top_waiter() - Return the highest priority waiter on a futex798* @hb: the hash bucket the futex_q's reside in799* @key: the futex key (to distinguish it from other futex futex_q's)800*801* Must be called with the hb lock held.802*/803struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key)804{805struct futex_q *this;806807plist_for_each_entry(this, &hb->chain, list) {808if (futex_match(&this->key, key))809return this;810}811return NULL;812}813814/**815* wait_for_owner_exiting - Block until the owner has exited816* @ret: owner's current futex lock status817* @exiting: Pointer to the exiting task818*819* Caller must hold a refcount on @exiting.820*/821void wait_for_owner_exiting(int ret, struct task_struct *exiting)822{823if (ret != -EBUSY) {824WARN_ON_ONCE(exiting);825return;826}827828if (WARN_ON_ONCE(ret == -EBUSY && !exiting))829return;830831mutex_lock(&exiting->futex_exit_mutex);832/*833* No point in doing state checking here. If the waiter got here834* while the task was in exec()->exec_futex_release() then it can835* have any FUTEX_STATE_* value when the waiter has acquired the836* mutex. OK, if running, EXITING or DEAD if it reached exit()837* already. Highly unlikely and not a problem. Just one more round838* through the futex maze.839*/840mutex_unlock(&exiting->futex_exit_mutex);841842put_task_struct(exiting);843}844845/**846* __futex_unqueue() - Remove the futex_q from its futex_hash_bucket847* @q: The futex_q to unqueue848*849* The q->lock_ptr must not be NULL and must be held by the caller.850*/851void __futex_unqueue(struct futex_q *q)852{853struct futex_hash_bucket *hb;854855if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))856return;857lockdep_assert_held(q->lock_ptr);858859hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);860plist_del(&q->list, &hb->chain);861futex_hb_waiters_dec(hb);862}863864/* The key must be already stored in q->key. */865void futex_q_lock(struct futex_q *q, struct futex_hash_bucket *hb)866__acquires(&hb->lock)867{868/*869* Increment the counter before taking the lock so that870* a potential waker won't miss a to-be-slept task that is871* waiting for the spinlock. This is safe as all futex_q_lock()872* users end up calling futex_queue(). Similarly, for housekeeping,873* decrement the counter at futex_q_unlock() when some error has874* occurred and we don't end up adding the task to the list.875*/876futex_hb_waiters_inc(hb); /* implies smp_mb(); (A) */877878q->lock_ptr = &hb->lock;879880spin_lock(&hb->lock);881}882883void futex_q_unlock(struct futex_hash_bucket *hb)884__releases(&hb->lock)885{886futex_hb_waiters_dec(hb);887spin_unlock(&hb->lock);888}889890void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb,891struct task_struct *task)892{893int prio;894895/*896* The priority used to register this element is897* - either the real thread-priority for the real-time threads898* (i.e. threads with a priority lower than MAX_RT_PRIO)899* - or MAX_RT_PRIO for non-RT threads.900* Thus, all RT-threads are woken first in priority order, and901* the others are woken last, in FIFO order.902*/903prio = min(current->normal_prio, MAX_RT_PRIO);904905plist_node_init(&q->list, prio);906plist_add(&q->list, &hb->chain);907q->task = task;908}909910/**911* futex_unqueue() - Remove the futex_q from its futex_hash_bucket912* @q: The futex_q to unqueue913*914* The q->lock_ptr must not be held by the caller. A call to futex_unqueue() must915* be paired with exactly one earlier call to futex_queue().916*917* Return:918* - 1 - if the futex_q was still queued (and we removed unqueued it);919* - 0 - if the futex_q was already removed by the waking thread920*/921int futex_unqueue(struct futex_q *q)922{923spinlock_t *lock_ptr;924int ret = 0;925926/* RCU so lock_ptr is not going away during locking. */927guard(rcu)();928/* In the common case we don't take the spinlock, which is nice. */929retry:930/*931* q->lock_ptr can change between this read and the following spin_lock.932* Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and933* optimizing lock_ptr out of the logic below.934*/935lock_ptr = READ_ONCE(q->lock_ptr);936if (lock_ptr != NULL) {937spin_lock(lock_ptr);938/*939* q->lock_ptr can change between reading it and940* spin_lock(), causing us to take the wrong lock. This941* corrects the race condition.942*943* Reasoning goes like this: if we have the wrong lock,944* q->lock_ptr must have changed (maybe several times)945* between reading it and the spin_lock(). It can946* change again after the spin_lock() but only if it was947* already changed before the spin_lock(). It cannot,948* however, change back to the original value. Therefore949* we can detect whether we acquired the correct lock.950*/951if (unlikely(lock_ptr != q->lock_ptr)) {952spin_unlock(lock_ptr);953goto retry;954}955__futex_unqueue(q);956957BUG_ON(q->pi_state);958959spin_unlock(lock_ptr);960ret = 1;961}962963return ret;964}965966void futex_q_lockptr_lock(struct futex_q *q)967{968spinlock_t *lock_ptr;969970/*971* See futex_unqueue() why lock_ptr can change.972*/973guard(rcu)();974retry:975lock_ptr = READ_ONCE(q->lock_ptr);976spin_lock(lock_ptr);977978if (unlikely(lock_ptr != q->lock_ptr)) {979spin_unlock(lock_ptr);980goto retry;981}982}983984/*985* PI futexes can not be requeued and must remove themselves from the hash986* bucket. The hash bucket lock (i.e. lock_ptr) is held.987*/988void futex_unqueue_pi(struct futex_q *q)989{990/*991* If the lock was not acquired (due to timeout or signal) then the992* rt_waiter is removed before futex_q is. If this is observed by993* an unlocker after dropping the rtmutex wait lock and before994* acquiring the hash bucket lock, then the unlocker dequeues the995* futex_q from the hash bucket list to guarantee consistent state996* vs. userspace. Therefore the dequeue here must be conditional.997*/998if (!plist_node_empty(&q->list))999__futex_unqueue(q);10001001BUG_ON(!q->pi_state);1002put_pi_state(q->pi_state);1003q->pi_state = NULL;1004}10051006/* Constants for the pending_op argument of handle_futex_death */1007#define HANDLE_DEATH_PENDING true1008#define HANDLE_DEATH_LIST false10091010/*1011* Process a futex-list entry, check whether it's owned by the1012* dying task, and do notification if so:1013*/1014static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,1015bool pi, bool pending_op)1016{1017u32 uval, nval, mval;1018pid_t owner;1019int err;10201021/* Futex address must be 32bit aligned */1022if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)1023return -1;10241025retry:1026if (get_user(uval, uaddr))1027return -1;10281029/*1030* Special case for regular (non PI) futexes. The unlock path in1031* user space has two race scenarios:1032*1033* 1. The unlock path releases the user space futex value and1034* before it can execute the futex() syscall to wake up1035* waiters it is killed.1036*1037* 2. A woken up waiter is killed before it can acquire the1038* futex in user space.1039*1040* In the second case, the wake up notification could be generated1041* by the unlock path in user space after setting the futex value1042* to zero or by the kernel after setting the OWNER_DIED bit below.1043*1044* In both cases the TID validation below prevents a wakeup of1045* potential waiters which can cause these waiters to block1046* forever.1047*1048* In both cases the following conditions are met:1049*1050* 1) task->robust_list->list_op_pending != NULL1051* @pending_op == true1052* 2) The owner part of user space futex value == 01053* 3) Regular futex: @pi == false1054*1055* If these conditions are met, it is safe to attempt waking up a1056* potential waiter without touching the user space futex value and1057* trying to set the OWNER_DIED bit. If the futex value is zero,1058* the rest of the user space mutex state is consistent, so a woken1059* waiter will just take over the uncontended futex. Setting the1060* OWNER_DIED bit would create inconsistent state and malfunction1061* of the user space owner died handling. Otherwise, the OWNER_DIED1062* bit is already set, and the woken waiter is expected to deal with1063* this.1064*/1065owner = uval & FUTEX_TID_MASK;10661067if (pending_op && !pi && !owner) {1068futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,1069FUTEX_BITSET_MATCH_ANY);1070return 0;1071}10721073if (owner != task_pid_vnr(curr))1074return 0;10751076/*1077* Ok, this dying thread is truly holding a futex1078* of interest. Set the OWNER_DIED bit atomically1079* via cmpxchg, and if the value had FUTEX_WAITERS1080* set, wake up a waiter (if any). (We have to do a1081* futex_wake() even if OWNER_DIED is already set -1082* to handle the rare but possible case of recursive1083* thread-death.) The rest of the cleanup is done in1084* userspace.1085*/1086mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;10871088/*1089* We are not holding a lock here, but we want to have1090* the pagefault_disable/enable() protection because1091* we want to handle the fault gracefully. If the1092* access fails we try to fault in the futex with R/W1093* verification via get_user_pages. get_user() above1094* does not guarantee R/W access. If that fails we1095* give up and leave the futex locked.1096*/1097if ((err = futex_cmpxchg_value_locked(&nval, uaddr, uval, mval))) {1098switch (err) {1099case -EFAULT:1100if (fault_in_user_writeable(uaddr))1101return -1;1102goto retry;11031104case -EAGAIN:1105cond_resched();1106goto retry;11071108default:1109WARN_ON_ONCE(1);1110return err;1111}1112}11131114if (nval != uval)1115goto retry;11161117/*1118* Wake robust non-PI futexes here. The wakeup of1119* PI futexes happens in exit_pi_state():1120*/1121if (!pi && (uval & FUTEX_WAITERS)) {1122futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,1123FUTEX_BITSET_MATCH_ANY);1124}11251126return 0;1127}11281129/*1130* Fetch a robust-list pointer. Bit 0 signals PI futexes:1131*/1132static inline int fetch_robust_entry(struct robust_list __user **entry,1133struct robust_list __user * __user *head,1134unsigned int *pi)1135{1136unsigned long uentry;11371138if (get_user(uentry, (unsigned long __user *)head))1139return -EFAULT;11401141*entry = (void __user *)(uentry & ~1UL);1142*pi = uentry & 1;11431144return 0;1145}11461147/*1148* Walk curr->robust_list (very carefully, it's a userspace list!)1149* and mark any locks found there dead, and notify any waiters.1150*1151* We silently return on any sign of list-walking problem.1152*/1153static void exit_robust_list(struct task_struct *curr)1154{1155struct robust_list_head __user *head = curr->robust_list;1156struct robust_list __user *entry, *next_entry, *pending;1157unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;1158unsigned int next_pi;1159unsigned long futex_offset;1160int rc;11611162/*1163* Fetch the list head (which was registered earlier, via1164* sys_set_robust_list()):1165*/1166if (fetch_robust_entry(&entry, &head->list.next, &pi))1167return;1168/*1169* Fetch the relative futex offset:1170*/1171if (get_user(futex_offset, &head->futex_offset))1172return;1173/*1174* Fetch any possibly pending lock-add first, and handle it1175* if it exists:1176*/1177if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))1178return;11791180next_entry = NULL; /* avoid warning with gcc */1181while (entry != &head->list) {1182/*1183* Fetch the next entry in the list before calling1184* handle_futex_death:1185*/1186rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);1187/*1188* A pending lock might already be on the list, so1189* don't process it twice:1190*/1191if (entry != pending) {1192if (handle_futex_death((void __user *)entry + futex_offset,1193curr, pi, HANDLE_DEATH_LIST))1194return;1195}1196if (rc)1197return;1198entry = next_entry;1199pi = next_pi;1200/*1201* Avoid excessively long or circular lists:1202*/1203if (!--limit)1204break;12051206cond_resched();1207}12081209if (pending) {1210handle_futex_death((void __user *)pending + futex_offset,1211curr, pip, HANDLE_DEATH_PENDING);1212}1213}12141215#ifdef CONFIG_COMPAT1216static void __user *futex_uaddr(struct robust_list __user *entry,1217compat_long_t futex_offset)1218{1219compat_uptr_t base = ptr_to_compat(entry);1220void __user *uaddr = compat_ptr(base + futex_offset);12211222return uaddr;1223}12241225/*1226* Fetch a robust-list pointer. Bit 0 signals PI futexes:1227*/1228static inline int1229compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,1230compat_uptr_t __user *head, unsigned int *pi)1231{1232if (get_user(*uentry, head))1233return -EFAULT;12341235*entry = compat_ptr((*uentry) & ~1);1236*pi = (unsigned int)(*uentry) & 1;12371238return 0;1239}12401241/*1242* Walk curr->robust_list (very carefully, it's a userspace list!)1243* and mark any locks found there dead, and notify any waiters.1244*1245* We silently return on any sign of list-walking problem.1246*/1247static void compat_exit_robust_list(struct task_struct *curr)1248{1249struct compat_robust_list_head __user *head = curr->compat_robust_list;1250struct robust_list __user *entry, *next_entry, *pending;1251unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;1252unsigned int next_pi;1253compat_uptr_t uentry, next_uentry, upending;1254compat_long_t futex_offset;1255int rc;12561257/*1258* Fetch the list head (which was registered earlier, via1259* sys_set_robust_list()):1260*/1261if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))1262return;1263/*1264* Fetch the relative futex offset:1265*/1266if (get_user(futex_offset, &head->futex_offset))1267return;1268/*1269* Fetch any possibly pending lock-add first, and handle it1270* if it exists:1271*/1272if (compat_fetch_robust_entry(&upending, &pending,1273&head->list_op_pending, &pip))1274return;12751276next_entry = NULL; /* avoid warning with gcc */1277while (entry != (struct robust_list __user *) &head->list) {1278/*1279* Fetch the next entry in the list before calling1280* handle_futex_death:1281*/1282rc = compat_fetch_robust_entry(&next_uentry, &next_entry,1283(compat_uptr_t __user *)&entry->next, &next_pi);1284/*1285* A pending lock might already be on the list, so1286* dont process it twice:1287*/1288if (entry != pending) {1289void __user *uaddr = futex_uaddr(entry, futex_offset);12901291if (handle_futex_death(uaddr, curr, pi,1292HANDLE_DEATH_LIST))1293return;1294}1295if (rc)1296return;1297uentry = next_uentry;1298entry = next_entry;1299pi = next_pi;1300/*1301* Avoid excessively long or circular lists:1302*/1303if (!--limit)1304break;13051306cond_resched();1307}1308if (pending) {1309void __user *uaddr = futex_uaddr(pending, futex_offset);13101311handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);1312}1313}1314#endif13151316#ifdef CONFIG_FUTEX_PI13171318/*1319* This task is holding PI mutexes at exit time => bad.1320* Kernel cleans up PI-state, but userspace is likely hosed.1321* (Robust-futex cleanup is separate and might save the day for userspace.)1322*/1323static void exit_pi_state_list(struct task_struct *curr)1324{1325struct list_head *next, *head = &curr->pi_state_list;1326struct futex_pi_state *pi_state;1327union futex_key key = FUTEX_KEY_INIT;13281329/*1330* The mutex mm_struct::futex_hash_lock might be acquired.1331*/1332might_sleep();1333/*1334* Ensure the hash remains stable (no resize) during the while loop1335* below. The hb pointer is acquired under the pi_lock so we can't block1336* on the mutex.1337*/1338WARN_ON(curr != current);1339guard(private_hash)();1340/*1341* We are a ZOMBIE and nobody can enqueue itself on1342* pi_state_list anymore, but we have to be careful1343* versus waiters unqueueing themselves:1344*/1345raw_spin_lock_irq(&curr->pi_lock);1346while (!list_empty(head)) {1347next = head->next;1348pi_state = list_entry(next, struct futex_pi_state, list);1349key = pi_state->key;1350if (1) {1351CLASS(hb, hb)(&key);13521353/*1354* We can race against put_pi_state() removing itself from the1355* list (a waiter going away). put_pi_state() will first1356* decrement the reference count and then modify the list, so1357* its possible to see the list entry but fail this reference1358* acquire.1359*1360* In that case; drop the locks to let put_pi_state() make1361* progress and retry the loop.1362*/1363if (!refcount_inc_not_zero(&pi_state->refcount)) {1364raw_spin_unlock_irq(&curr->pi_lock);1365cpu_relax();1366raw_spin_lock_irq(&curr->pi_lock);1367continue;1368}1369raw_spin_unlock_irq(&curr->pi_lock);13701371spin_lock(&hb->lock);1372raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);1373raw_spin_lock(&curr->pi_lock);1374/*1375* We dropped the pi-lock, so re-check whether this1376* task still owns the PI-state:1377*/1378if (head->next != next) {1379/* retain curr->pi_lock for the loop invariant */1380raw_spin_unlock(&pi_state->pi_mutex.wait_lock);1381spin_unlock(&hb->lock);1382put_pi_state(pi_state);1383continue;1384}13851386WARN_ON(pi_state->owner != curr);1387WARN_ON(list_empty(&pi_state->list));1388list_del_init(&pi_state->list);1389pi_state->owner = NULL;13901391raw_spin_unlock(&curr->pi_lock);1392raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);1393spin_unlock(&hb->lock);1394}13951396rt_mutex_futex_unlock(&pi_state->pi_mutex);1397put_pi_state(pi_state);13981399raw_spin_lock_irq(&curr->pi_lock);1400}1401raw_spin_unlock_irq(&curr->pi_lock);1402}1403#else1404static inline void exit_pi_state_list(struct task_struct *curr) { }1405#endif14061407static void futex_cleanup(struct task_struct *tsk)1408{1409if (unlikely(tsk->robust_list)) {1410exit_robust_list(tsk);1411tsk->robust_list = NULL;1412}14131414#ifdef CONFIG_COMPAT1415if (unlikely(tsk->compat_robust_list)) {1416compat_exit_robust_list(tsk);1417tsk->compat_robust_list = NULL;1418}1419#endif14201421if (unlikely(!list_empty(&tsk->pi_state_list)))1422exit_pi_state_list(tsk);1423}14241425/**1426* futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD1427* @tsk: task to set the state on1428*1429* Set the futex exit state of the task lockless. The futex waiter code1430* observes that state when a task is exiting and loops until the task has1431* actually finished the futex cleanup. The worst case for this is that the1432* waiter runs through the wait loop until the state becomes visible.1433*1434* This is called from the recursive fault handling path in make_task_dead().1435*1436* This is best effort. Either the futex exit code has run already or1437* not. If the OWNER_DIED bit has been set on the futex then the waiter can1438* take it over. If not, the problem is pushed back to user space. If the1439* futex exit code did not run yet, then an already queued waiter might1440* block forever, but there is nothing which can be done about that.1441*/1442void futex_exit_recursive(struct task_struct *tsk)1443{1444/* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */1445if (tsk->futex_state == FUTEX_STATE_EXITING)1446mutex_unlock(&tsk->futex_exit_mutex);1447tsk->futex_state = FUTEX_STATE_DEAD;1448}14491450static void futex_cleanup_begin(struct task_struct *tsk)1451{1452/*1453* Prevent various race issues against a concurrent incoming waiter1454* including live locks by forcing the waiter to block on1455* tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in1456* attach_to_pi_owner().1457*/1458mutex_lock(&tsk->futex_exit_mutex);14591460/*1461* Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.1462*1463* This ensures that all subsequent checks of tsk->futex_state in1464* attach_to_pi_owner() must observe FUTEX_STATE_EXITING with1465* tsk->pi_lock held.1466*1467* It guarantees also that a pi_state which was queued right before1468* the state change under tsk->pi_lock by a concurrent waiter must1469* be observed in exit_pi_state_list().1470*/1471raw_spin_lock_irq(&tsk->pi_lock);1472tsk->futex_state = FUTEX_STATE_EXITING;1473raw_spin_unlock_irq(&tsk->pi_lock);1474}14751476static void futex_cleanup_end(struct task_struct *tsk, int state)1477{1478/*1479* Lockless store. The only side effect is that an observer might1480* take another loop until it becomes visible.1481*/1482tsk->futex_state = state;1483/*1484* Drop the exit protection. This unblocks waiters which observed1485* FUTEX_STATE_EXITING to reevaluate the state.1486*/1487mutex_unlock(&tsk->futex_exit_mutex);1488}14891490void futex_exec_release(struct task_struct *tsk)1491{1492/*1493* The state handling is done for consistency, but in the case of1494* exec() there is no way to prevent further damage as the PID stays1495* the same. But for the unlikely and arguably buggy case that a1496* futex is held on exec(), this provides at least as much state1497* consistency protection which is possible.1498*/1499futex_cleanup_begin(tsk);1500futex_cleanup(tsk);1501/*1502* Reset the state to FUTEX_STATE_OK. The task is alive and about1503* exec a new binary.1504*/1505futex_cleanup_end(tsk, FUTEX_STATE_OK);1506}15071508void futex_exit_release(struct task_struct *tsk)1509{1510futex_cleanup_begin(tsk);1511futex_cleanup(tsk);1512futex_cleanup_end(tsk, FUTEX_STATE_DEAD);1513}15141515static void futex_hash_bucket_init(struct futex_hash_bucket *fhb,1516struct futex_private_hash *fph)1517{1518#ifdef CONFIG_FUTEX_PRIVATE_HASH1519fhb->priv = fph;1520#endif1521atomic_set(&fhb->waiters, 0);1522plist_head_init(&fhb->chain);1523spin_lock_init(&fhb->lock);1524}15251526#define FH_CUSTOM 0x0115271528#ifdef CONFIG_FUTEX_PRIVATE_HASH15291530/*1531* futex-ref1532*1533* Heavily inspired by percpu-rwsem/percpu-refcount; not reusing any of that1534* code because it just doesn't fit right.1535*1536* Dual counter, per-cpu / atomic approach like percpu-refcount, except it1537* re-initializes the state automatically, such that the fph swizzle is also a1538* transition back to per-cpu.1539*/15401541static void futex_ref_rcu(struct rcu_head *head);15421543static void __futex_ref_atomic_begin(struct futex_private_hash *fph)1544{1545struct mm_struct *mm = fph->mm;15461547/*1548* The counter we're about to switch to must have fully switched;1549* otherwise it would be impossible for it to have reported success1550* from futex_ref_is_dead().1551*/1552WARN_ON_ONCE(atomic_long_read(&mm->futex_atomic) != 0);15531554/*1555* Set the atomic to the bias value such that futex_ref_{get,put}()1556* will never observe 0. Will be fixed up in __futex_ref_atomic_end()1557* when folding in the percpu count.1558*/1559atomic_long_set(&mm->futex_atomic, LONG_MAX);1560smp_store_release(&fph->state, FR_ATOMIC);15611562call_rcu_hurry(&mm->futex_rcu, futex_ref_rcu);1563}15641565static void __futex_ref_atomic_end(struct futex_private_hash *fph)1566{1567struct mm_struct *mm = fph->mm;1568unsigned int count = 0;1569long ret;1570int cpu;15711572/*1573* Per __futex_ref_atomic_begin() the state of the fph must be ATOMIC1574* and per this RCU callback, everybody must now observe this state and1575* use the atomic variable.1576*/1577WARN_ON_ONCE(fph->state != FR_ATOMIC);15781579/*1580* Therefore the per-cpu counter is now stable, sum and reset.1581*/1582for_each_possible_cpu(cpu) {1583unsigned int *ptr = per_cpu_ptr(mm->futex_ref, cpu);1584count += *ptr;1585*ptr = 0;1586}15871588/*1589* Re-init for the next cycle.1590*/1591this_cpu_inc(*mm->futex_ref); /* 0 -> 1 */15921593/*1594* Add actual count, subtract bias and initial refcount.1595*1596* The moment this atomic operation happens, futex_ref_is_dead() can1597* become true.1598*/1599ret = atomic_long_add_return(count - LONG_MAX - 1, &mm->futex_atomic);1600if (!ret)1601wake_up_var(mm);16021603WARN_ON_ONCE(ret < 0);1604mmput_async(mm);1605}16061607static void futex_ref_rcu(struct rcu_head *head)1608{1609struct mm_struct *mm = container_of(head, struct mm_struct, futex_rcu);1610struct futex_private_hash *fph = rcu_dereference_raw(mm->futex_phash);16111612if (fph->state == FR_PERCPU) {1613/*1614* Per this extra grace-period, everybody must now observe1615* fph as the current fph and no previously observed fph's1616* are in-flight.1617*1618* Notably, nobody will now rely on the atomic1619* futex_ref_is_dead() state anymore so we can begin the1620* migration of the per-cpu counter into the atomic.1621*/1622__futex_ref_atomic_begin(fph);1623return;1624}16251626__futex_ref_atomic_end(fph);1627}16281629/*1630* Drop the initial refcount and transition to atomics.1631*/1632static void futex_ref_drop(struct futex_private_hash *fph)1633{1634struct mm_struct *mm = fph->mm;16351636/*1637* Can only transition the current fph;1638*/1639WARN_ON_ONCE(rcu_dereference_raw(mm->futex_phash) != fph);1640/*1641* We enqueue at least one RCU callback. Ensure mm stays if the task1642* exits before the transition is completed.1643*/1644mmget(mm);16451646/*1647* In order to avoid the following scenario:1648*1649* futex_hash() __futex_pivot_hash()1650* guard(rcu); guard(mm->futex_hash_lock);1651* fph = mm->futex_phash;1652* rcu_assign_pointer(&mm->futex_phash, new);1653* futex_hash_allocate()1654* futex_ref_drop()1655* fph->state = FR_ATOMIC;1656* atomic_set(, BIAS);1657*1658* futex_private_hash_get(fph); // OOPS1659*1660* Where an old fph (which is FR_ATOMIC) and should fail on1661* inc_not_zero, will succeed because a new transition is started and1662* the atomic is bias'ed away from 0.1663*1664* There must be at least one full grace-period between publishing a1665* new fph and trying to replace it.1666*/1667if (poll_state_synchronize_rcu(mm->futex_batches)) {1668/*1669* There was a grace-period, we can begin now.1670*/1671__futex_ref_atomic_begin(fph);1672return;1673}16741675call_rcu_hurry(&mm->futex_rcu, futex_ref_rcu);1676}16771678static bool futex_ref_get(struct futex_private_hash *fph)1679{1680struct mm_struct *mm = fph->mm;16811682guard(rcu)();16831684if (smp_load_acquire(&fph->state) == FR_PERCPU) {1685this_cpu_inc(*mm->futex_ref);1686return true;1687}16881689return atomic_long_inc_not_zero(&mm->futex_atomic);1690}16911692static bool futex_ref_put(struct futex_private_hash *fph)1693{1694struct mm_struct *mm = fph->mm;16951696guard(rcu)();16971698if (smp_load_acquire(&fph->state) == FR_PERCPU) {1699this_cpu_dec(*mm->futex_ref);1700return false;1701}17021703return atomic_long_dec_and_test(&mm->futex_atomic);1704}17051706static bool futex_ref_is_dead(struct futex_private_hash *fph)1707{1708struct mm_struct *mm = fph->mm;17091710guard(rcu)();17111712if (smp_load_acquire(&fph->state) == FR_PERCPU)1713return false;17141715return atomic_long_read(&mm->futex_atomic) == 0;1716}17171718int futex_mm_init(struct mm_struct *mm)1719{1720mutex_init(&mm->futex_hash_lock);1721RCU_INIT_POINTER(mm->futex_phash, NULL);1722mm->futex_phash_new = NULL;1723/* futex-ref */1724mm->futex_ref = NULL;1725atomic_long_set(&mm->futex_atomic, 0);1726mm->futex_batches = get_state_synchronize_rcu();1727return 0;1728}17291730void futex_hash_free(struct mm_struct *mm)1731{1732struct futex_private_hash *fph;17331734free_percpu(mm->futex_ref);1735kvfree(mm->futex_phash_new);1736fph = rcu_dereference_raw(mm->futex_phash);1737if (fph)1738kvfree(fph);1739}17401741static bool futex_pivot_pending(struct mm_struct *mm)1742{1743struct futex_private_hash *fph;17441745guard(rcu)();17461747if (!mm->futex_phash_new)1748return true;17491750fph = rcu_dereference(mm->futex_phash);1751return futex_ref_is_dead(fph);1752}17531754static bool futex_hash_less(struct futex_private_hash *a,1755struct futex_private_hash *b)1756{1757/* user provided always wins */1758if (!a->custom && b->custom)1759return true;1760if (a->custom && !b->custom)1761return false;17621763/* zero-sized hash wins */1764if (!b->hash_mask)1765return true;1766if (!a->hash_mask)1767return false;17681769/* keep the biggest */1770if (a->hash_mask < b->hash_mask)1771return true;1772if (a->hash_mask > b->hash_mask)1773return false;17741775return false; /* equal */1776}17771778static int futex_hash_allocate(unsigned int hash_slots, unsigned int flags)1779{1780struct mm_struct *mm = current->mm;1781struct futex_private_hash *fph;1782bool custom = flags & FH_CUSTOM;1783int i;17841785if (hash_slots && (hash_slots == 1 || !is_power_of_2(hash_slots)))1786return -EINVAL;17871788/*1789* Once we've disabled the global hash there is no way back.1790*/1791scoped_guard(rcu) {1792fph = rcu_dereference(mm->futex_phash);1793if (fph && !fph->hash_mask) {1794if (custom)1795return -EBUSY;1796return 0;1797}1798}17991800if (!mm->futex_ref) {1801/*1802* This will always be allocated by the first thread and1803* therefore requires no locking.1804*/1805mm->futex_ref = alloc_percpu(unsigned int);1806if (!mm->futex_ref)1807return -ENOMEM;1808this_cpu_inc(*mm->futex_ref); /* 0 -> 1 */1809}18101811fph = kvzalloc(struct_size(fph, queues, hash_slots),1812GFP_KERNEL_ACCOUNT | __GFP_NOWARN);1813if (!fph)1814return -ENOMEM;18151816fph->hash_mask = hash_slots ? hash_slots - 1 : 0;1817fph->custom = custom;1818fph->mm = mm;18191820for (i = 0; i < hash_slots; i++)1821futex_hash_bucket_init(&fph->queues[i], fph);18221823if (custom) {1824/*1825* Only let prctl() wait / retry; don't unduly delay clone().1826*/1827again:1828wait_var_event(mm, futex_pivot_pending(mm));1829}18301831scoped_guard(mutex, &mm->futex_hash_lock) {1832struct futex_private_hash *free __free(kvfree) = NULL;1833struct futex_private_hash *cur, *new;18341835cur = rcu_dereference_protected(mm->futex_phash,1836lockdep_is_held(&mm->futex_hash_lock));1837new = mm->futex_phash_new;1838mm->futex_phash_new = NULL;18391840if (fph) {1841if (cur && !cur->hash_mask) {1842/*1843* If two threads simultaneously request the global1844* hash then the first one performs the switch,1845* the second one returns here.1846*/1847free = fph;1848mm->futex_phash_new = new;1849return -EBUSY;1850}1851if (cur && !new) {1852/*1853* If we have an existing hash, but do not yet have1854* allocated a replacement hash, drop the initial1855* reference on the existing hash.1856*/1857futex_ref_drop(cur);1858}18591860if (new) {1861/*1862* Two updates raced; throw out the lesser one.1863*/1864if (futex_hash_less(new, fph)) {1865free = new;1866new = fph;1867} else {1868free = fph;1869}1870} else {1871new = fph;1872}1873fph = NULL;1874}18751876if (new) {1877/*1878* Will set mm->futex_phash_new on failure;1879* futex_private_hash_get() will try again.1880*/1881if (!__futex_pivot_hash(mm, new) && custom)1882goto again;1883}1884}1885return 0;1886}18871888int futex_hash_allocate_default(void)1889{1890unsigned int threads, buckets, current_buckets = 0;1891struct futex_private_hash *fph;18921893if (!current->mm)1894return 0;18951896scoped_guard(rcu) {1897threads = min_t(unsigned int,1898get_nr_threads(current),1899num_online_cpus());19001901fph = rcu_dereference(current->mm->futex_phash);1902if (fph) {1903if (fph->custom)1904return 0;19051906current_buckets = fph->hash_mask + 1;1907}1908}19091910/*1911* The default allocation will remain within1912* 16 <= threads * 4 <= global hash size1913*/1914buckets = roundup_pow_of_two(4 * threads);1915buckets = clamp(buckets, 16, futex_hashmask + 1);19161917if (current_buckets >= buckets)1918return 0;19191920return futex_hash_allocate(buckets, 0);1921}19221923static int futex_hash_get_slots(void)1924{1925struct futex_private_hash *fph;19261927guard(rcu)();1928fph = rcu_dereference(current->mm->futex_phash);1929if (fph && fph->hash_mask)1930return fph->hash_mask + 1;1931return 0;1932}19331934#else19351936static int futex_hash_allocate(unsigned int hash_slots, unsigned int flags)1937{1938return -EINVAL;1939}19401941static int futex_hash_get_slots(void)1942{1943return 0;1944}19451946#endif19471948int futex_hash_prctl(unsigned long arg2, unsigned long arg3, unsigned long arg4)1949{1950unsigned int flags = FH_CUSTOM;1951int ret;19521953switch (arg2) {1954case PR_FUTEX_HASH_SET_SLOTS:1955if (arg4)1956return -EINVAL;1957ret = futex_hash_allocate(arg3, flags);1958break;19591960case PR_FUTEX_HASH_GET_SLOTS:1961ret = futex_hash_get_slots();1962break;19631964default:1965ret = -EINVAL;1966break;1967}1968return ret;1969}19701971static int __init futex_init(void)1972{1973unsigned long hashsize, i;1974unsigned int order, n;1975unsigned long size;19761977#ifdef CONFIG_BASE_SMALL1978hashsize = 16;1979#else1980hashsize = 256 * num_possible_cpus();1981hashsize /= num_possible_nodes();1982hashsize = max(4, hashsize);1983hashsize = roundup_pow_of_two(hashsize);1984#endif1985futex_hashshift = ilog2(hashsize);1986size = sizeof(struct futex_hash_bucket) * hashsize;1987order = get_order(size);19881989for_each_node(n) {1990struct futex_hash_bucket *table;19911992if (order > MAX_PAGE_ORDER)1993table = vmalloc_huge_node(size, GFP_KERNEL, n);1994else1995table = alloc_pages_exact_nid(n, size, GFP_KERNEL);19961997BUG_ON(!table);19981999for (i = 0; i < hashsize; i++)2000futex_hash_bucket_init(&table[i], NULL);20012002futex_queues[n] = table;2003}20042005futex_hashmask = hashsize - 1;2006pr_info("futex hash table entries: %lu (%lu bytes on %d NUMA nodes, total %lu KiB, %s).\n",2007hashsize, size, num_possible_nodes(), size * num_possible_nodes() / 1024,2008order > MAX_PAGE_ORDER ? "vmalloc" : "linear");2009return 0;2010}2011core_initcall(futex_init);201220132014