qspinlock.c 17 KB

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