qspinlock.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. * set_locked - Set the lock bit and own the lock
  211. * @lock: Pointer to queued spinlock structure
  212. *
  213. * *,*,0 -> *,0,1
  214. */
  215. static __always_inline void set_locked(struct qspinlock *lock)
  216. {
  217. WRITE_ONCE(lock->locked, _Q_LOCKED_VAL);
  218. }
  219. /*
  220. * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for
  221. * all the PV callbacks.
  222. */
  223. static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }
  224. static __always_inline void __pv_wait_node(struct mcs_spinlock *node,
  225. struct mcs_spinlock *prev) { }
  226. static __always_inline void __pv_kick_node(struct qspinlock *lock,
  227. struct mcs_spinlock *node) { }
  228. static __always_inline u32 __pv_wait_head_or_lock(struct qspinlock *lock,
  229. struct mcs_spinlock *node)
  230. { return 0; }
  231. #define pv_enabled() false
  232. #define pv_init_node __pv_init_node
  233. #define pv_wait_node __pv_wait_node
  234. #define pv_kick_node __pv_kick_node
  235. #define pv_wait_head_or_lock __pv_wait_head_or_lock
  236. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  237. #define queued_spin_lock_slowpath native_queued_spin_lock_slowpath
  238. #endif
  239. #endif /* _GEN_PV_LOCK_SLOWPATH */
  240. /**
  241. * queued_spin_lock_slowpath - acquire the queued spinlock
  242. * @lock: Pointer to queued spinlock structure
  243. * @val: Current value of the queued spinlock 32-bit word
  244. *
  245. * (queue tail, pending bit, lock value)
  246. *
  247. * fast : slow : unlock
  248. * : :
  249. * uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
  250. * : | ^--------.------. / :
  251. * : v \ \ | :
  252. * pending : (0,1,1) +--> (0,1,0) \ | :
  253. * : | ^--' | | :
  254. * : v | | :
  255. * uncontended : (n,x,y) +--> (n,0,0) --' | :
  256. * queue : | ^--' | :
  257. * : v | :
  258. * contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' :
  259. * queue : ^--' :
  260. */
  261. void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
  262. {
  263. struct mcs_spinlock *prev, *next, *node;
  264. u32 old, tail;
  265. int idx;
  266. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  267. if (pv_enabled())
  268. goto pv_queue;
  269. if (virt_spin_lock(lock))
  270. return;
  271. /*
  272. * Wait for in-progress pending->locked hand-overs with a bounded
  273. * number of spins so that we guarantee forward progress.
  274. *
  275. * 0,1,0 -> 0,0,1
  276. */
  277. if (val == _Q_PENDING_VAL) {
  278. int cnt = _Q_PENDING_LOOPS;
  279. val = atomic_cond_read_relaxed(&lock->val,
  280. (VAL != _Q_PENDING_VAL) || !cnt--);
  281. }
  282. /*
  283. * If we observe any contention; queue.
  284. */
  285. if (val & ~_Q_LOCKED_MASK)
  286. goto queue;
  287. /*
  288. * trylock || pending
  289. *
  290. * 0,0,0 -> 0,0,1 ; trylock
  291. * 0,0,1 -> 0,1,1 ; pending
  292. */
  293. val = atomic_fetch_or_acquire(_Q_PENDING_VAL, &lock->val);
  294. if (!(val & ~_Q_LOCKED_MASK)) {
  295. /*
  296. * We're pending, wait for the owner to go away.
  297. *
  298. * *,1,1 -> *,1,0
  299. *
  300. * this wait loop must be a load-acquire such that we match the
  301. * store-release that clears the locked bit and create lock
  302. * sequentiality; this is because not all
  303. * clear_pending_set_locked() implementations imply full
  304. * barriers.
  305. */
  306. if (val & _Q_LOCKED_MASK) {
  307. atomic_cond_read_acquire(&lock->val,
  308. !(VAL & _Q_LOCKED_MASK));
  309. }
  310. /*
  311. * take ownership and clear the pending bit.
  312. *
  313. * *,1,0 -> *,0,1
  314. */
  315. clear_pending_set_locked(lock);
  316. qstat_inc(qstat_lock_pending, true);
  317. return;
  318. }
  319. /*
  320. * If pending was clear but there are waiters in the queue, then
  321. * we need to undo our setting of pending before we queue ourselves.
  322. */
  323. if (!(val & _Q_PENDING_MASK))
  324. clear_pending(lock);
  325. /*
  326. * End of pending bit optimistic spinning and beginning of MCS
  327. * queuing.
  328. */
  329. queue:
  330. qstat_inc(qstat_lock_slowpath, true);
  331. pv_queue:
  332. node = this_cpu_ptr(&mcs_nodes[0]);
  333. idx = node->count++;
  334. tail = encode_tail(smp_processor_id(), idx);
  335. node += idx;
  336. /*
  337. * Ensure that we increment the head node->count before initialising
  338. * the actual node. If the compiler is kind enough to reorder these
  339. * stores, then an IRQ could overwrite our assignments.
  340. */
  341. barrier();
  342. node->locked = 0;
  343. node->next = NULL;
  344. pv_init_node(node);
  345. /*
  346. * We touched a (possibly) cold cacheline in the per-cpu queue node;
  347. * attempt the trylock once more in the hope someone let go while we
  348. * weren't watching.
  349. */
  350. if (queued_spin_trylock(lock))
  351. goto release;
  352. /*
  353. * Ensure that the initialisation of @node is complete before we
  354. * publish the updated tail via xchg_tail() and potentially link
  355. * @node into the waitqueue via WRITE_ONCE(prev->next, node) below.
  356. */
  357. smp_wmb();
  358. /*
  359. * Publish the updated tail.
  360. * We have already touched the queueing cacheline; don't bother with
  361. * pending stuff.
  362. *
  363. * p,*,* -> n,*,*
  364. */
  365. old = xchg_tail(lock, tail);
  366. next = NULL;
  367. /*
  368. * if there was a previous node; link it and wait until reaching the
  369. * head of the waitqueue.
  370. */
  371. if (old & _Q_TAIL_MASK) {
  372. prev = decode_tail(old);
  373. /* Link @node into the waitqueue. */
  374. WRITE_ONCE(prev->next, node);
  375. pv_wait_node(node, prev);
  376. arch_mcs_spin_lock_contended(&node->locked);
  377. /*
  378. * While waiting for the MCS lock, the next pointer may have
  379. * been set by another lock waiter. We optimistically load
  380. * the next pointer & prefetch the cacheline for writing
  381. * to reduce latency in the upcoming MCS unlock operation.
  382. */
  383. next = READ_ONCE(node->next);
  384. if (next)
  385. prefetchw(next);
  386. }
  387. /*
  388. * we're at the head of the waitqueue, wait for the owner & pending to
  389. * go away.
  390. *
  391. * *,x,y -> *,0,0
  392. *
  393. * this wait loop must use a load-acquire such that we match the
  394. * store-release that clears the locked bit and create lock
  395. * sequentiality; this is because the set_locked() function below
  396. * does not imply a full barrier.
  397. *
  398. * The PV pv_wait_head_or_lock function, if active, will acquire
  399. * the lock and return a non-zero value. So we have to skip the
  400. * atomic_cond_read_acquire() call. As the next PV queue head hasn't
  401. * been designated yet, there is no way for the locked value to become
  402. * _Q_SLOW_VAL. So both the set_locked() and the
  403. * atomic_cmpxchg_relaxed() calls will be safe.
  404. *
  405. * If PV isn't active, 0 will be returned instead.
  406. *
  407. */
  408. if ((val = pv_wait_head_or_lock(lock, node)))
  409. goto locked;
  410. val = atomic_cond_read_acquire(&lock->val, !(VAL & _Q_LOCKED_PENDING_MASK));
  411. locked:
  412. /*
  413. * claim the lock:
  414. *
  415. * n,0,0 -> 0,0,1 : lock, uncontended
  416. * *,*,0 -> *,*,1 : lock, contended
  417. *
  418. * If the queue head is the only one in the queue (lock value == tail)
  419. * and nobody is pending, clear the tail code and grab the lock.
  420. * Otherwise, we only need to grab the lock.
  421. */
  422. /*
  423. * In the PV case we might already have _Q_LOCKED_VAL set.
  424. *
  425. * The atomic_cond_read_acquire() call above has provided the
  426. * necessary acquire semantics required for locking.
  427. */
  428. if (((val & _Q_TAIL_MASK) == tail) &&
  429. atomic_try_cmpxchg_relaxed(&lock->val, &val, _Q_LOCKED_VAL))
  430. goto release; /* No contention */
  431. /* Either somebody is queued behind us or _Q_PENDING_VAL is set */
  432. set_locked(lock);
  433. /*
  434. * contended path; wait for next if not observed yet, release.
  435. */
  436. if (!next)
  437. next = smp_cond_load_relaxed(&node->next, (VAL));
  438. arch_mcs_spin_unlock_contended(&next->locked);
  439. pv_kick_node(lock, next);
  440. release:
  441. /*
  442. * release the node
  443. */
  444. __this_cpu_dec(mcs_nodes[0].count);
  445. }
  446. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  447. /*
  448. * Generate the paravirt code for queued_spin_unlock_slowpath().
  449. */
  450. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  451. #define _GEN_PV_LOCK_SLOWPATH
  452. #undef pv_enabled
  453. #define pv_enabled() true
  454. #undef pv_init_node
  455. #undef pv_wait_node
  456. #undef pv_kick_node
  457. #undef pv_wait_head_or_lock
  458. #undef queued_spin_lock_slowpath
  459. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  460. #include "qspinlock_paravirt.h"
  461. #include "qspinlock.c"
  462. #endif