qspinlock.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*
  2. * Queued spinlock
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
  15. * (C) Copyright 2013-2014,2018 Red Hat, Inc.
  16. * (C) Copyright 2015 Intel Corp.
  17. * (C) Copyright 2015 Hewlett-Packard Enterprise Development LP
  18. *
  19. * Authors: Waiman Long <longman@redhat.com>
  20. * Peter Zijlstra <peterz@infradead.org>
  21. */
  22. #ifndef _GEN_PV_LOCK_SLOWPATH
  23. #include <linux/smp.h>
  24. #include <linux/bug.h>
  25. #include <linux/cpumask.h>
  26. #include <linux/percpu.h>
  27. #include <linux/hardirq.h>
  28. #include <linux/mutex.h>
  29. #include <linux/prefetch.h>
  30. #include <asm/byteorder.h>
  31. #include <asm/qspinlock.h>
  32. /*
  33. * Include queued spinlock statistics code
  34. */
  35. #include "qspinlock_stat.h"
  36. /*
  37. * The basic principle of a queue-based spinlock can best be understood
  38. * by studying a classic queue-based spinlock implementation called the
  39. * MCS lock. The paper below provides a good description for this kind
  40. * of lock.
  41. *
  42. * http://www.cise.ufl.edu/tr/DOC/REP-1992-71.pdf
  43. *
  44. * This queued spinlock implementation is based on the MCS lock, however to make
  45. * it fit the 4 bytes we assume spinlock_t to be, and preserve its existing
  46. * API, we must modify it somehow.
  47. *
  48. * In particular; where the traditional MCS lock consists of a tail pointer
  49. * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
  50. * unlock the next pending (next->locked), we compress both these: {tail,
  51. * next->locked} into a single u32 value.
  52. *
  53. * Since a spinlock disables recursion of its own context and there is a limit
  54. * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
  55. * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
  56. * we can encode the tail by combining the 2-bit nesting level with the cpu
  57. * number. With one byte for the lock value and 3 bytes for the tail, only a
  58. * 32-bit word is now needed. Even though we only need 1 bit for the lock,
  59. * we extend it to a full byte to achieve better performance for architectures
  60. * that support atomic byte write.
  61. *
  62. * We also change the first spinner to spin on the lock bit instead of its
  63. * node; whereby avoiding the need to carry a node from lock to unlock, and
  64. * preserving existing lock API. This also makes the unlock code simpler and
  65. * faster.
  66. *
  67. * N.B. The current implementation only supports architectures that allow
  68. * atomic operations on smaller 8-bit and 16-bit data types.
  69. *
  70. */
  71. #include "mcs_spinlock.h"
  72. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  73. #define MAX_NODES 8
  74. #else
  75. #define MAX_NODES 4
  76. #endif
  77. /*
  78. * The pending bit spinning loop count.
  79. * This heuristic is used to limit the number of lockword accesses
  80. * made by atomic_cond_read_relaxed when waiting for the lock to
  81. * transition out of the "== _Q_PENDING_VAL" state. We don't spin
  82. * indefinitely because there's no guarantee that we'll make forward
  83. * progress.
  84. */
  85. #ifndef _Q_PENDING_LOOPS
  86. #define _Q_PENDING_LOOPS 1
  87. #endif
  88. /*
  89. * Per-CPU queue node structures; we can never have more than 4 nested
  90. * contexts: task, softirq, hardirq, nmi.
  91. *
  92. * Exactly fits one 64-byte cacheline on a 64-bit architecture.
  93. *
  94. * PV doubles the storage and uses the second cacheline for PV state.
  95. */
  96. static DEFINE_PER_CPU_ALIGNED(struct mcs_spinlock, mcs_nodes[MAX_NODES]);
  97. /*
  98. * We must be able to distinguish between no-tail and the tail at 0:0,
  99. * therefore increment the cpu number by one.
  100. */
  101. static inline __pure u32 encode_tail(int cpu, int idx)
  102. {
  103. u32 tail;
  104. #ifdef CONFIG_DEBUG_SPINLOCK
  105. BUG_ON(idx > 3);
  106. #endif
  107. tail = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
  108. tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
  109. return tail;
  110. }
  111. static inline __pure struct mcs_spinlock *decode_tail(u32 tail)
  112. {
  113. int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
  114. int idx = (tail & _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
  115. return per_cpu_ptr(&mcs_nodes[idx], cpu);
  116. }
  117. #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
  118. #if _Q_PENDING_BITS == 8
  119. /**
  120. * clear_pending - clear the pending bit.
  121. * @lock: Pointer to queued spinlock structure
  122. *
  123. * *,1,* -> *,0,*
  124. */
  125. static __always_inline void clear_pending(struct qspinlock *lock)
  126. {
  127. WRITE_ONCE(lock->pending, 0);
  128. }
  129. /**
  130. * clear_pending_set_locked - take ownership and clear the pending bit.
  131. * @lock: Pointer to queued spinlock structure
  132. *
  133. * *,1,0 -> *,0,1
  134. *
  135. * Lock stealing is not allowed if this function is used.
  136. */
  137. static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
  138. {
  139. WRITE_ONCE(lock->locked_pending, _Q_LOCKED_VAL);
  140. }
  141. /*
  142. * xchg_tail - Put in the new queue tail code word & retrieve previous one
  143. * @lock : Pointer to queued spinlock structure
  144. * @tail : The new queue tail code word
  145. * Return: The previous queue tail code word
  146. *
  147. * xchg(lock, tail), which heads an address dependency
  148. *
  149. * p,*,* -> n,*,* ; prev = xchg(lock, node)
  150. */
  151. static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
  152. {
  153. /*
  154. * We can use relaxed semantics since the caller ensures that the
  155. * MCS node is properly initialized before updating the tail.
  156. */
  157. return (u32)xchg_relaxed(&lock->tail,
  158. tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
  159. }
  160. #else /* _Q_PENDING_BITS == 8 */
  161. /**
  162. * clear_pending - clear the pending bit.
  163. * @lock: Pointer to queued spinlock structure
  164. *
  165. * *,1,* -> *,0,*
  166. */
  167. static __always_inline void clear_pending(struct qspinlock *lock)
  168. {
  169. atomic_andnot(_Q_PENDING_VAL, &lock->val);
  170. }
  171. /**
  172. * clear_pending_set_locked - take ownership and clear the pending bit.
  173. * @lock: Pointer to queued spinlock structure
  174. *
  175. * *,1,0 -> *,0,1
  176. */
  177. static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
  178. {
  179. atomic_add(-_Q_PENDING_VAL + _Q_LOCKED_VAL, &lock->val);
  180. }
  181. /**
  182. * xchg_tail - Put in the new queue tail code word & retrieve previous one
  183. * @lock : Pointer to queued spinlock structure
  184. * @tail : The new queue tail code word
  185. * Return: The previous queue tail code word
  186. *
  187. * xchg(lock, tail)
  188. *
  189. * p,*,* -> n,*,* ; prev = xchg(lock, node)
  190. */
  191. static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
  192. {
  193. u32 old, new, val = atomic_read(&lock->val);
  194. for (;;) {
  195. new = (val & _Q_LOCKED_PENDING_MASK) | tail;
  196. /*
  197. * We can use relaxed semantics since the caller ensures that
  198. * the MCS node is properly initialized before updating the
  199. * tail.
  200. */
  201. old = atomic_cmpxchg_relaxed(&lock->val, val, new);
  202. if (old == val)
  203. break;
  204. val = old;
  205. }
  206. return old;
  207. }
  208. #endif /* _Q_PENDING_BITS == 8 */
  209. /**
  210. * queued_fetch_set_pending_acquire - fetch the whole lock value and set pending
  211. * @lock : Pointer to queued spinlock structure
  212. * Return: The previous lock value
  213. *
  214. * *,*,* -> *,1,*
  215. */
  216. #ifndef queued_fetch_set_pending_acquire
  217. static __always_inline u32 queued_fetch_set_pending_acquire(struct qspinlock *lock)
  218. {
  219. return atomic_fetch_or_acquire(_Q_PENDING_VAL, &lock->val);
  220. }
  221. #endif
  222. /**
  223. * set_locked - Set the lock bit and own the lock
  224. * @lock: Pointer to queued spinlock structure
  225. *
  226. * *,*,0 -> *,0,1
  227. */
  228. static __always_inline void set_locked(struct qspinlock *lock)
  229. {
  230. WRITE_ONCE(lock->locked, _Q_LOCKED_VAL);
  231. }
  232. /*
  233. * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for
  234. * all the PV callbacks.
  235. */
  236. static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }
  237. static __always_inline void __pv_wait_node(struct mcs_spinlock *node,
  238. struct mcs_spinlock *prev) { }
  239. static __always_inline void __pv_kick_node(struct qspinlock *lock,
  240. struct mcs_spinlock *node) { }
  241. static __always_inline u32 __pv_wait_head_or_lock(struct qspinlock *lock,
  242. struct mcs_spinlock *node)
  243. { return 0; }
  244. #define pv_enabled() false
  245. #define pv_init_node __pv_init_node
  246. #define pv_wait_node __pv_wait_node
  247. #define pv_kick_node __pv_kick_node
  248. #define pv_wait_head_or_lock __pv_wait_head_or_lock
  249. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  250. #define queued_spin_lock_slowpath native_queued_spin_lock_slowpath
  251. #endif
  252. #endif /* _GEN_PV_LOCK_SLOWPATH */
  253. /**
  254. * queued_spin_lock_slowpath - acquire the queued spinlock
  255. * @lock: Pointer to queued spinlock structure
  256. * @val: Current value of the queued spinlock 32-bit word
  257. *
  258. * (queue tail, pending bit, lock value)
  259. *
  260. * fast : slow : unlock
  261. * : :
  262. * uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
  263. * : | ^--------.------. / :
  264. * : v \ \ | :
  265. * pending : (0,1,1) +--> (0,1,0) \ | :
  266. * : | ^--' | | :
  267. * : v | | :
  268. * uncontended : (n,x,y) +--> (n,0,0) --' | :
  269. * queue : | ^--' | :
  270. * : v | :
  271. * contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' :
  272. * queue : ^--' :
  273. */
  274. void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
  275. {
  276. struct mcs_spinlock *prev, *next, *node;
  277. u32 old, tail;
  278. int idx;
  279. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  280. if (pv_enabled())
  281. goto pv_queue;
  282. if (virt_spin_lock(lock))
  283. return;
  284. /*
  285. * Wait for in-progress pending->locked hand-overs with a bounded
  286. * number of spins so that we guarantee forward progress.
  287. *
  288. * 0,1,0 -> 0,0,1
  289. */
  290. if (val == _Q_PENDING_VAL) {
  291. int cnt = _Q_PENDING_LOOPS;
  292. val = atomic_cond_read_relaxed(&lock->val,
  293. (VAL != _Q_PENDING_VAL) || !cnt--);
  294. }
  295. /*
  296. * If we observe any contention; queue.
  297. */
  298. if (val & ~_Q_LOCKED_MASK)
  299. goto queue;
  300. /*
  301. * trylock || pending
  302. *
  303. * 0,0,0 -> 0,0,1 ; trylock
  304. * 0,0,1 -> 0,1,1 ; pending
  305. */
  306. val = queued_fetch_set_pending_acquire(lock);
  307. /*
  308. * If we observe any contention; undo and queue.
  309. */
  310. if (unlikely(val & ~_Q_LOCKED_MASK)) {
  311. if (!(val & _Q_PENDING_MASK))
  312. clear_pending(lock);
  313. goto queue;
  314. }
  315. /*
  316. * We're pending, wait for the owner to go away.
  317. *
  318. * 0,1,1 -> 0,1,0
  319. *
  320. * this wait loop must be a load-acquire such that we match the
  321. * store-release that clears the locked bit and create lock
  322. * sequentiality; this is because not all
  323. * clear_pending_set_locked() implementations imply full
  324. * barriers.
  325. */
  326. if (val & _Q_LOCKED_MASK)
  327. atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_MASK));
  328. /*
  329. * take ownership and clear the pending bit.
  330. *
  331. * 0,1,0 -> 0,0,1
  332. */
  333. clear_pending_set_locked(lock);
  334. qstat_inc(qstat_lock_pending, true);
  335. return;
  336. /*
  337. * End of pending bit optimistic spinning and beginning of MCS
  338. * queuing.
  339. */
  340. queue:
  341. qstat_inc(qstat_lock_slowpath, true);
  342. pv_queue:
  343. node = this_cpu_ptr(&mcs_nodes[0]);
  344. idx = node->count++;
  345. tail = encode_tail(smp_processor_id(), idx);
  346. node += idx;
  347. /*
  348. * Ensure that we increment the head node->count before initialising
  349. * the actual node. If the compiler is kind enough to reorder these
  350. * stores, then an IRQ could overwrite our assignments.
  351. */
  352. barrier();
  353. node->locked = 0;
  354. node->next = NULL;
  355. pv_init_node(node);
  356. /*
  357. * We touched a (possibly) cold cacheline in the per-cpu queue node;
  358. * attempt the trylock once more in the hope someone let go while we
  359. * weren't watching.
  360. */
  361. if (queued_spin_trylock(lock))
  362. goto release;
  363. /*
  364. * Ensure that the initialisation of @node is complete before we
  365. * publish the updated tail via xchg_tail() and potentially link
  366. * @node into the waitqueue via WRITE_ONCE(prev->next, node) below.
  367. */
  368. smp_wmb();
  369. /*
  370. * Publish the updated tail.
  371. * We have already touched the queueing cacheline; don't bother with
  372. * pending stuff.
  373. *
  374. * p,*,* -> n,*,*
  375. */
  376. old = xchg_tail(lock, tail);
  377. next = NULL;
  378. /*
  379. * if there was a previous node; link it and wait until reaching the
  380. * head of the waitqueue.
  381. */
  382. if (old & _Q_TAIL_MASK) {
  383. prev = decode_tail(old);
  384. /* Link @node into the waitqueue. */
  385. WRITE_ONCE(prev->next, node);
  386. pv_wait_node(node, prev);
  387. arch_mcs_spin_lock_contended(&node->locked);
  388. /*
  389. * While waiting for the MCS lock, the next pointer may have
  390. * been set by another lock waiter. We optimistically load
  391. * the next pointer & prefetch the cacheline for writing
  392. * to reduce latency in the upcoming MCS unlock operation.
  393. */
  394. next = READ_ONCE(node->next);
  395. if (next)
  396. prefetchw(next);
  397. }
  398. /*
  399. * we're at the head of the waitqueue, wait for the owner & pending to
  400. * go away.
  401. *
  402. * *,x,y -> *,0,0
  403. *
  404. * this wait loop must use a load-acquire such that we match the
  405. * store-release that clears the locked bit and create lock
  406. * sequentiality; this is because the set_locked() function below
  407. * does not imply a full barrier.
  408. *
  409. * The PV pv_wait_head_or_lock function, if active, will acquire
  410. * the lock and return a non-zero value. So we have to skip the
  411. * atomic_cond_read_acquire() call. As the next PV queue head hasn't
  412. * been designated yet, there is no way for the locked value to become
  413. * _Q_SLOW_VAL. So both the set_locked() and the
  414. * atomic_cmpxchg_relaxed() calls will be safe.
  415. *
  416. * If PV isn't active, 0 will be returned instead.
  417. *
  418. */
  419. if ((val = pv_wait_head_or_lock(lock, node)))
  420. goto locked;
  421. val = atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_PENDING_MASK));
  422. locked:
  423. /*
  424. * claim the lock:
  425. *
  426. * n,0,0 -> 0,0,1 : lock, uncontended
  427. * *,*,0 -> *,*,1 : lock, contended
  428. *
  429. * If the queue head is the only one in the queue (lock value == tail)
  430. * and nobody is pending, clear the tail code and grab the lock.
  431. * Otherwise, we only need to grab the lock.
  432. */
  433. /*
  434. * In the PV case we might already have _Q_LOCKED_VAL set.
  435. *
  436. * The atomic_cond_read_acquire() call above has provided the
  437. * necessary acquire semantics required for locking.
  438. */
  439. if (((val & _Q_TAIL_MASK) == tail) &&
  440. atomic_try_cmpxchg_relaxed(&lock->val, &val, _Q_LOCKED_VAL))
  441. goto release; /* No contention */
  442. /* Either somebody is queued behind us or _Q_PENDING_VAL is set */
  443. set_locked(lock);
  444. /*
  445. * contended path; wait for next if not observed yet, release.
  446. */
  447. if (!next)
  448. next = smp_cond_load_relaxed(&node->next, (VAL));
  449. arch_mcs_spin_unlock_contended(&next->locked);
  450. pv_kick_node(lock, next);
  451. release:
  452. /*
  453. * release the node
  454. */
  455. __this_cpu_dec(mcs_nodes[0].count);
  456. }
  457. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  458. /*
  459. * Generate the paravirt code for queued_spin_unlock_slowpath().
  460. */
  461. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  462. #define _GEN_PV_LOCK_SLOWPATH
  463. #undef pv_enabled
  464. #define pv_enabled() true
  465. #undef pv_init_node
  466. #undef pv_wait_node
  467. #undef pv_kick_node
  468. #undef pv_wait_head_or_lock
  469. #undef queued_spin_lock_slowpath
  470. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  471. #include "qspinlock_paravirt.h"
  472. #include "qspinlock.c"
  473. #endif