// SPDX-License-Identifier: GPL-2.0-or-later1/*2* Queued spinlock3*4* (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.5* (C) Copyright 2013-2014,2018 Red Hat, Inc.6* (C) Copyright 2015 Intel Corp.7* (C) Copyright 2015 Hewlett-Packard Enterprise Development LP8*9* Authors: Waiman Long <[email protected]>10* Peter Zijlstra <[email protected]>11*/1213#ifndef _GEN_PV_LOCK_SLOWPATH1415#include <linux/smp.h>16#include <linux/bug.h>17#include <linux/cpumask.h>18#include <linux/percpu.h>19#include <linux/hardirq.h>20#include <linux/mutex.h>21#include <linux/prefetch.h>22#include <asm/byteorder.h>23#include <asm/qspinlock.h>24#include <trace/events/lock.h>2526/*27* Include queued spinlock definitions and statistics code28*/29#include "qspinlock.h"30#include "qspinlock_stat.h"3132/*33* The basic principle of a queue-based spinlock can best be understood34* by studying a classic queue-based spinlock implementation called the35* MCS lock. A copy of the original MCS lock paper ("Algorithms for Scalable36* Synchronization on Shared-Memory Multiprocessors by Mellor-Crummey and37* Scott") is available at38*39* https://bugzilla.kernel.org/show_bug.cgi?id=20611540*41* This queued spinlock implementation is based on the MCS lock, however to42* make it fit the 4 bytes we assume spinlock_t to be, and preserve its43* existing API, we must modify it somehow.44*45* In particular; where the traditional MCS lock consists of a tail pointer46* (8 bytes) and needs the next pointer (another 8 bytes) of its own node to47* unlock the next pending (next->locked), we compress both these: {tail,48* next->locked} into a single u32 value.49*50* Since a spinlock disables recursion of its own context and there is a limit51* to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there52* are at most 4 nesting levels, it can be encoded by a 2-bit number. Now53* we can encode the tail by combining the 2-bit nesting level with the cpu54* number. With one byte for the lock value and 3 bytes for the tail, only a55* 32-bit word is now needed. Even though we only need 1 bit for the lock,56* we extend it to a full byte to achieve better performance for architectures57* that support atomic byte write.58*59* We also change the first spinner to spin on the lock bit instead of its60* node; whereby avoiding the need to carry a node from lock to unlock, and61* preserving existing lock API. This also makes the unlock code simpler and62* faster.63*64* N.B. The current implementation only supports architectures that allow65* atomic operations on smaller 8-bit and 16-bit data types.66*67*/6869#include "mcs_spinlock.h"7071/*72* Per-CPU queue node structures; we can never have more than 4 nested73* contexts: task, softirq, hardirq, nmi.74*75* Exactly fits one 64-byte cacheline on a 64-bit architecture.76*77* PV doubles the storage and uses the second cacheline for PV state.78*/79static DEFINE_PER_CPU_ALIGNED(struct qnode, qnodes[_Q_MAX_NODES]);8081/*82* Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for83* all the PV callbacks.84*/8586static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }87static __always_inline void __pv_wait_node(struct mcs_spinlock *node,88struct mcs_spinlock *prev) { }89static __always_inline void __pv_kick_node(struct qspinlock *lock,90struct mcs_spinlock *node) { }91static __always_inline u32 __pv_wait_head_or_lock(struct qspinlock *lock,92struct mcs_spinlock *node)93{ return 0; }9495#define pv_enabled() false9697#define pv_init_node __pv_init_node98#define pv_wait_node __pv_wait_node99#define pv_kick_node __pv_kick_node100#define pv_wait_head_or_lock __pv_wait_head_or_lock101102#ifdef CONFIG_PARAVIRT_SPINLOCKS103#define queued_spin_lock_slowpath native_queued_spin_lock_slowpath104#endif105106#endif /* _GEN_PV_LOCK_SLOWPATH */107108/**109* queued_spin_lock_slowpath - acquire the queued spinlock110* @lock: Pointer to queued spinlock structure111* @val: Current value of the queued spinlock 32-bit word112*113* (queue tail, pending bit, lock value)114*115* fast : slow : unlock116* : :117* uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)118* : | ^--------.------. / :119* : v \ \ | :120* pending : (0,1,1) +--> (0,1,0) \ | :121* : | ^--' | | :122* : v | | :123* uncontended : (n,x,y) +--> (n,0,0) --' | :124* queue : | ^--' | :125* : v | :126* contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' :127* queue : ^--' :128*/129void __lockfunc queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)130{131struct mcs_spinlock *prev, *next, *node;132u32 old, tail;133int idx;134135BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));136137if (pv_enabled())138goto pv_queue;139140if (virt_spin_lock(lock))141return;142143/*144* Wait for in-progress pending->locked hand-overs with a bounded145* number of spins so that we guarantee forward progress.146*147* 0,1,0 -> 0,0,1148*/149if (val == _Q_PENDING_VAL) {150int cnt = _Q_PENDING_LOOPS;151val = atomic_cond_read_relaxed(&lock->val,152(VAL != _Q_PENDING_VAL) || !cnt--);153}154155/*156* If we observe any contention; queue.157*/158if (val & ~_Q_LOCKED_MASK)159goto queue;160161/*162* trylock || pending163*164* 0,0,* -> 0,1,* -> 0,0,1 pending, trylock165*/166val = queued_fetch_set_pending_acquire(lock);167168/*169* If we observe contention, there is a concurrent locker.170*171* Undo and queue; our setting of PENDING might have made the172* n,0,0 -> 0,0,0 transition fail and it will now be waiting173* on @next to become !NULL.174*/175if (unlikely(val & ~_Q_LOCKED_MASK)) {176177/* Undo PENDING if we set it. */178if (!(val & _Q_PENDING_MASK))179clear_pending(lock);180181goto queue;182}183184/*185* We're pending, wait for the owner to go away.186*187* 0,1,1 -> *,1,0188*189* this wait loop must be a load-acquire such that we match the190* store-release that clears the locked bit and create lock191* sequentiality; this is because not all192* clear_pending_set_locked() implementations imply full193* barriers.194*/195if (val & _Q_LOCKED_MASK)196smp_cond_load_acquire(&lock->locked, !VAL);197198/*199* take ownership and clear the pending bit.200*201* 0,1,0 -> 0,0,1202*/203clear_pending_set_locked(lock);204lockevent_inc(lock_pending);205return;206207/*208* End of pending bit optimistic spinning and beginning of MCS209* queuing.210*/211queue:212lockevent_inc(lock_slowpath);213pv_queue:214node = this_cpu_ptr(&qnodes[0].mcs);215idx = node->count++;216tail = encode_tail(smp_processor_id(), idx);217218trace_contention_begin(lock, LCB_F_SPIN);219220/*221* 4 nodes are allocated based on the assumption that there will222* not be nested NMIs taking spinlocks. That may not be true in223* some architectures even though the chance of needing more than224* 4 nodes will still be extremely unlikely. When that happens,225* we fall back to spinning on the lock directly without using226* any MCS node. This is not the most elegant solution, but is227* simple enough.228*/229if (unlikely(idx >= _Q_MAX_NODES)) {230lockevent_inc(lock_no_node);231while (!queued_spin_trylock(lock))232cpu_relax();233goto release;234}235236node = grab_mcs_node(node, idx);237238/*239* Keep counts of non-zero index values:240*/241lockevent_cond_inc(lock_use_node2 + idx - 1, idx);242243/*244* Ensure that we increment the head node->count before initialising245* the actual node. If the compiler is kind enough to reorder these246* stores, then an IRQ could overwrite our assignments.247*/248barrier();249250node->locked = 0;251node->next = NULL;252pv_init_node(node);253254/*255* We touched a (possibly) cold cacheline in the per-cpu queue node;256* attempt the trylock once more in the hope someone let go while we257* weren't watching.258*/259if (queued_spin_trylock(lock))260goto release;261262/*263* Ensure that the initialisation of @node is complete before we264* publish the updated tail via xchg_tail() and potentially link265* @node into the waitqueue via WRITE_ONCE(prev->next, node) below.266*/267smp_wmb();268269/*270* Publish the updated tail.271* We have already touched the queueing cacheline; don't bother with272* pending stuff.273*274* p,*,* -> n,*,*275*/276old = xchg_tail(lock, tail);277next = NULL;278279/*280* if there was a previous node; link it and wait until reaching the281* head of the waitqueue.282*/283if (old & _Q_TAIL_MASK) {284prev = decode_tail(old, qnodes);285286/* Link @node into the waitqueue. */287WRITE_ONCE(prev->next, node);288289pv_wait_node(node, prev);290arch_mcs_spin_lock_contended(&node->locked);291292/*293* While waiting for the MCS lock, the next pointer may have294* been set by another lock waiter. We optimistically load295* the next pointer & prefetch the cacheline for writing296* to reduce latency in the upcoming MCS unlock operation.297*/298next = READ_ONCE(node->next);299if (next)300prefetchw(next);301}302303/*304* we're at the head of the waitqueue, wait for the owner & pending to305* go away.306*307* *,x,y -> *,0,0308*309* this wait loop must use a load-acquire such that we match the310* store-release that clears the locked bit and create lock311* sequentiality; this is because the set_locked() function below312* does not imply a full barrier.313*314* The PV pv_wait_head_or_lock function, if active, will acquire315* the lock and return a non-zero value. So we have to skip the316* atomic_cond_read_acquire() call. As the next PV queue head hasn't317* been designated yet, there is no way for the locked value to become318* _Q_SLOW_VAL. So both the set_locked() and the319* atomic_cmpxchg_relaxed() calls will be safe.320*321* If PV isn't active, 0 will be returned instead.322*323*/324if ((val = pv_wait_head_or_lock(lock, node)))325goto locked;326327val = atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_PENDING_MASK));328329locked:330/*331* claim the lock:332*333* n,0,0 -> 0,0,1 : lock, uncontended334* *,*,0 -> *,*,1 : lock, contended335*336* If the queue head is the only one in the queue (lock value == tail)337* and nobody is pending, clear the tail code and grab the lock.338* Otherwise, we only need to grab the lock.339*/340341/*342* In the PV case we might already have _Q_LOCKED_VAL set, because343* of lock stealing; therefore we must also allow:344*345* n,0,1 -> 0,0,1346*347* Note: at this point: (val & _Q_PENDING_MASK) == 0, because of the348* above wait condition, therefore any concurrent setting of349* PENDING will make the uncontended transition fail.350*/351if ((val & _Q_TAIL_MASK) == tail) {352if (atomic_try_cmpxchg_relaxed(&lock->val, &val, _Q_LOCKED_VAL))353goto release; /* No contention */354}355356/*357* Either somebody is queued behind us or _Q_PENDING_VAL got set358* which will then detect the remaining tail and queue behind us359* ensuring we'll see a @next.360*/361set_locked(lock);362363/*364* contended path; wait for next if not observed yet, release.365*/366if (!next)367next = smp_cond_load_relaxed(&node->next, (VAL));368369arch_mcs_spin_unlock_contended(&next->locked);370pv_kick_node(lock, next);371372release:373trace_contention_end(lock, 0);374375/*376* release the node377*/378__this_cpu_dec(qnodes[0].mcs.count);379}380EXPORT_SYMBOL(queued_spin_lock_slowpath);381382/*383* Generate the paravirt code for queued_spin_unlock_slowpath().384*/385#if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)386#define _GEN_PV_LOCK_SLOWPATH387388#undef pv_enabled389#define pv_enabled() true390391#undef pv_init_node392#undef pv_wait_node393#undef pv_kick_node394#undef pv_wait_head_or_lock395396#undef queued_spin_lock_slowpath397#define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath398399#include "qspinlock_paravirt.h"400#include "qspinlock.c"401402bool nopvspin;403static __init int parse_nopvspin(char *arg)404{405nopvspin = true;406return 0;407}408early_param("nopvspin", parse_nopvspin);409#endif410411412