1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Queued spinlock 4 * 5 * (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P. 6 * (C) Copyright 2013-2014,2018 Red Hat, Inc. 7 * (C) Copyright 2015 Intel Corp. 8 * (C) Copyright 2015 Hewlett-Packard Enterprise Development LP 9 * 10 * Authors: Waiman Long <longman@redhat.com> 11 * Peter Zijlstra <peterz@infradead.org> 12 */ 13 14 #ifndef _GEN_PV_LOCK_SLOWPATH 15 16 #include <linux/smp.h> 17 #include <linux/bug.h> 18 #include <linux/cpumask.h> 19 #include <linux/percpu.h> 20 #include <linux/hardirq.h> 21 #include <linux/mutex.h> 22 #include <linux/prefetch.h> 23 #include <asm/byteorder.h> 24 #include <asm/qspinlock.h> 25 #include <trace/events/lock.h> 26 27 /* 28 * Include queued spinlock definitions and statistics code 29 */ 30 #include "qspinlock.h" 31 #include "qspinlock_stat.h" 32 33 /* 34 * The basic principle of a queue-based spinlock can best be understood 35 * by studying a classic queue-based spinlock implementation called the 36 * MCS lock. A copy of the original MCS lock paper ("Algorithms for Scalable 37 * Synchronization on Shared-Memory Multiprocessors by Mellor-Crummey and 38 * Scott") is available at 39 * 40 * https://bugzilla.kernel.org/show_bug.cgi?id=206115 41 * 42 * This queued spinlock implementation is based on the MCS lock, however to 43 * make it fit the 4 bytes we assume spinlock_t to be, and preserve its 44 * existing API, we must modify it somehow. 45 * 46 * In particular; where the traditional MCS lock consists of a tail pointer 47 * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to 48 * unlock the next pending (next->locked), we compress both these: {tail, 49 * next->locked} into a single u32 value. 50 * 51 * Since a spinlock disables recursion of its own context and there is a limit 52 * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there 53 * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now 54 * we can encode the tail by combining the 2-bit nesting level with the cpu 55 * number. With one byte for the lock value and 3 bytes for the tail, only a 56 * 32-bit word is now needed. Even though we only need 1 bit for the lock, 57 * we extend it to a full byte to achieve better performance for architectures 58 * that support atomic byte write. 59 * 60 * We also change the first spinner to spin on the lock bit instead of its 61 * node; whereby avoiding the need to carry a node from lock to unlock, and 62 * preserving existing lock API. This also makes the unlock code simpler and 63 * faster. 64 * 65 * N.B. The current implementation only supports architectures that allow 66 * atomic operations on smaller 8-bit and 16-bit data types. 67 * 68 */ 69 70 #include "mcs_spinlock.h" 71 72 /* 73 * Per-CPU queue node structures; we can never have more than 4 nested 74 * contexts: task, softirq, hardirq, nmi. 75 * 76 * Exactly fits one 64-byte cacheline on a 64-bit architecture. 77 * 78 * PV doubles the storage and uses the second cacheline for PV state. 79 */ 80 static DEFINE_PER_CPU_ALIGNED(struct qnode, qnodes[_Q_MAX_NODES]); 81 82 /* 83 * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for 84 * all the PV callbacks. 85 */ 86 87 static __always_inline void __pv_init_node(struct mcs_spinlock *node) { } 88 static __always_inline void __pv_wait_node(struct mcs_spinlock *node, 89 struct mcs_spinlock *prev) { } 90 static __always_inline void __pv_kick_node(struct qspinlock *lock, 91 struct mcs_spinlock *node) { } 92 static __always_inline u32 __pv_wait_head_or_lock(struct qspinlock *lock, 93 struct mcs_spinlock *node) 94 { return 0; } 95 96 #define pv_enabled() false 97 98 #define pv_init_node __pv_init_node 99 #define pv_wait_node __pv_wait_node 100 #define pv_kick_node __pv_kick_node 101 #define pv_wait_head_or_lock __pv_wait_head_or_lock 102 103 #ifdef CONFIG_PARAVIRT_SPINLOCKS 104 #define queued_spin_lock_slowpath native_queued_spin_lock_slowpath 105 #endif 106 107 #if !defined(queued_spin_unlock) && \ 108 IS_ENABLED(CONFIG_QUEUED_SPINLOCKS_TRACE_CONTENDED_RELEASE) 109 /* 110 * Out-of-line trace-and-release path for queued_spin_unlock(), used when 111 * the contended_release tracepoint is enabled. 112 * 113 * queued_spin_release() is duplicated here on purpose: doing the release 114 * in this function (rather than tracing here and releasing in the caller) 115 * lets queued_spin_unlock() return right after the call, so the 116 * tracepoint-disabled hot path never has to keep lock live across a call 117 * in a callee-saved register. Keep this release in sync with the one in 118 * queued_spin_unlock(). 119 */ 120 void __lockfunc queued_spin_release_traced(struct qspinlock *lock) 121 { 122 if (queued_spin_is_contended(lock)) 123 trace_call__contended_release(lock); 124 queued_spin_release(lock); 125 } 126 EXPORT_SYMBOL(queued_spin_release_traced); 127 #endif 128 129 #endif /* _GEN_PV_LOCK_SLOWPATH */ 130 131 /** 132 * queued_spin_lock_slowpath - acquire the queued spinlock 133 * @lock: Pointer to queued spinlock structure 134 * @val: Current value of the queued spinlock 32-bit word 135 * 136 * (queue tail, pending bit, lock value) 137 * 138 * fast : slow : unlock 139 * : : 140 * uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0) 141 * : | ^--------.------. / : 142 * : v \ \ | : 143 * pending : (0,1,1) +--> (0,1,0) \ | : 144 * : | ^--' | | : 145 * : v | | : 146 * uncontended : (n,x,y) +--> (n,0,0) --' | : 147 * queue : | ^--' | : 148 * : v | : 149 * contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' : 150 * queue : ^--' : 151 */ 152 void __lockfunc queued_spin_lock_slowpath(struct qspinlock *lock, u32 val) 153 { 154 struct mcs_spinlock *prev, *next, *node; 155 u32 old, tail; 156 int idx; 157 158 BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS)); 159 160 if (pv_enabled()) 161 goto pv_queue; 162 163 if (virt_spin_lock(lock)) 164 return; 165 166 /* 167 * Wait for in-progress pending->locked hand-overs with a bounded 168 * number of spins so that we guarantee forward progress. 169 * 170 * 0,1,0 -> 0,0,1 171 */ 172 if (val == _Q_PENDING_VAL) { 173 int cnt = _Q_PENDING_LOOPS; 174 val = atomic_cond_read_relaxed(&lock->val, 175 (VAL != _Q_PENDING_VAL) || !cnt--); 176 } 177 178 /* 179 * If we observe any contention; queue. 180 */ 181 if (val & ~_Q_LOCKED_MASK) 182 goto queue; 183 184 /* 185 * trylock || pending 186 * 187 * 0,0,* -> 0,1,* -> 0,0,1 pending, trylock 188 */ 189 val = queued_fetch_set_pending_acquire(lock); 190 191 /* 192 * If we observe contention, there is a concurrent locker. 193 * 194 * Undo and queue; our setting of PENDING might have made the 195 * n,0,0 -> 0,0,0 transition fail and it will now be waiting 196 * on @next to become !NULL. 197 */ 198 if (unlikely(val & ~_Q_LOCKED_MASK)) { 199 200 /* Undo PENDING if we set it. */ 201 if (!(val & _Q_PENDING_MASK)) 202 clear_pending(lock); 203 204 goto queue; 205 } 206 207 /* 208 * We're pending, wait for the owner to go away. 209 * 210 * 0,1,1 -> *,1,0 211 * 212 * this wait loop must be a load-acquire such that we match the 213 * store-release that clears the locked bit and create lock 214 * sequentiality; this is because not all 215 * clear_pending_set_locked() implementations imply full 216 * barriers. 217 */ 218 if (val & _Q_LOCKED_MASK) 219 smp_cond_load_acquire(&lock->locked, !VAL); 220 221 /* 222 * take ownership and clear the pending bit. 223 * 224 * 0,1,0 -> 0,0,1 225 */ 226 clear_pending_set_locked(lock); 227 lockevent_inc(lock_pending); 228 return; 229 230 /* 231 * End of pending bit optimistic spinning and beginning of MCS 232 * queuing. 233 */ 234 queue: 235 lockevent_inc(lock_slowpath); 236 pv_queue: 237 node = this_cpu_ptr(&qnodes[0].mcs); 238 idx = node->count++; 239 tail = encode_tail(smp_processor_id(), idx); 240 241 trace_contention_begin(lock, LCB_F_SPIN); 242 243 /* 244 * 4 nodes are allocated based on the assumption that there will 245 * not be nested NMIs taking spinlocks. That may not be true in 246 * some architectures even though the chance of needing more than 247 * 4 nodes will still be extremely unlikely. When that happens, 248 * we fall back to spinning on the lock directly without using 249 * any MCS node. This is not the most elegant solution, but is 250 * simple enough. 251 */ 252 if (unlikely(idx >= _Q_MAX_NODES)) { 253 lockevent_inc(lock_no_node); 254 while (!queued_spin_trylock(lock)) 255 cpu_relax(); 256 goto release; 257 } 258 259 node = grab_mcs_node(node, idx); 260 261 /* 262 * Keep counts of non-zero index values: 263 */ 264 lockevent_cond_inc(lock_use_node2 + idx - 1, idx); 265 266 /* 267 * Ensure that we increment the head node->count before initialising 268 * the actual node. If the compiler is kind enough to reorder these 269 * stores, then an IRQ could overwrite our assignments. 270 */ 271 barrier(); 272 273 node->locked = 0; 274 node->next = NULL; 275 pv_init_node(node); 276 277 /* 278 * We touched a (possibly) cold cacheline in the per-cpu queue node; 279 * attempt the trylock once more in the hope someone let go while we 280 * weren't watching. 281 */ 282 if (queued_spin_trylock(lock)) 283 goto release; 284 285 /* 286 * Ensure that the initialisation of @node is complete before we 287 * publish the updated tail via xchg_tail() and potentially link 288 * @node into the waitqueue via WRITE_ONCE(prev->next, node) below. 289 */ 290 smp_wmb(); 291 292 /* 293 * Publish the updated tail. 294 * We have already touched the queueing cacheline; don't bother with 295 * pending stuff. 296 * 297 * p,*,* -> n,*,* 298 */ 299 old = xchg_tail(lock, tail); 300 next = NULL; 301 302 /* 303 * if there was a previous node; link it and wait until reaching the 304 * head of the waitqueue. 305 */ 306 if (old & _Q_TAIL_MASK) { 307 prev = decode_tail(old, qnodes); 308 309 /* Link @node into the waitqueue. */ 310 WRITE_ONCE(prev->next, node); 311 312 pv_wait_node(node, prev); 313 arch_mcs_spin_lock_contended(&node->locked); 314 315 /* 316 * While waiting for the MCS lock, the next pointer may have 317 * been set by another lock waiter. We optimistically load 318 * the next pointer & prefetch the cacheline for writing 319 * to reduce latency in the upcoming MCS unlock operation. 320 */ 321 next = READ_ONCE(node->next); 322 if (next) 323 prefetchw(next); 324 } 325 326 /* 327 * we're at the head of the waitqueue, wait for the owner & pending to 328 * go away. 329 * 330 * *,x,y -> *,0,0 331 * 332 * this wait loop must use a load-acquire such that we match the 333 * store-release that clears the locked bit and create lock 334 * sequentiality; this is because the set_locked() function below 335 * does not imply a full barrier. 336 * 337 * The PV pv_wait_head_or_lock function, if active, will acquire 338 * the lock and return a non-zero value. So we have to skip the 339 * atomic_cond_read_acquire() call. As the next PV queue head hasn't 340 * been designated yet, there is no way for the locked value to become 341 * _Q_SLOW_VAL. So both the set_locked() and the 342 * atomic_cmpxchg_relaxed() calls will be safe. 343 * 344 * If PV isn't active, 0 will be returned instead. 345 * 346 */ 347 if ((val = pv_wait_head_or_lock(lock, node))) 348 goto locked; 349 350 val = atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_PENDING_MASK)); 351 352 locked: 353 /* 354 * claim the lock: 355 * 356 * n,0,0 -> 0,0,1 : lock, uncontended 357 * *,*,0 -> *,*,1 : lock, contended 358 * 359 * If the queue head is the only one in the queue (lock value == tail) 360 * and nobody is pending, clear the tail code and grab the lock. 361 * Otherwise, we only need to grab the lock. 362 */ 363 364 /* 365 * In the PV case we might already have _Q_LOCKED_VAL set, because 366 * of lock stealing; therefore we must also allow: 367 * 368 * n,0,1 -> 0,0,1 369 * 370 * Note: at this point: (val & _Q_PENDING_MASK) == 0, because of the 371 * above wait condition, therefore any concurrent setting of 372 * PENDING will make the uncontended transition fail. 373 */ 374 if ((val & _Q_TAIL_MASK) == tail) { 375 if (atomic_try_cmpxchg_relaxed(&lock->val, &val, _Q_LOCKED_VAL)) 376 goto release; /* No contention */ 377 } 378 379 /* 380 * Either somebody is queued behind us or _Q_PENDING_VAL got set 381 * which will then detect the remaining tail and queue behind us 382 * ensuring we'll see a @next. 383 */ 384 set_locked(lock); 385 386 /* 387 * contended path; wait for next if not observed yet, release. 388 */ 389 if (!next) 390 next = smp_cond_load_relaxed(&node->next, (VAL)); 391 392 arch_mcs_spin_unlock_contended(&next->locked); 393 pv_kick_node(lock, next); 394 395 release: 396 trace_contention_end(lock, 0); 397 398 /* 399 * release the node 400 */ 401 __this_cpu_dec(qnodes[0].mcs.count); 402 } 403 EXPORT_SYMBOL(queued_spin_lock_slowpath); 404 405 /* 406 * Generate the paravirt code for queued_spin_unlock_slowpath(). 407 */ 408 #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS) 409 #define _GEN_PV_LOCK_SLOWPATH 410 411 #undef pv_enabled 412 #define pv_enabled() true 413 414 #undef pv_init_node 415 #undef pv_wait_node 416 #undef pv_kick_node 417 #undef pv_wait_head_or_lock 418 419 #undef queued_spin_lock_slowpath 420 #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath 421 422 #include "qspinlock_paravirt.h" 423 #include "qspinlock.c" 424 425 bool nopvspin; 426 static __init int parse_nopvspin(char *arg) 427 { 428 nopvspin = true; 429 return 0; 430 } 431 early_param("nopvspin", parse_nopvspin); 432 #endif 433