qspinlock.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 <asm/byteorder.h>
  30. #include <asm/qspinlock.h>
  31. /*
  32. * The basic principle of a queue-based spinlock can best be understood
  33. * by studying a classic queue-based spinlock implementation called the
  34. * MCS lock. The paper below provides a good description for this kind
  35. * of lock.
  36. *
  37. * http://www.cise.ufl.edu/tr/DOC/REP-1992-71.pdf
  38. *
  39. * This queued spinlock implementation is based on the MCS lock, however to make
  40. * it fit the 4 bytes we assume spinlock_t to be, and preserve its existing
  41. * API, we must modify it somehow.
  42. *
  43. * In particular; where the traditional MCS lock consists of a tail pointer
  44. * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
  45. * unlock the next pending (next->locked), we compress both these: {tail,
  46. * next->locked} into a single u32 value.
  47. *
  48. * Since a spinlock disables recursion of its own context and there is a limit
  49. * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
  50. * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
  51. * we can encode the tail by combining the 2-bit nesting level with the cpu
  52. * number. With one byte for the lock value and 3 bytes for the tail, only a
  53. * 32-bit word is now needed. Even though we only need 1 bit for the lock,
  54. * we extend it to a full byte to achieve better performance for architectures
  55. * that support atomic byte write.
  56. *
  57. * We also change the first spinner to spin on the lock bit instead of its
  58. * node; whereby avoiding the need to carry a node from lock to unlock, and
  59. * preserving existing lock API. This also makes the unlock code simpler and
  60. * faster.
  61. *
  62. * N.B. The current implementation only supports architectures that allow
  63. * atomic operations on smaller 8-bit and 16-bit data types.
  64. *
  65. */
  66. #include "mcs_spinlock.h"
  67. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  68. #define MAX_NODES 8
  69. #else
  70. #define MAX_NODES 4
  71. #endif
  72. /*
  73. * Per-CPU queue node structures; we can never have more than 4 nested
  74. * contexts: task, softirq, hardirq, nmi.
  75. *
  76. * Exactly fits one 64-byte cacheline on a 64-bit architecture.
  77. *
  78. * PV doubles the storage and uses the second cacheline for PV state.
  79. */
  80. static DEFINE_PER_CPU_ALIGNED(struct mcs_spinlock, mcs_nodes[MAX_NODES]);
  81. /*
  82. * We must be able to distinguish between no-tail and the tail at 0:0,
  83. * therefore increment the cpu number by one.
  84. */
  85. static inline u32 encode_tail(int cpu, int idx)
  86. {
  87. u32 tail;
  88. #ifdef CONFIG_DEBUG_SPINLOCK
  89. BUG_ON(idx > 3);
  90. #endif
  91. tail = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
  92. tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
  93. return tail;
  94. }
  95. static inline struct mcs_spinlock *decode_tail(u32 tail)
  96. {
  97. int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
  98. int idx = (tail & _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
  99. return per_cpu_ptr(&mcs_nodes[idx], cpu);
  100. }
  101. #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
  102. /*
  103. * By using the whole 2nd least significant byte for the pending bit, we
  104. * can allow better optimization of the lock acquisition for the pending
  105. * bit holder.
  106. *
  107. * This internal structure is also used by the set_locked function which
  108. * is not restricted to _Q_PENDING_BITS == 8.
  109. */
  110. struct __qspinlock {
  111. union {
  112. atomic_t val;
  113. #ifdef __LITTLE_ENDIAN
  114. struct {
  115. u8 locked;
  116. u8 pending;
  117. };
  118. struct {
  119. u16 locked_pending;
  120. u16 tail;
  121. };
  122. #else
  123. struct {
  124. u16 tail;
  125. u16 locked_pending;
  126. };
  127. struct {
  128. u8 reserved[2];
  129. u8 pending;
  130. u8 locked;
  131. };
  132. #endif
  133. };
  134. };
  135. #if _Q_PENDING_BITS == 8
  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. struct __qspinlock *l = (void *)lock;
  147. WRITE_ONCE(l->locked_pending, _Q_LOCKED_VAL);
  148. }
  149. /*
  150. * xchg_tail - Put in the new queue tail code word & retrieve previous one
  151. * @lock : Pointer to queued spinlock structure
  152. * @tail : The new queue tail code word
  153. * Return: The previous queue tail code word
  154. *
  155. * xchg(lock, tail)
  156. *
  157. * p,*,* -> n,*,* ; prev = xchg(lock, node)
  158. */
  159. static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
  160. {
  161. struct __qspinlock *l = (void *)lock;
  162. /*
  163. * Use release semantics to make sure that the MCS node is properly
  164. * initialized before changing the tail code.
  165. */
  166. return (u32)xchg_release(&l->tail,
  167. tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
  168. }
  169. #else /* _Q_PENDING_BITS == 8 */
  170. /**
  171. * clear_pending_set_locked - take ownership and clear the pending bit.
  172. * @lock: Pointer to queued spinlock structure
  173. *
  174. * *,1,0 -> *,0,1
  175. */
  176. static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
  177. {
  178. atomic_add(-_Q_PENDING_VAL + _Q_LOCKED_VAL, &lock->val);
  179. }
  180. /**
  181. * xchg_tail - Put in the new queue tail code word & retrieve previous one
  182. * @lock : Pointer to queued spinlock structure
  183. * @tail : The new queue tail code word
  184. * Return: The previous queue tail code word
  185. *
  186. * xchg(lock, tail)
  187. *
  188. * p,*,* -> n,*,* ; prev = xchg(lock, node)
  189. */
  190. static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
  191. {
  192. u32 old, new, val = atomic_read(&lock->val);
  193. for (;;) {
  194. new = (val & _Q_LOCKED_PENDING_MASK) | tail;
  195. /*
  196. * Use release semantics to make sure that the MCS node is
  197. * properly initialized before changing the tail code.
  198. */
  199. old = atomic_cmpxchg_release(&lock->val, val, new);
  200. if (old == val)
  201. break;
  202. val = old;
  203. }
  204. return old;
  205. }
  206. #endif /* _Q_PENDING_BITS == 8 */
  207. /**
  208. * set_locked - Set the lock bit and own the lock
  209. * @lock: Pointer to queued spinlock structure
  210. *
  211. * *,*,0 -> *,0,1
  212. */
  213. static __always_inline void set_locked(struct qspinlock *lock)
  214. {
  215. struct __qspinlock *l = (void *)lock;
  216. WRITE_ONCE(l->locked, _Q_LOCKED_VAL);
  217. }
  218. /*
  219. * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for
  220. * all the PV callbacks.
  221. */
  222. static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }
  223. static __always_inline void __pv_wait_node(struct mcs_spinlock *node,
  224. struct mcs_spinlock *prev) { }
  225. static __always_inline void __pv_kick_node(struct qspinlock *lock,
  226. struct mcs_spinlock *node) { }
  227. static __always_inline u32 __pv_wait_head_or_lock(struct qspinlock *lock,
  228. struct mcs_spinlock *node)
  229. { return 0; }
  230. #define pv_enabled() false
  231. #define pv_init_node __pv_init_node
  232. #define pv_wait_node __pv_wait_node
  233. #define pv_kick_node __pv_kick_node
  234. #define pv_wait_head_or_lock __pv_wait_head_or_lock
  235. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  236. #define queued_spin_lock_slowpath native_queued_spin_lock_slowpath
  237. #endif
  238. /*
  239. * queued_spin_lock_slowpath() can (load-)ACQUIRE the lock before
  240. * issuing an _unordered_ store to set _Q_LOCKED_VAL.
  241. *
  242. * This means that the store can be delayed, but no later than the
  243. * store-release from the unlock. This means that simply observing
  244. * _Q_LOCKED_VAL is not sufficient to determine if the lock is acquired.
  245. *
  246. * There are two paths that can issue the unordered store:
  247. *
  248. * (1) clear_pending_set_locked(): *,1,0 -> *,0,1
  249. *
  250. * (2) set_locked(): t,0,0 -> t,0,1 ; t != 0
  251. * atomic_cmpxchg_relaxed(): t,0,0 -> 0,0,1
  252. *
  253. * However, in both cases we have other !0 state we've set before to queue
  254. * ourseves:
  255. *
  256. * For (1) we have the atomic_cmpxchg_acquire() that set _Q_PENDING_VAL, our
  257. * load is constrained by that ACQUIRE to not pass before that, and thus must
  258. * observe the store.
  259. *
  260. * For (2) we have a more intersting scenario. We enqueue ourselves using
  261. * xchg_tail(), which ends up being a RELEASE. This in itself is not
  262. * sufficient, however that is followed by an smp_cond_acquire() on the same
  263. * word, giving a RELEASE->ACQUIRE ordering. This again constrains our load and
  264. * guarantees we must observe that store.
  265. *
  266. * Therefore both cases have other !0 state that is observable before the
  267. * unordered locked byte store comes through. This means we can use that to
  268. * wait for the lock store, and then wait for an unlock.
  269. */
  270. #ifndef queued_spin_unlock_wait
  271. void queued_spin_unlock_wait(struct qspinlock *lock)
  272. {
  273. u32 val;
  274. for (;;) {
  275. val = atomic_read(&lock->val);
  276. if (!val) /* not locked, we're done */
  277. goto done;
  278. if (val & _Q_LOCKED_MASK) /* locked, go wait for unlock */
  279. break;
  280. /* not locked, but pending, wait until we observe the lock */
  281. cpu_relax();
  282. }
  283. /* any unlock is good */
  284. while (atomic_read(&lock->val) & _Q_LOCKED_MASK)
  285. cpu_relax();
  286. done:
  287. smp_rmb(); /* CTRL + RMB -> ACQUIRE */
  288. }
  289. EXPORT_SYMBOL(queued_spin_unlock_wait);
  290. #endif
  291. #endif /* _GEN_PV_LOCK_SLOWPATH */
  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 queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
  314. {
  315. struct mcs_spinlock *prev, *next, *node;
  316. u32 new, old, tail;
  317. int idx;
  318. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  319. if (pv_enabled())
  320. goto queue;
  321. if (virt_spin_lock(lock))
  322. return;
  323. /*
  324. * wait for in-progress pending->locked hand-overs
  325. *
  326. * 0,1,0 -> 0,0,1
  327. */
  328. if (val == _Q_PENDING_VAL) {
  329. while ((val = atomic_read(&lock->val)) == _Q_PENDING_VAL)
  330. cpu_relax();
  331. }
  332. /*
  333. * trylock || pending
  334. *
  335. * 0,0,0 -> 0,0,1 ; trylock
  336. * 0,0,1 -> 0,1,1 ; pending
  337. */
  338. for (;;) {
  339. /*
  340. * If we observe any contention; queue.
  341. */
  342. if (val & ~_Q_LOCKED_MASK)
  343. goto queue;
  344. new = _Q_LOCKED_VAL;
  345. if (val == new)
  346. new |= _Q_PENDING_VAL;
  347. /*
  348. * Acquire semantic is required here as the function may
  349. * return immediately if the lock was free.
  350. */
  351. old = atomic_cmpxchg_acquire(&lock->val, val, new);
  352. if (old == val)
  353. break;
  354. val = old;
  355. }
  356. /*
  357. * we won the trylock
  358. */
  359. if (new == _Q_LOCKED_VAL)
  360. return;
  361. /*
  362. * we're pending, wait for the owner to go away.
  363. *
  364. * *,1,1 -> *,1,0
  365. *
  366. * this wait loop must be a load-acquire such that we match the
  367. * store-release that clears the locked bit and create lock
  368. * sequentiality; this is because not all clear_pending_set_locked()
  369. * implementations imply full barriers.
  370. */
  371. smp_cond_acquire(!(atomic_read(&lock->val) & _Q_LOCKED_MASK));
  372. /*
  373. * take ownership and clear the pending bit.
  374. *
  375. * *,1,0 -> *,0,1
  376. */
  377. clear_pending_set_locked(lock);
  378. return;
  379. /*
  380. * End of pending bit optimistic spinning and beginning of MCS
  381. * queuing.
  382. */
  383. queue:
  384. node = this_cpu_ptr(&mcs_nodes[0]);
  385. idx = node->count++;
  386. tail = encode_tail(smp_processor_id(), idx);
  387. node += idx;
  388. node->locked = 0;
  389. node->next = NULL;
  390. pv_init_node(node);
  391. /*
  392. * We touched a (possibly) cold cacheline in the per-cpu queue node;
  393. * attempt the trylock once more in the hope someone let go while we
  394. * weren't watching.
  395. */
  396. if (queued_spin_trylock(lock))
  397. goto release;
  398. /*
  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. WRITE_ONCE(prev->next, node);
  413. pv_wait_node(node, prev);
  414. arch_mcs_spin_lock_contended(&node->locked);
  415. /*
  416. * While waiting for the MCS lock, the next pointer may have
  417. * been set by another lock waiter. We optimistically load
  418. * the next pointer & prefetch the cacheline for writing
  419. * to reduce latency in the upcoming MCS unlock operation.
  420. */
  421. next = READ_ONCE(node->next);
  422. if (next)
  423. prefetchw(next);
  424. }
  425. /*
  426. * we're at the head of the waitqueue, wait for the owner & pending to
  427. * go away.
  428. *
  429. * *,x,y -> *,0,0
  430. *
  431. * this wait loop must use a load-acquire such that we match the
  432. * store-release that clears the locked bit and create lock
  433. * sequentiality; this is because the set_locked() function below
  434. * does not imply a full barrier.
  435. *
  436. * The PV pv_wait_head_or_lock function, if active, will acquire
  437. * the lock and return a non-zero value. So we have to skip the
  438. * smp_cond_acquire() call. As the next PV queue head hasn't been
  439. * designated yet, there is no way for the locked value to become
  440. * _Q_SLOW_VAL. So both the set_locked() and the
  441. * atomic_cmpxchg_relaxed() calls will be safe.
  442. *
  443. * If PV isn't active, 0 will be returned instead.
  444. *
  445. */
  446. if ((val = pv_wait_head_or_lock(lock, node)))
  447. goto locked;
  448. smp_cond_acquire(!((val = atomic_read(&lock->val)) & _Q_LOCKED_PENDING_MASK));
  449. locked:
  450. /*
  451. * claim the lock:
  452. *
  453. * n,0,0 -> 0,0,1 : lock, uncontended
  454. * *,0,0 -> *,0,1 : lock, contended
  455. *
  456. * If the queue head is the only one in the queue (lock value == tail),
  457. * clear the tail code and grab the lock. Otherwise, we only need
  458. * to grab the lock.
  459. */
  460. for (;;) {
  461. /* In the PV case we might already have _Q_LOCKED_VAL set */
  462. if ((val & _Q_TAIL_MASK) != tail) {
  463. set_locked(lock);
  464. break;
  465. }
  466. /*
  467. * The smp_cond_acquire() call above has provided the necessary
  468. * acquire semantics required for locking. At most two
  469. * iterations of this loop may be ran.
  470. */
  471. old = atomic_cmpxchg_relaxed(&lock->val, val, _Q_LOCKED_VAL);
  472. if (old == val)
  473. goto release; /* No contention */
  474. val = old;
  475. }
  476. /*
  477. * contended path; wait for next if not observed yet, release.
  478. */
  479. if (!next) {
  480. while (!(next = READ_ONCE(node->next)))
  481. cpu_relax();
  482. }
  483. arch_mcs_spin_unlock_contended(&next->locked);
  484. pv_kick_node(lock, next);
  485. release:
  486. /*
  487. * release the node
  488. */
  489. this_cpu_dec(mcs_nodes[0].count);
  490. }
  491. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  492. /*
  493. * Generate the paravirt code for queued_spin_unlock_slowpath().
  494. */
  495. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  496. #define _GEN_PV_LOCK_SLOWPATH
  497. #undef pv_enabled
  498. #define pv_enabled() true
  499. #undef pv_init_node
  500. #undef pv_wait_node
  501. #undef pv_kick_node
  502. #undef pv_wait_head_or_lock
  503. #undef queued_spin_lock_slowpath
  504. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  505. #include "qspinlock_paravirt.h"
  506. #include "qspinlock.c"
  507. #endif