xref: /linux/kernel/locking/qspinlock.c (revision 63ba5b0fb4f54db256ec43b3062b2606b383055d)
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 statistics code
29  */
30 #include "qspinlock_stat.h"
31 
32 /*
33  * The basic principle of a queue-based spinlock can best be understood
34  * by studying a classic queue-based spinlock implementation called the
35  * MCS lock. A copy of the original MCS lock paper ("Algorithms for Scalable
36  * Synchronization on Shared-Memory Multiprocessors by Mellor-Crummey and
37  * Scott") is available at
38  *
39  * https://bugzilla.kernel.org/show_bug.cgi?id=206115
40  *
41  * This queued spinlock implementation is based on the MCS lock, however to
42  * make it fit the 4 bytes we assume spinlock_t to be, and preserve its
43  * existing API, we must modify it somehow.
44  *
45  * In particular; where the traditional MCS lock consists of a tail pointer
46  * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
47  * 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 limit
51  * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
52  * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
53  * we can encode the tail by combining the 2-bit nesting level with the cpu
54  * number. With one byte for the lock value and 3 bytes for the tail, only a
55  * 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 architectures
57  * that support atomic byte write.
58  *
59  * We also change the first spinner to spin on the lock bit instead of its
60  * node; whereby avoiding the need to carry a node from lock to unlock, and
61  * preserving existing lock API. This also makes the unlock code simpler and
62  * faster.
63  *
64  * N.B. The current implementation only supports architectures that allow
65  *      atomic operations on smaller 8-bit and 16-bit data types.
66  *
67  */
68 
69 #include "mcs_spinlock.h"
70 #define MAX_NODES	4
71 
72 /*
73  * On 64-bit architectures, the mcs_spinlock structure will be 16 bytes in
74  * size and four of them will fit nicely in one 64-byte cacheline. For
75  * pvqspinlock, however, we need more space for extra data. To accommodate
76  * that, we insert two more long words to pad it up to 32 bytes. IOW, only
77  * two of them can fit in a cacheline in this case. That is OK as it is rare
78  * to have more than 2 levels of slowpath nesting in actual use. We don't
79  * want to penalize pvqspinlocks to optimize for a rare case in native
80  * qspinlocks.
81  */
82 struct qnode {
83 	struct mcs_spinlock mcs;
84 #ifdef CONFIG_PARAVIRT_SPINLOCKS
85 	long reserved[2];
86 #endif
87 };
88 
89 /*
90  * The pending bit spinning loop count.
91  * This heuristic is used to limit the number of lockword accesses
92  * made by atomic_cond_read_relaxed when waiting for the lock to
93  * transition out of the "== _Q_PENDING_VAL" state. We don't spin
94  * indefinitely because there's no guarantee that we'll make forward
95  * progress.
96  */
97 #ifndef _Q_PENDING_LOOPS
98 #define _Q_PENDING_LOOPS	1
99 #endif
100 
101 /*
102  * Per-CPU queue node structures; we can never have more than 4 nested
103  * contexts: task, softirq, hardirq, nmi.
104  *
105  * Exactly fits one 64-byte cacheline on a 64-bit architecture.
106  *
107  * PV doubles the storage and uses the second cacheline for PV state.
108  */
109 static DEFINE_PER_CPU_ALIGNED(struct qnode, qnodes[MAX_NODES]);
110 
111 /*
112  * We must be able to distinguish between no-tail and the tail at 0:0,
113  * therefore increment the cpu number by one.
114  */
115 
116 static inline __pure u32 encode_tail(int cpu, int idx)
117 {
118 	u32 tail;
119 
120 	tail  = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
121 	tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
122 
123 	return tail;
124 }
125 
126 static inline __pure struct mcs_spinlock *decode_tail(u32 tail)
127 {
128 	int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
129 	int idx = (tail &  _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
130 
131 	return per_cpu_ptr(&qnodes[idx].mcs, cpu);
132 }
133 
134 static inline __pure
135 struct mcs_spinlock *grab_mcs_node(struct mcs_spinlock *base, int idx)
136 {
137 	return &((struct qnode *)base + idx)->mcs;
138 }
139 
140 #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
141 
142 #if _Q_PENDING_BITS == 8
143 /**
144  * clear_pending - clear the pending bit.
145  * @lock: Pointer to queued spinlock structure
146  *
147  * *,1,* -> *,0,*
148  */
149 static __always_inline void clear_pending(struct qspinlock *lock)
150 {
151 	WRITE_ONCE(lock->pending, 0);
152 }
153 
154 /**
155  * clear_pending_set_locked - take ownership and clear the pending bit.
156  * @lock: Pointer to queued spinlock structure
157  *
158  * *,1,0 -> *,0,1
159  *
160  * Lock stealing is not allowed if this function is used.
161  */
162 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
163 {
164 	WRITE_ONCE(lock->locked_pending, _Q_LOCKED_VAL);
165 }
166 
167 /*
168  * xchg_tail - Put in the new queue tail code word & retrieve previous one
169  * @lock : Pointer to queued spinlock structure
170  * @tail : The new queue tail code word
171  * Return: The previous queue tail code word
172  *
173  * xchg(lock, tail), which heads an address dependency
174  *
175  * p,*,* -> n,*,* ; prev = xchg(lock, node)
176  */
177 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
178 {
179 	/*
180 	 * We can use relaxed semantics since the caller ensures that the
181 	 * MCS node is properly initialized before updating the tail.
182 	 */
183 	return (u32)xchg_relaxed(&lock->tail,
184 				 tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
185 }
186 
187 #else /* _Q_PENDING_BITS == 8 */
188 
189 /**
190  * clear_pending - clear the pending bit.
191  * @lock: Pointer to queued spinlock structure
192  *
193  * *,1,* -> *,0,*
194  */
195 static __always_inline void clear_pending(struct qspinlock *lock)
196 {
197 	atomic_andnot(_Q_PENDING_VAL, &lock->val);
198 }
199 
200 /**
201  * clear_pending_set_locked - take ownership and clear the pending bit.
202  * @lock: Pointer to queued spinlock structure
203  *
204  * *,1,0 -> *,0,1
205  */
206 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
207 {
208 	atomic_add(-_Q_PENDING_VAL + _Q_LOCKED_VAL, &lock->val);
209 }
210 
211 /**
212  * xchg_tail - Put in the new queue tail code word & retrieve previous one
213  * @lock : Pointer to queued spinlock structure
214  * @tail : The new queue tail code word
215  * Return: The previous queue tail code word
216  *
217  * xchg(lock, tail)
218  *
219  * p,*,* -> n,*,* ; prev = xchg(lock, node)
220  */
221 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
222 {
223 	u32 old, new;
224 
225 	old = atomic_read(&lock->val);
226 	do {
227 		new = (old & _Q_LOCKED_PENDING_MASK) | tail;
228 		/*
229 		 * We can use relaxed semantics since the caller ensures that
230 		 * the MCS node is properly initialized before updating the
231 		 * tail.
232 		 */
233 	} while (!atomic_try_cmpxchg_relaxed(&lock->val, &old, new));
234 
235 	return old;
236 }
237 #endif /* _Q_PENDING_BITS == 8 */
238 
239 /**
240  * queued_fetch_set_pending_acquire - fetch the whole lock value and set pending
241  * @lock : Pointer to queued spinlock structure
242  * Return: The previous lock value
243  *
244  * *,*,* -> *,1,*
245  */
246 #ifndef queued_fetch_set_pending_acquire
247 static __always_inline u32 queued_fetch_set_pending_acquire(struct qspinlock *lock)
248 {
249 	return atomic_fetch_or_acquire(_Q_PENDING_VAL, &lock->val);
250 }
251 #endif
252 
253 /**
254  * set_locked - Set the lock bit and own the lock
255  * @lock: Pointer to queued spinlock structure
256  *
257  * *,*,0 -> *,0,1
258  */
259 static __always_inline void set_locked(struct qspinlock *lock)
260 {
261 	WRITE_ONCE(lock->locked, _Q_LOCKED_VAL);
262 }
263 
264 
265 /*
266  * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for
267  * all the PV callbacks.
268  */
269 
270 static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }
271 static __always_inline void __pv_wait_node(struct mcs_spinlock *node,
272 					   struct mcs_spinlock *prev) { }
273 static __always_inline void __pv_kick_node(struct qspinlock *lock,
274 					   struct mcs_spinlock *node) { }
275 static __always_inline u32  __pv_wait_head_or_lock(struct qspinlock *lock,
276 						   struct mcs_spinlock *node)
277 						   { return 0; }
278 
279 #define pv_enabled()		false
280 
281 #define pv_init_node		__pv_init_node
282 #define pv_wait_node		__pv_wait_node
283 #define pv_kick_node		__pv_kick_node
284 #define pv_wait_head_or_lock	__pv_wait_head_or_lock
285 
286 #ifdef CONFIG_PARAVIRT_SPINLOCKS
287 #define queued_spin_lock_slowpath	native_queued_spin_lock_slowpath
288 #endif
289 
290 #endif /* _GEN_PV_LOCK_SLOWPATH */
291 
292 /**
293  * queued_spin_lock_slowpath - acquire the queued spinlock
294  * @lock: Pointer to queued spinlock structure
295  * @val: Current value of the queued spinlock 32-bit word
296  *
297  * (queue tail, pending bit, lock value)
298  *
299  *              fast     :    slow                                  :    unlock
300  *                       :                                          :
301  * uncontended  (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
302  *                       :       | ^--------.------.             /  :
303  *                       :       v           \      \            |  :
304  * pending               :    (0,1,1) +--> (0,1,0)   \           |  :
305  *                       :       | ^--'              |           |  :
306  *                       :       v                   |           |  :
307  * uncontended           :    (n,x,y) +--> (n,0,0) --'           |  :
308  *   queue               :       | ^--'                          |  :
309  *                       :       v                               |  :
310  * contended             :    (*,x,y) +--> (*,0,0) ---> (*,0,1) -'  :
311  *   queue               :         ^--'                             :
312  */
313 void __lockfunc queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
314 {
315 	struct mcs_spinlock *prev, *next, *node;
316 	u32 old, tail;
317 	int idx;
318 
319 	BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
320 
321 	if (pv_enabled())
322 		goto pv_queue;
323 
324 	if (virt_spin_lock(lock))
325 		return;
326 
327 	/*
328 	 * Wait for in-progress pending->locked hand-overs with a bounded
329 	 * number of spins so that we guarantee forward progress.
330 	 *
331 	 * 0,1,0 -> 0,0,1
332 	 */
333 	if (val == _Q_PENDING_VAL) {
334 		int cnt = _Q_PENDING_LOOPS;
335 		val = atomic_cond_read_relaxed(&lock->val,
336 					       (VAL != _Q_PENDING_VAL) || !cnt--);
337 	}
338 
339 	/*
340 	 * If we observe any contention; queue.
341 	 */
342 	if (val & ~_Q_LOCKED_MASK)
343 		goto queue;
344 
345 	/*
346 	 * trylock || pending
347 	 *
348 	 * 0,0,* -> 0,1,* -> 0,0,1 pending, trylock
349 	 */
350 	val = queued_fetch_set_pending_acquire(lock);
351 
352 	/*
353 	 * If we observe contention, there is a concurrent locker.
354 	 *
355 	 * Undo and queue; our setting of PENDING might have made the
356 	 * n,0,0 -> 0,0,0 transition fail and it will now be waiting
357 	 * on @next to become !NULL.
358 	 */
359 	if (unlikely(val & ~_Q_LOCKED_MASK)) {
360 
361 		/* Undo PENDING if we set it. */
362 		if (!(val & _Q_PENDING_MASK))
363 			clear_pending(lock);
364 
365 		goto queue;
366 	}
367 
368 	/*
369 	 * We're pending, wait for the owner to go away.
370 	 *
371 	 * 0,1,1 -> *,1,0
372 	 *
373 	 * this wait loop must be a load-acquire such that we match the
374 	 * store-release that clears the locked bit and create lock
375 	 * sequentiality; this is because not all
376 	 * clear_pending_set_locked() implementations imply full
377 	 * barriers.
378 	 */
379 	if (val & _Q_LOCKED_MASK)
380 		smp_cond_load_acquire(&lock->locked, !VAL);
381 
382 	/*
383 	 * take ownership and clear the pending bit.
384 	 *
385 	 * 0,1,0 -> 0,0,1
386 	 */
387 	clear_pending_set_locked(lock);
388 	lockevent_inc(lock_pending);
389 	return;
390 
391 	/*
392 	 * End of pending bit optimistic spinning and beginning of MCS
393 	 * queuing.
394 	 */
395 queue:
396 	lockevent_inc(lock_slowpath);
397 pv_queue:
398 	node = this_cpu_ptr(&qnodes[0].mcs);
399 	idx = node->count++;
400 	tail = encode_tail(smp_processor_id(), idx);
401 
402 	trace_contention_begin(lock, LCB_F_SPIN);
403 
404 	/*
405 	 * 4 nodes are allocated based on the assumption that there will
406 	 * not be nested NMIs taking spinlocks. That may not be true in
407 	 * some architectures even though the chance of needing more than
408 	 * 4 nodes will still be extremely unlikely. When that happens,
409 	 * we fall back to spinning on the lock directly without using
410 	 * any MCS node. This is not the most elegant solution, but is
411 	 * simple enough.
412 	 */
413 	if (unlikely(idx >= MAX_NODES)) {
414 		lockevent_inc(lock_no_node);
415 		while (!queued_spin_trylock(lock))
416 			cpu_relax();
417 		goto release;
418 	}
419 
420 	node = grab_mcs_node(node, idx);
421 
422 	/*
423 	 * Keep counts of non-zero index values:
424 	 */
425 	lockevent_cond_inc(lock_use_node2 + idx - 1, idx);
426 
427 	/*
428 	 * Ensure that we increment the head node->count before initialising
429 	 * the actual node. If the compiler is kind enough to reorder these
430 	 * stores, then an IRQ could overwrite our assignments.
431 	 */
432 	barrier();
433 
434 	node->locked = 0;
435 	node->next = NULL;
436 	pv_init_node(node);
437 
438 	/*
439 	 * We touched a (possibly) cold cacheline in the per-cpu queue node;
440 	 * attempt the trylock once more in the hope someone let go while we
441 	 * weren't watching.
442 	 */
443 	if (queued_spin_trylock(lock))
444 		goto release;
445 
446 	/*
447 	 * Ensure that the initialisation of @node is complete before we
448 	 * publish the updated tail via xchg_tail() and potentially link
449 	 * @node into the waitqueue via WRITE_ONCE(prev->next, node) below.
450 	 */
451 	smp_wmb();
452 
453 	/*
454 	 * Publish the updated tail.
455 	 * We have already touched the queueing cacheline; don't bother with
456 	 * pending stuff.
457 	 *
458 	 * p,*,* -> n,*,*
459 	 */
460 	old = xchg_tail(lock, tail);
461 	next = NULL;
462 
463 	/*
464 	 * if there was a previous node; link it and wait until reaching the
465 	 * head of the waitqueue.
466 	 */
467 	if (old & _Q_TAIL_MASK) {
468 		prev = decode_tail(old);
469 
470 		/* Link @node into the waitqueue. */
471 		WRITE_ONCE(prev->next, node);
472 
473 		pv_wait_node(node, prev);
474 		arch_mcs_spin_lock_contended(&node->locked);
475 
476 		/*
477 		 * While waiting for the MCS lock, the next pointer may have
478 		 * been set by another lock waiter. We optimistically load
479 		 * the next pointer & prefetch the cacheline for writing
480 		 * to reduce latency in the upcoming MCS unlock operation.
481 		 */
482 		next = READ_ONCE(node->next);
483 		if (next)
484 			prefetchw(next);
485 	}
486 
487 	/*
488 	 * we're at the head of the waitqueue, wait for the owner & pending to
489 	 * go away.
490 	 *
491 	 * *,x,y -> *,0,0
492 	 *
493 	 * this wait loop must use a load-acquire such that we match the
494 	 * store-release that clears the locked bit and create lock
495 	 * sequentiality; this is because the set_locked() function below
496 	 * does not imply a full barrier.
497 	 *
498 	 * The PV pv_wait_head_or_lock function, if active, will acquire
499 	 * the lock and return a non-zero value. So we have to skip the
500 	 * atomic_cond_read_acquire() call. As the next PV queue head hasn't
501 	 * been designated yet, there is no way for the locked value to become
502 	 * _Q_SLOW_VAL. So both the set_locked() and the
503 	 * atomic_cmpxchg_relaxed() calls will be safe.
504 	 *
505 	 * If PV isn't active, 0 will be returned instead.
506 	 *
507 	 */
508 	if ((val = pv_wait_head_or_lock(lock, node)))
509 		goto locked;
510 
511 	val = atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_PENDING_MASK));
512 
513 locked:
514 	/*
515 	 * claim the lock:
516 	 *
517 	 * n,0,0 -> 0,0,1 : lock, uncontended
518 	 * *,*,0 -> *,*,1 : lock, contended
519 	 *
520 	 * If the queue head is the only one in the queue (lock value == tail)
521 	 * and nobody is pending, clear the tail code and grab the lock.
522 	 * Otherwise, we only need to grab the lock.
523 	 */
524 
525 	/*
526 	 * In the PV case we might already have _Q_LOCKED_VAL set, because
527 	 * of lock stealing; therefore we must also allow:
528 	 *
529 	 * n,0,1 -> 0,0,1
530 	 *
531 	 * Note: at this point: (val & _Q_PENDING_MASK) == 0, because of the
532 	 *       above wait condition, therefore any concurrent setting of
533 	 *       PENDING will make the uncontended transition fail.
534 	 */
535 	if ((val & _Q_TAIL_MASK) == tail) {
536 		if (atomic_try_cmpxchg_relaxed(&lock->val, &val, _Q_LOCKED_VAL))
537 			goto release; /* No contention */
538 	}
539 
540 	/*
541 	 * Either somebody is queued behind us or _Q_PENDING_VAL got set
542 	 * which will then detect the remaining tail and queue behind us
543 	 * ensuring we'll see a @next.
544 	 */
545 	set_locked(lock);
546 
547 	/*
548 	 * contended path; wait for next if not observed yet, release.
549 	 */
550 	if (!next)
551 		next = smp_cond_load_relaxed(&node->next, (VAL));
552 
553 	arch_mcs_spin_unlock_contended(&next->locked);
554 	pv_kick_node(lock, next);
555 
556 release:
557 	trace_contention_end(lock, 0);
558 
559 	/*
560 	 * release the node
561 	 */
562 	__this_cpu_dec(qnodes[0].mcs.count);
563 }
564 EXPORT_SYMBOL(queued_spin_lock_slowpath);
565 
566 /*
567  * Generate the paravirt code for queued_spin_unlock_slowpath().
568  */
569 #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
570 #define _GEN_PV_LOCK_SLOWPATH
571 
572 #undef  pv_enabled
573 #define pv_enabled()	true
574 
575 #undef pv_init_node
576 #undef pv_wait_node
577 #undef pv_kick_node
578 #undef pv_wait_head_or_lock
579 
580 #undef  queued_spin_lock_slowpath
581 #define queued_spin_lock_slowpath	__pv_queued_spin_lock_slowpath
582 
583 #include "qspinlock_paravirt.h"
584 #include "qspinlock.c"
585 
586 bool nopvspin;
587 static __init int parse_nopvspin(char *arg)
588 {
589 	nopvspin = true;
590 	return 0;
591 }
592 early_param("nopvspin", parse_nopvspin);
593 #endif
594