qspinlock.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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), which heads an address dependency
  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. #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 new, old, tail;
  265. int idx;
  266. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  267. if (pv_enabled())
  268. goto queue;
  269. if (virt_spin_lock(lock))
  270. return;
  271. /*
  272. * wait for in-progress pending->locked hand-overs
  273. *
  274. * 0,1,0 -> 0,0,1
  275. */
  276. if (val == _Q_PENDING_VAL) {
  277. while ((val = atomic_read(&lock->val)) == _Q_PENDING_VAL)
  278. cpu_relax();
  279. }
  280. /*
  281. * trylock || pending
  282. *
  283. * 0,0,0 -> 0,0,1 ; trylock
  284. * 0,0,1 -> 0,1,1 ; pending
  285. */
  286. for (;;) {
  287. /*
  288. * If we observe any contention; queue.
  289. */
  290. if (val & ~_Q_LOCKED_MASK)
  291. goto queue;
  292. new = _Q_LOCKED_VAL;
  293. if (val == new)
  294. new |= _Q_PENDING_VAL;
  295. /*
  296. * Acquire semantic is required here as the function may
  297. * return immediately if the lock was free.
  298. */
  299. old = atomic_cmpxchg_acquire(&lock->val, val, new);
  300. if (old == val)
  301. break;
  302. val = old;
  303. }
  304. /*
  305. * we won the trylock
  306. */
  307. if (new == _Q_LOCKED_VAL)
  308. return;
  309. /*
  310. * we're pending, wait for the owner to go away.
  311. *
  312. * *,1,1 -> *,1,0
  313. *
  314. * this wait loop must be a load-acquire such that we match the
  315. * store-release that clears the locked bit and create lock
  316. * sequentiality; this is because not all clear_pending_set_locked()
  317. * implementations imply full barriers.
  318. */
  319. smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_MASK));
  320. /*
  321. * take ownership and clear the pending bit.
  322. *
  323. * *,1,0 -> *,0,1
  324. */
  325. clear_pending_set_locked(lock);
  326. return;
  327. /*
  328. * End of pending bit optimistic spinning and beginning of MCS
  329. * queuing.
  330. */
  331. 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. * We have already touched the queueing cacheline; don't bother with
  354. * pending stuff.
  355. *
  356. * p,*,* -> n,*,*
  357. *
  358. * RELEASE, such that the stores to @node must be complete.
  359. */
  360. old = xchg_tail(lock, tail);
  361. next = NULL;
  362. /*
  363. * if there was a previous node; link it and wait until reaching the
  364. * head of the waitqueue.
  365. */
  366. if (old & _Q_TAIL_MASK) {
  367. prev = decode_tail(old);
  368. /*
  369. * We must ensure that the stores to @node are observed before
  370. * the write to prev->next. The address dependency from
  371. * xchg_tail is not sufficient to ensure this because the read
  372. * component of xchg_tail is unordered with respect to the
  373. * initialisation of @node.
  374. */
  375. smp_store_release(&prev->next, node);
  376. pv_wait_node(node, prev);
  377. arch_mcs_spin_lock_contended(&node->locked);
  378. /*
  379. * While waiting for the MCS lock, the next pointer may have
  380. * been set by another lock waiter. We optimistically load
  381. * the next pointer & prefetch the cacheline for writing
  382. * to reduce latency in the upcoming MCS unlock operation.
  383. */
  384. next = READ_ONCE(node->next);
  385. if (next)
  386. prefetchw(next);
  387. }
  388. /*
  389. * we're at the head of the waitqueue, wait for the owner & pending to
  390. * go away.
  391. *
  392. * *,x,y -> *,0,0
  393. *
  394. * this wait loop must use a load-acquire such that we match the
  395. * store-release that clears the locked bit and create lock
  396. * sequentiality; this is because the set_locked() function below
  397. * does not imply a full barrier.
  398. *
  399. * The PV pv_wait_head_or_lock function, if active, will acquire
  400. * the lock and return a non-zero value. So we have to skip the
  401. * smp_cond_load_acquire() call. As the next PV queue head hasn't been
  402. * designated yet, there is no way for the locked value to become
  403. * _Q_SLOW_VAL. So both the set_locked() and the
  404. * atomic_cmpxchg_relaxed() calls will be safe.
  405. *
  406. * If PV isn't active, 0 will be returned instead.
  407. *
  408. */
  409. if ((val = pv_wait_head_or_lock(lock, node)))
  410. goto locked;
  411. val = smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_PENDING_MASK));
  412. locked:
  413. /*
  414. * claim the lock:
  415. *
  416. * n,0,0 -> 0,0,1 : lock, uncontended
  417. * *,0,0 -> *,0,1 : lock, contended
  418. *
  419. * If the queue head is the only one in the queue (lock value == tail),
  420. * clear the tail code and grab the lock. Otherwise, we only need
  421. * to grab the lock.
  422. */
  423. for (;;) {
  424. /* In the PV case we might already have _Q_LOCKED_VAL set */
  425. if ((val & _Q_TAIL_MASK) != tail) {
  426. set_locked(lock);
  427. break;
  428. }
  429. /*
  430. * The smp_cond_load_acquire() call above has provided the
  431. * necessary acquire semantics required for locking. At most
  432. * two iterations of this loop may be ran.
  433. */
  434. old = atomic_cmpxchg_relaxed(&lock->val, val, _Q_LOCKED_VAL);
  435. if (old == val)
  436. goto release; /* No contention */
  437. val = old;
  438. }
  439. /*
  440. * contended path; wait for next if not observed yet, release.
  441. */
  442. if (!next) {
  443. while (!(next = READ_ONCE(node->next)))
  444. cpu_relax();
  445. }
  446. arch_mcs_spin_unlock_contended(&next->locked);
  447. pv_kick_node(lock, next);
  448. release:
  449. /*
  450. * release the node
  451. */
  452. __this_cpu_dec(mcs_nodes[0].count);
  453. }
  454. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  455. /*
  456. * Generate the paravirt code for queued_spin_unlock_slowpath().
  457. */
  458. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  459. #define _GEN_PV_LOCK_SLOWPATH
  460. #undef pv_enabled
  461. #define pv_enabled() true
  462. #undef pv_init_node
  463. #undef pv_wait_node
  464. #undef pv_kick_node
  465. #undef pv_wait_head_or_lock
  466. #undef queued_spin_lock_slowpath
  467. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  468. #include "qspinlock_paravirt.h"
  469. #include "qspinlock.c"
  470. #endif