qspinlock.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 Red Hat, Inc.
  16. * (C) Copyright 2015 Intel Corp.
  17. * (C) Copyright 2015 Hewlett-Packard Enterprise Development LP
  18. *
  19. * Authors: Waiman Long <waiman.long@hpe.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. * 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. The paper below provides a good description for this kind
  36. * of lock.
  37. *
  38. * http://www.cise.ufl.edu/tr/DOC/REP-1992-71.pdf
  39. *
  40. * This queued spinlock implementation is based on the MCS lock, however to make
  41. * it fit the 4 bytes we assume spinlock_t to be, and preserve its existing
  42. * API, we must modify it somehow.
  43. *
  44. * In particular; where the traditional MCS lock consists of a tail pointer
  45. * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
  46. * unlock the next pending (next->locked), we compress both these: {tail,
  47. * next->locked} into a single u32 value.
  48. *
  49. * Since a spinlock disables recursion of its own context and there is a limit
  50. * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
  51. * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
  52. * we can encode the tail by combining the 2-bit nesting level with the cpu
  53. * number. With one byte for the lock value and 3 bytes for the tail, only a
  54. * 32-bit word is now needed. Even though we only need 1 bit for the lock,
  55. * we extend it to a full byte to achieve better performance for architectures
  56. * that support atomic byte write.
  57. *
  58. * We also change the first spinner to spin on the lock bit instead of its
  59. * node; whereby avoiding the need to carry a node from lock to unlock, and
  60. * preserving existing lock API. This also makes the unlock code simpler and
  61. * faster.
  62. *
  63. * N.B. The current implementation only supports architectures that allow
  64. * atomic operations on smaller 8-bit and 16-bit data types.
  65. *
  66. */
  67. #include "mcs_spinlock.h"
  68. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  69. #define MAX_NODES 8
  70. #else
  71. #define MAX_NODES 4
  72. #endif
  73. /*
  74. * Per-CPU queue node structures; we can never have more than 4 nested
  75. * contexts: task, softirq, hardirq, nmi.
  76. *
  77. * Exactly fits one 64-byte cacheline on a 64-bit architecture.
  78. *
  79. * PV doubles the storage and uses the second cacheline for PV state.
  80. */
  81. static DEFINE_PER_CPU_ALIGNED(struct mcs_spinlock, mcs_nodes[MAX_NODES]);
  82. /*
  83. * We must be able to distinguish between no-tail and the tail at 0:0,
  84. * therefore increment the cpu number by one.
  85. */
  86. static inline __pure u32 encode_tail(int cpu, int idx)
  87. {
  88. u32 tail;
  89. #ifdef CONFIG_DEBUG_SPINLOCK
  90. BUG_ON(idx > 3);
  91. #endif
  92. tail = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
  93. tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
  94. return tail;
  95. }
  96. static inline __pure struct mcs_spinlock *decode_tail(u32 tail)
  97. {
  98. int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
  99. int idx = (tail & _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
  100. return per_cpu_ptr(&mcs_nodes[idx], cpu);
  101. }
  102. #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
  103. /*
  104. * By using the whole 2nd least significant byte for the pending bit, we
  105. * can allow better optimization of the lock acquisition for the pending
  106. * bit holder.
  107. *
  108. * This internal structure is also used by the set_locked function which
  109. * is not restricted to _Q_PENDING_BITS == 8.
  110. */
  111. struct __qspinlock {
  112. union {
  113. atomic_t val;
  114. #ifdef __LITTLE_ENDIAN
  115. struct {
  116. u8 locked;
  117. u8 pending;
  118. };
  119. struct {
  120. u16 locked_pending;
  121. u16 tail;
  122. };
  123. #else
  124. struct {
  125. u16 tail;
  126. u16 locked_pending;
  127. };
  128. struct {
  129. u8 reserved[2];
  130. u8 pending;
  131. u8 locked;
  132. };
  133. #endif
  134. };
  135. };
  136. #if _Q_PENDING_BITS == 8
  137. /**
  138. * clear_pending_set_locked - take ownership and clear the pending bit.
  139. * @lock: Pointer to queued spinlock structure
  140. *
  141. * *,1,0 -> *,0,1
  142. *
  143. * Lock stealing is not allowed if this function is used.
  144. */
  145. static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
  146. {
  147. struct __qspinlock *l = (void *)lock;
  148. WRITE_ONCE(l->locked_pending, _Q_LOCKED_VAL);
  149. }
  150. /*
  151. * xchg_tail - Put in the new queue tail code word & retrieve previous one
  152. * @lock : Pointer to queued spinlock structure
  153. * @tail : The new queue tail code word
  154. * Return: The previous queue tail code word
  155. *
  156. * xchg(lock, tail)
  157. *
  158. * p,*,* -> n,*,* ; prev = xchg(lock, node)
  159. */
  160. static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
  161. {
  162. struct __qspinlock *l = (void *)lock;
  163. /*
  164. * Use release semantics to make sure that the MCS node is properly
  165. * initialized before changing the tail code.
  166. */
  167. return (u32)xchg_release(&l->tail,
  168. tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
  169. }
  170. #else /* _Q_PENDING_BITS == 8 */
  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. * Use release semantics to make sure that the MCS node is
  198. * properly initialized before changing the tail code.
  199. */
  200. old = atomic_cmpxchg_release(&lock->val, val, new);
  201. if (old == val)
  202. break;
  203. val = old;
  204. }
  205. return old;
  206. }
  207. #endif /* _Q_PENDING_BITS == 8 */
  208. /**
  209. * set_locked - Set the lock bit and own the lock
  210. * @lock: Pointer to queued spinlock structure
  211. *
  212. * *,*,0 -> *,0,1
  213. */
  214. static __always_inline void set_locked(struct qspinlock *lock)
  215. {
  216. struct __qspinlock *l = (void *)lock;
  217. WRITE_ONCE(l->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. /*
  240. * Various notes on spin_is_locked() and spin_unlock_wait(), which are
  241. * 'interesting' functions:
  242. *
  243. * PROBLEM: some architectures have an interesting issue with atomic ACQUIRE
  244. * operations in that the ACQUIRE applies to the LOAD _not_ the STORE (ARM64,
  245. * PPC). Also qspinlock has a similar issue per construction, the setting of
  246. * the locked byte can be unordered acquiring the lock proper.
  247. *
  248. * This gets to be 'interesting' in the following cases, where the /should/s
  249. * end up false because of this issue.
  250. *
  251. *
  252. * CASE 1:
  253. *
  254. * So the spin_is_locked() correctness issue comes from something like:
  255. *
  256. * CPU0 CPU1
  257. *
  258. * global_lock(); local_lock(i)
  259. * spin_lock(&G) spin_lock(&L[i])
  260. * for (i) if (!spin_is_locked(&G)) {
  261. * spin_unlock_wait(&L[i]); smp_acquire__after_ctrl_dep();
  262. * return;
  263. * }
  264. * // deal with fail
  265. *
  266. * Where it is important CPU1 sees G locked or CPU0 sees L[i] locked such
  267. * that there is exclusion between the two critical sections.
  268. *
  269. * The load from spin_is_locked(&G) /should/ be constrained by the ACQUIRE from
  270. * spin_lock(&L[i]), and similarly the load(s) from spin_unlock_wait(&L[i])
  271. * /should/ be constrained by the ACQUIRE from spin_lock(&G).
  272. *
  273. * Similarly, later stuff is constrained by the ACQUIRE from CTRL+RMB.
  274. *
  275. *
  276. * CASE 2:
  277. *
  278. * For spin_unlock_wait() there is a second correctness issue, namely:
  279. *
  280. * CPU0 CPU1
  281. *
  282. * flag = set;
  283. * smp_mb(); spin_lock(&l)
  284. * spin_unlock_wait(&l); if (!flag)
  285. * // add to lockless list
  286. * spin_unlock(&l);
  287. * // iterate lockless list
  288. *
  289. * Which wants to ensure that CPU1 will stop adding bits to the list and CPU0
  290. * will observe the last entry on the list (if spin_unlock_wait() had ACQUIRE
  291. * semantics etc..)
  292. *
  293. * Where flag /should/ be ordered against the locked store of l.
  294. */
  295. /*
  296. * queued_spin_lock_slowpath() can (load-)ACQUIRE the lock before
  297. * issuing an _unordered_ store to set _Q_LOCKED_VAL.
  298. *
  299. * This means that the store can be delayed, but no later than the
  300. * store-release from the unlock. This means that simply observing
  301. * _Q_LOCKED_VAL is not sufficient to determine if the lock is acquired.
  302. *
  303. * There are two paths that can issue the unordered store:
  304. *
  305. * (1) clear_pending_set_locked(): *,1,0 -> *,0,1
  306. *
  307. * (2) set_locked(): t,0,0 -> t,0,1 ; t != 0
  308. * atomic_cmpxchg_relaxed(): t,0,0 -> 0,0,1
  309. *
  310. * However, in both cases we have other !0 state we've set before to queue
  311. * ourseves:
  312. *
  313. * For (1) we have the atomic_cmpxchg_acquire() that set _Q_PENDING_VAL, our
  314. * load is constrained by that ACQUIRE to not pass before that, and thus must
  315. * observe the store.
  316. *
  317. * For (2) we have a more intersting scenario. We enqueue ourselves using
  318. * xchg_tail(), which ends up being a RELEASE. This in itself is not
  319. * sufficient, however that is followed by an smp_cond_acquire() on the same
  320. * word, giving a RELEASE->ACQUIRE ordering. This again constrains our load and
  321. * guarantees we must observe that store.
  322. *
  323. * Therefore both cases have other !0 state that is observable before the
  324. * unordered locked byte store comes through. This means we can use that to
  325. * wait for the lock store, and then wait for an unlock.
  326. */
  327. #ifndef queued_spin_unlock_wait
  328. void queued_spin_unlock_wait(struct qspinlock *lock)
  329. {
  330. u32 val;
  331. for (;;) {
  332. val = atomic_read(&lock->val);
  333. if (!val) /* not locked, we're done */
  334. goto done;
  335. if (val & _Q_LOCKED_MASK) /* locked, go wait for unlock */
  336. break;
  337. /* not locked, but pending, wait until we observe the lock */
  338. cpu_relax();
  339. }
  340. /* any unlock is good */
  341. while (atomic_read(&lock->val) & _Q_LOCKED_MASK)
  342. cpu_relax();
  343. done:
  344. smp_acquire__after_ctrl_dep();
  345. }
  346. EXPORT_SYMBOL(queued_spin_unlock_wait);
  347. #endif
  348. #endif /* _GEN_PV_LOCK_SLOWPATH */
  349. /**
  350. * queued_spin_lock_slowpath - acquire the queued spinlock
  351. * @lock: Pointer to queued spinlock structure
  352. * @val: Current value of the queued spinlock 32-bit word
  353. *
  354. * (queue tail, pending bit, lock value)
  355. *
  356. * fast : slow : unlock
  357. * : :
  358. * uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
  359. * : | ^--------.------. / :
  360. * : v \ \ | :
  361. * pending : (0,1,1) +--> (0,1,0) \ | :
  362. * : | ^--' | | :
  363. * : v | | :
  364. * uncontended : (n,x,y) +--> (n,0,0) --' | :
  365. * queue : | ^--' | :
  366. * : v | :
  367. * contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' :
  368. * queue : ^--' :
  369. */
  370. void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
  371. {
  372. struct mcs_spinlock *prev, *next, *node;
  373. u32 new, old, tail;
  374. int idx;
  375. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  376. if (pv_enabled())
  377. goto queue;
  378. if (virt_spin_lock(lock))
  379. return;
  380. /*
  381. * wait for in-progress pending->locked hand-overs
  382. *
  383. * 0,1,0 -> 0,0,1
  384. */
  385. if (val == _Q_PENDING_VAL) {
  386. while ((val = atomic_read(&lock->val)) == _Q_PENDING_VAL)
  387. cpu_relax();
  388. }
  389. /*
  390. * trylock || pending
  391. *
  392. * 0,0,0 -> 0,0,1 ; trylock
  393. * 0,0,1 -> 0,1,1 ; pending
  394. */
  395. for (;;) {
  396. /*
  397. * If we observe any contention; queue.
  398. */
  399. if (val & ~_Q_LOCKED_MASK)
  400. goto queue;
  401. new = _Q_LOCKED_VAL;
  402. if (val == new)
  403. new |= _Q_PENDING_VAL;
  404. /*
  405. * Acquire semantic is required here as the function may
  406. * return immediately if the lock was free.
  407. */
  408. old = atomic_cmpxchg_acquire(&lock->val, val, new);
  409. if (old == val)
  410. break;
  411. val = old;
  412. }
  413. /*
  414. * we won the trylock
  415. */
  416. if (new == _Q_LOCKED_VAL)
  417. return;
  418. /*
  419. * we're pending, wait for the owner to go away.
  420. *
  421. * *,1,1 -> *,1,0
  422. *
  423. * this wait loop must be a load-acquire such that we match the
  424. * store-release that clears the locked bit and create lock
  425. * sequentiality; this is because not all clear_pending_set_locked()
  426. * implementations imply full barriers.
  427. */
  428. smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_MASK));
  429. /*
  430. * take ownership and clear the pending bit.
  431. *
  432. * *,1,0 -> *,0,1
  433. */
  434. clear_pending_set_locked(lock);
  435. return;
  436. /*
  437. * End of pending bit optimistic spinning and beginning of MCS
  438. * queuing.
  439. */
  440. queue:
  441. node = this_cpu_ptr(&mcs_nodes[0]);
  442. idx = node->count++;
  443. tail = encode_tail(smp_processor_id(), idx);
  444. node += idx;
  445. node->locked = 0;
  446. node->next = NULL;
  447. pv_init_node(node);
  448. /*
  449. * We touched a (possibly) cold cacheline in the per-cpu queue node;
  450. * attempt the trylock once more in the hope someone let go while we
  451. * weren't watching.
  452. */
  453. if (queued_spin_trylock(lock))
  454. goto release;
  455. /*
  456. * We have already touched the queueing cacheline; don't bother with
  457. * pending stuff.
  458. *
  459. * p,*,* -> n,*,*
  460. *
  461. * RELEASE, such that the stores to @node must be complete.
  462. */
  463. old = xchg_tail(lock, tail);
  464. next = NULL;
  465. /*
  466. * if there was a previous node; link it and wait until reaching the
  467. * head of the waitqueue.
  468. */
  469. if (old & _Q_TAIL_MASK) {
  470. prev = decode_tail(old);
  471. /*
  472. * The above xchg_tail() is also a load of @lock which generates,
  473. * through decode_tail(), a pointer.
  474. *
  475. * The address dependency matches the RELEASE of xchg_tail()
  476. * such that the access to @prev must happen after.
  477. */
  478. smp_read_barrier_depends();
  479. WRITE_ONCE(prev->next, node);
  480. pv_wait_node(node, prev);
  481. arch_mcs_spin_lock_contended(&node->locked);
  482. /*
  483. * While waiting for the MCS lock, the next pointer may have
  484. * been set by another lock waiter. We optimistically load
  485. * the next pointer & prefetch the cacheline for writing
  486. * to reduce latency in the upcoming MCS unlock operation.
  487. */
  488. next = READ_ONCE(node->next);
  489. if (next)
  490. prefetchw(next);
  491. }
  492. /*
  493. * we're at the head of the waitqueue, wait for the owner & pending to
  494. * go away.
  495. *
  496. * *,x,y -> *,0,0
  497. *
  498. * this wait loop must use a load-acquire such that we match the
  499. * store-release that clears the locked bit and create lock
  500. * sequentiality; this is because the set_locked() function below
  501. * does not imply a full barrier.
  502. *
  503. * The PV pv_wait_head_or_lock function, if active, will acquire
  504. * the lock and return a non-zero value. So we have to skip the
  505. * smp_cond_load_acquire() call. As the next PV queue head hasn't been
  506. * designated yet, there is no way for the locked value to become
  507. * _Q_SLOW_VAL. So both the set_locked() and the
  508. * atomic_cmpxchg_relaxed() calls will be safe.
  509. *
  510. * If PV isn't active, 0 will be returned instead.
  511. *
  512. */
  513. if ((val = pv_wait_head_or_lock(lock, node)))
  514. goto locked;
  515. val = smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_PENDING_MASK));
  516. locked:
  517. /*
  518. * claim the lock:
  519. *
  520. * n,0,0 -> 0,0,1 : lock, uncontended
  521. * *,0,0 -> *,0,1 : lock, contended
  522. *
  523. * If the queue head is the only one in the queue (lock value == tail),
  524. * clear the tail code and grab the lock. Otherwise, we only need
  525. * to grab the lock.
  526. */
  527. for (;;) {
  528. /* In the PV case we might already have _Q_LOCKED_VAL set */
  529. if ((val & _Q_TAIL_MASK) != tail) {
  530. set_locked(lock);
  531. break;
  532. }
  533. /*
  534. * The smp_cond_load_acquire() call above has provided the
  535. * necessary acquire semantics required for locking. At most
  536. * two iterations of this loop may be ran.
  537. */
  538. old = atomic_cmpxchg_relaxed(&lock->val, val, _Q_LOCKED_VAL);
  539. if (old == val)
  540. goto release; /* No contention */
  541. val = old;
  542. }
  543. /*
  544. * contended path; wait for next if not observed yet, release.
  545. */
  546. if (!next) {
  547. while (!(next = READ_ONCE(node->next)))
  548. cpu_relax();
  549. }
  550. arch_mcs_spin_unlock_contended(&next->locked);
  551. pv_kick_node(lock, next);
  552. release:
  553. /*
  554. * release the node
  555. */
  556. __this_cpu_dec(mcs_nodes[0].count);
  557. }
  558. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  559. /*
  560. * Generate the paravirt code for queued_spin_unlock_slowpath().
  561. */
  562. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  563. #define _GEN_PV_LOCK_SLOWPATH
  564. #undef pv_enabled
  565. #define pv_enabled() true
  566. #undef pv_init_node
  567. #undef pv_wait_node
  568. #undef pv_kick_node
  569. #undef pv_wait_head_or_lock
  570. #undef queued_spin_lock_slowpath
  571. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  572. #include "qspinlock_paravirt.h"
  573. #include "qspinlock.c"
  574. #endif