/* SPDX-License-Identifier: GPL-2.0 */1#ifndef _GEN_PV_LOCK_SLOWPATH2#error "do not include this file"3#endif45#include <linux/hash.h>6#include <linux/memblock.h>7#include <linux/debug_locks.h>89/*10* Implement paravirt qspinlocks; the general idea is to halt the vcpus instead11* of spinning them.12*13* This relies on the architecture to provide two paravirt hypercalls:14*15* pv_wait(u8 *ptr, u8 val) -- suspends the vcpu if *ptr == val16* pv_kick(cpu) -- wakes a suspended vcpu17*18* Using these we implement __pv_queued_spin_lock_slowpath() and19* __pv_queued_spin_unlock() to replace native_queued_spin_lock_slowpath() and20* native_queued_spin_unlock().21*/2223#define _Q_SLOW_VAL (3U << _Q_LOCKED_OFFSET)2425/*26* Queue Node Adaptive Spinning27*28* A queue node vCPU will stop spinning if the vCPU in the previous node is29* not running. The one lock stealing attempt allowed at slowpath entry30* mitigates the slight slowdown for non-overcommitted guest with this31* aggressive wait-early mechanism.32*33* The status of the previous node will be checked at fixed interval34* controlled by PV_PREV_CHECK_MASK. This is to ensure that we won't35* pound on the cacheline of the previous node too heavily.36*/37#define PV_PREV_CHECK_MASK 0xff3839/*40* Queue node uses: VCPU_RUNNING & VCPU_HALTED.41* Queue head uses: VCPU_RUNNING & VCPU_HASHED.42*/43enum vcpu_state {44VCPU_RUNNING = 0,45VCPU_HALTED, /* Used only in pv_wait_node */46VCPU_HASHED, /* = pv_hash'ed + VCPU_HALTED */47};4849struct pv_node {50struct mcs_spinlock mcs;51int cpu;52u8 state;53};5455/*56* Hybrid PV queued/unfair lock57*58* By replacing the regular queued_spin_trylock() with the function below,59* it will be called once when a lock waiter enter the PV slowpath before60* being queued.61*62* The pending bit is set by the queue head vCPU of the MCS wait queue in63* pv_wait_head_or_lock() to signal that it is ready to spin on the lock.64* When that bit becomes visible to the incoming waiters, no lock stealing65* is allowed. The function will return immediately to make the waiters66* enter the MCS wait queue. So lock starvation shouldn't happen as long67* as the queued mode vCPUs are actively running to set the pending bit68* and hence disabling lock stealing.69*70* When the pending bit isn't set, the lock waiters will stay in the unfair71* mode spinning on the lock unless the MCS wait queue is empty. In this72* case, the lock waiters will enter the queued mode slowpath trying to73* become the queue head and set the pending bit.74*75* This hybrid PV queued/unfair lock combines the best attributes of a76* queued lock (no lock starvation) and an unfair lock (good performance77* on not heavily contended locks).78*/79#define queued_spin_trylock(l) pv_hybrid_queued_unfair_trylock(l)80static inline bool pv_hybrid_queued_unfair_trylock(struct qspinlock *lock)81{82/*83* Stay in unfair lock mode as long as queued mode waiters are84* present in the MCS wait queue but the pending bit isn't set.85*/86for (;;) {87int val = atomic_read(&lock->val);88u8 old = 0;8990if (!(val & _Q_LOCKED_PENDING_MASK) &&91try_cmpxchg_acquire(&lock->locked, &old, _Q_LOCKED_VAL)) {92lockevent_inc(pv_lock_stealing);93return true;94}95if (!(val & _Q_TAIL_MASK) || (val & _Q_PENDING_MASK))96break;9798cpu_relax();99}100101return false;102}103104/*105* The pending bit is used by the queue head vCPU to indicate that it106* is actively spinning on the lock and no lock stealing is allowed.107*/108#if _Q_PENDING_BITS == 8109static __always_inline void set_pending(struct qspinlock *lock)110{111WRITE_ONCE(lock->pending, 1);112}113114/*115* The pending bit check in pv_queued_spin_steal_lock() isn't a memory116* barrier. Therefore, an atomic cmpxchg_acquire() is used to acquire the117* lock just to be sure that it will get it.118*/119static __always_inline bool trylock_clear_pending(struct qspinlock *lock)120{121u16 old = _Q_PENDING_VAL;122123return !READ_ONCE(lock->locked) &&124try_cmpxchg_acquire(&lock->locked_pending, &old, _Q_LOCKED_VAL);125}126#else /* _Q_PENDING_BITS == 8 */127static __always_inline void set_pending(struct qspinlock *lock)128{129atomic_or(_Q_PENDING_VAL, &lock->val);130}131132static __always_inline bool trylock_clear_pending(struct qspinlock *lock)133{134int old, new;135136old = atomic_read(&lock->val);137do {138if (old & _Q_LOCKED_MASK)139return false;140/*141* Try to clear pending bit & set locked bit142*/143new = (old & ~_Q_PENDING_MASK) | _Q_LOCKED_VAL;144} while (!atomic_try_cmpxchg_acquire (&lock->val, &old, new));145146return true;147}148#endif /* _Q_PENDING_BITS == 8 */149150/*151* Lock and MCS node addresses hash table for fast lookup152*153* Hashing is done on a per-cacheline basis to minimize the need to access154* more than one cacheline.155*156* Dynamically allocate a hash table big enough to hold at least 4X the157* number of possible cpus in the system. Allocation is done on page158* granularity. So the minimum number of hash buckets should be at least159* 256 (64-bit) or 512 (32-bit) to fully utilize a 4k page.160*161* Since we should not be holding locks from NMI context (very rare indeed) the162* max load factor is 0.75, which is around the point where open addressing163* breaks down.164*165*/166struct pv_hash_entry {167struct qspinlock *lock;168struct pv_node *node;169};170171#define PV_HE_PER_LINE (SMP_CACHE_BYTES / sizeof(struct pv_hash_entry))172#define PV_HE_MIN (PAGE_SIZE / sizeof(struct pv_hash_entry))173174static struct pv_hash_entry *pv_lock_hash;175static unsigned int pv_lock_hash_bits __read_mostly;176177/*178* Allocate memory for the PV qspinlock hash buckets179*180* This function should be called from the paravirt spinlock initialization181* routine.182*/183void __init __pv_init_lock_hash(void)184{185int pv_hash_size = ALIGN(4 * num_possible_cpus(), PV_HE_PER_LINE);186187if (pv_hash_size < PV_HE_MIN)188pv_hash_size = PV_HE_MIN;189190/*191* Allocate space from bootmem which should be page-size aligned192* and hence cacheline aligned.193*/194pv_lock_hash = alloc_large_system_hash("PV qspinlock",195sizeof(struct pv_hash_entry),196pv_hash_size, 0,197HASH_EARLY | HASH_ZERO,198&pv_lock_hash_bits, NULL,199pv_hash_size, pv_hash_size);200}201202#define for_each_hash_entry(he, offset, hash) \203for (hash &= ~(PV_HE_PER_LINE - 1), he = &pv_lock_hash[hash], offset = 0; \204offset < (1 << pv_lock_hash_bits); \205offset++, he = &pv_lock_hash[(hash + offset) & ((1 << pv_lock_hash_bits) - 1)])206207static struct qspinlock **pv_hash(struct qspinlock *lock, struct pv_node *node)208{209unsigned long offset, hash = hash_ptr(lock, pv_lock_hash_bits);210struct pv_hash_entry *he;211int hopcnt = 0;212213for_each_hash_entry(he, offset, hash) {214struct qspinlock *old = NULL;215hopcnt++;216if (try_cmpxchg(&he->lock, &old, lock)) {217WRITE_ONCE(he->node, node);218lockevent_pv_hop(hopcnt);219return &he->lock;220}221}222/*223* Hard assume there is a free entry for us.224*225* This is guaranteed by ensuring every blocked lock only ever consumes226* a single entry, and since we only have 4 nesting levels per CPU227* and allocated 4*nr_possible_cpus(), this must be so.228*229* The single entry is guaranteed by having the lock owner unhash230* before it releases.231*/232BUG();233}234235static struct pv_node *pv_unhash(struct qspinlock *lock)236{237unsigned long offset, hash = hash_ptr(lock, pv_lock_hash_bits);238struct pv_hash_entry *he;239struct pv_node *node;240241for_each_hash_entry(he, offset, hash) {242if (READ_ONCE(he->lock) == lock) {243node = READ_ONCE(he->node);244WRITE_ONCE(he->lock, NULL);245return node;246}247}248/*249* Hard assume we'll find an entry.250*251* This guarantees a limited lookup time and is itself guaranteed by252* having the lock owner do the unhash -- IFF the unlock sees the253* SLOW flag, there MUST be a hash entry.254*/255BUG();256}257258/*259* Return true if when it is time to check the previous node which is not260* in a running state.261*/262static inline bool263pv_wait_early(struct pv_node *prev, int loop)264{265if ((loop & PV_PREV_CHECK_MASK) != 0)266return false;267268return READ_ONCE(prev->state) != VCPU_RUNNING;269}270271/*272* Initialize the PV part of the mcs_spinlock node.273*/274static void pv_init_node(struct mcs_spinlock *node)275{276struct pv_node *pn = (struct pv_node *)node;277278BUILD_BUG_ON(sizeof(struct pv_node) > sizeof(struct qnode));279280pn->cpu = smp_processor_id();281pn->state = VCPU_RUNNING;282}283284/*285* Wait for node->locked to become true, halt the vcpu after a short spin.286* pv_kick_node() is used to set _Q_SLOW_VAL and fill in hash table on its287* behalf.288*/289static void pv_wait_node(struct mcs_spinlock *node, struct mcs_spinlock *prev)290{291struct pv_node *pn = (struct pv_node *)node;292struct pv_node *pp = (struct pv_node *)prev;293bool wait_early;294int loop;295296for (;;) {297for (wait_early = false, loop = SPIN_THRESHOLD; loop; loop--) {298if (READ_ONCE(node->locked))299return;300if (pv_wait_early(pp, loop)) {301wait_early = true;302break;303}304cpu_relax();305}306307/*308* Order pn->state vs pn->locked thusly:309*310* [S] pn->state = VCPU_HALTED [S] next->locked = 1311* MB MB312* [L] pn->locked [RmW] pn->state = VCPU_HASHED313*314* Matches the cmpxchg() from pv_kick_node().315*/316smp_store_mb(pn->state, VCPU_HALTED);317318if (!READ_ONCE(node->locked)) {319lockevent_inc(pv_wait_node);320lockevent_cond_inc(pv_wait_early, wait_early);321pv_wait(&pn->state, VCPU_HALTED);322}323324/*325* If pv_kick_node() changed us to VCPU_HASHED, retain that326* value so that pv_wait_head_or_lock() knows to not also try327* to hash this lock.328*/329cmpxchg(&pn->state, VCPU_HALTED, VCPU_RUNNING);330331/*332* If the locked flag is still not set after wakeup, it is a333* spurious wakeup and the vCPU should wait again. However,334* there is a pretty high overhead for CPU halting and kicking.335* So it is better to spin for a while in the hope that the336* MCS lock will be released soon.337*/338lockevent_cond_inc(pv_spurious_wakeup,339!READ_ONCE(node->locked));340}341342/*343* By now our node->locked should be 1 and our caller will not actually344* spin-wait for it. We do however rely on our caller to do a345* load-acquire for us.346*/347}348349/*350* Called after setting next->locked = 1 when we're the lock owner.351*352* Instead of waking the waiters stuck in pv_wait_node() advance their state353* such that they're waiting in pv_wait_head_or_lock(), this avoids a354* wake/sleep cycle.355*/356static void pv_kick_node(struct qspinlock *lock, struct mcs_spinlock *node)357{358struct pv_node *pn = (struct pv_node *)node;359u8 old = VCPU_HALTED;360/*361* If the vCPU is indeed halted, advance its state to match that of362* pv_wait_node(). If OTOH this fails, the vCPU was running and will363* observe its next->locked value and advance itself.364*365* Matches with smp_store_mb() and cmpxchg() in pv_wait_node()366*367* The write to next->locked in arch_mcs_spin_unlock_contended()368* must be ordered before the read of pn->state in the cmpxchg()369* below for the code to work correctly. To guarantee full ordering370* irrespective of the success or failure of the cmpxchg(),371* a relaxed version with explicit barrier is used. The control372* dependency will order the reading of pn->state before any373* subsequent writes.374*/375smp_mb__before_atomic();376if (!try_cmpxchg_relaxed(&pn->state, &old, VCPU_HASHED))377return;378379/*380* Put the lock into the hash table and set the _Q_SLOW_VAL.381*382* As this is the same vCPU that will check the _Q_SLOW_VAL value and383* the hash table later on at unlock time, no atomic instruction is384* needed.385*/386WRITE_ONCE(lock->locked, _Q_SLOW_VAL);387(void)pv_hash(lock, pn);388}389390/*391* Wait for l->locked to become clear and acquire the lock;392* halt the vcpu after a short spin.393* __pv_queued_spin_unlock() will wake us.394*395* The current value of the lock will be returned for additional processing.396*/397static u32398pv_wait_head_or_lock(struct qspinlock *lock, struct mcs_spinlock *node)399{400struct pv_node *pn = (struct pv_node *)node;401struct qspinlock **lp = NULL;402int waitcnt = 0;403int loop;404405/*406* If pv_kick_node() already advanced our state, we don't need to407* insert ourselves into the hash table anymore.408*/409if (READ_ONCE(pn->state) == VCPU_HASHED)410lp = (struct qspinlock **)1;411412/*413* Tracking # of slowpath locking operations414*/415lockevent_inc(lock_slowpath);416417for (;; waitcnt++) {418/*419* Set correct vCPU state to be used by queue node wait-early420* mechanism.421*/422WRITE_ONCE(pn->state, VCPU_RUNNING);423424/*425* Set the pending bit in the active lock spinning loop to426* disable lock stealing before attempting to acquire the lock.427*/428set_pending(lock);429for (loop = SPIN_THRESHOLD; loop; loop--) {430if (trylock_clear_pending(lock))431goto gotlock;432cpu_relax();433}434clear_pending(lock);435436437if (!lp) { /* ONCE */438lp = pv_hash(lock, pn);439440/*441* We must hash before setting _Q_SLOW_VAL, such that442* when we observe _Q_SLOW_VAL in __pv_queued_spin_unlock()443* we'll be sure to be able to observe our hash entry.444*445* [S] <hash> [Rmw] l->locked == _Q_SLOW_VAL446* MB RMB447* [RmW] l->locked = _Q_SLOW_VAL [L] <unhash>448*449* Matches the smp_rmb() in __pv_queued_spin_unlock().450*/451if (xchg(&lock->locked, _Q_SLOW_VAL) == 0) {452/*453* The lock was free and now we own the lock.454* Change the lock value back to _Q_LOCKED_VAL455* and unhash the table.456*/457WRITE_ONCE(lock->locked, _Q_LOCKED_VAL);458WRITE_ONCE(*lp, NULL);459goto gotlock;460}461}462WRITE_ONCE(pn->state, VCPU_HASHED);463lockevent_inc(pv_wait_head);464lockevent_cond_inc(pv_wait_again, waitcnt);465pv_wait(&lock->locked, _Q_SLOW_VAL);466467/*468* Because of lock stealing, the queue head vCPU may not be469* able to acquire the lock before it has to wait again.470*/471}472473/*474* The cmpxchg() or xchg() call before coming here provides the475* acquire semantics for locking. The dummy ORing of _Q_LOCKED_VAL476* here is to indicate to the compiler that the value will always477* be nozero to enable better code optimization.478*/479gotlock:480return (u32)(atomic_read(&lock->val) | _Q_LOCKED_VAL);481}482483/*484* Include the architecture specific callee-save thunk of the485* __pv_queued_spin_unlock(). This thunk is put together with486* __pv_queued_spin_unlock() to make the callee-save thunk and the real unlock487* function close to each other sharing consecutive instruction cachelines.488* Alternatively, architecture specific version of __pv_queued_spin_unlock()489* can be defined.490*/491#include <asm/qspinlock_paravirt.h>492493/*494* PV versions of the unlock fastpath and slowpath functions to be used495* instead of queued_spin_unlock().496*/497__visible __lockfunc void498__pv_queued_spin_unlock_slowpath(struct qspinlock *lock, u8 locked)499{500struct pv_node *node;501502if (unlikely(locked != _Q_SLOW_VAL)) {503WARN(!debug_locks_silent,504"pvqspinlock: lock 0x%lx has corrupted value 0x%x!\n",505(unsigned long)lock, atomic_read(&lock->val));506return;507}508509/*510* A failed cmpxchg doesn't provide any memory-ordering guarantees,511* so we need a barrier to order the read of the node data in512* pv_unhash *after* we've read the lock being _Q_SLOW_VAL.513*514* Matches the cmpxchg() in pv_wait_head_or_lock() setting _Q_SLOW_VAL.515*/516smp_rmb();517518/*519* Since the above failed to release, this must be the SLOW path.520* Therefore start by looking up the blocked node and unhashing it.521*/522node = pv_unhash(lock);523524/*525* Now that we have a reference to the (likely) blocked pv_node,526* release the lock.527*/528smp_store_release(&lock->locked, 0);529530/*531* At this point the memory pointed at by lock can be freed/reused,532* however we can still use the pv_node to kick the CPU.533* The other vCPU may not really be halted, but kicking an active534* vCPU is harmless other than the additional latency in completing535* the unlock.536*/537lockevent_inc(pv_kick_unlock);538pv_kick(node->cpu);539}540541#ifndef __pv_queued_spin_unlock542__visible __lockfunc void __pv_queued_spin_unlock(struct qspinlock *lock)543{544u8 locked = _Q_LOCKED_VAL;545546/*547* We must not unlock if SLOW, because in that case we must first548* unhash. Otherwise it would be possible to have multiple @lock549* entries, which would be BAD.550*/551if (try_cmpxchg_release(&lock->locked, &locked, 0))552return;553554__pv_queued_spin_unlock_slowpath(lock, locked);555}556#endif /* __pv_queued_spin_unlock */557558559