qspinlock.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. #endif /* _GEN_PV_LOCK_SLOWPATH */
  239. /**
  240. * queued_spin_lock_slowpath - acquire the queued spinlock
  241. * @lock: Pointer to queued spinlock structure
  242. * @val: Current value of the queued spinlock 32-bit word
  243. *
  244. * (queue tail, pending bit, lock value)
  245. *
  246. * fast : slow : unlock
  247. * : :
  248. * uncontended (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
  249. * : | ^--------.------. / :
  250. * : v \ \ | :
  251. * pending : (0,1,1) +--> (0,1,0) \ | :
  252. * : | ^--' | | :
  253. * : v | | :
  254. * uncontended : (n,x,y) +--> (n,0,0) --' | :
  255. * queue : | ^--' | :
  256. * : v | :
  257. * contended : (*,x,y) +--> (*,0,0) ---> (*,0,1) -' :
  258. * queue : ^--' :
  259. */
  260. void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
  261. {
  262. struct mcs_spinlock *prev, *next, *node;
  263. u32 new, old, tail;
  264. int idx;
  265. BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
  266. if (pv_enabled())
  267. goto queue;
  268. if (virt_spin_lock(lock))
  269. return;
  270. /*
  271. * wait for in-progress pending->locked hand-overs
  272. *
  273. * 0,1,0 -> 0,0,1
  274. */
  275. if (val == _Q_PENDING_VAL) {
  276. while ((val = atomic_read(&lock->val)) == _Q_PENDING_VAL)
  277. cpu_relax();
  278. }
  279. /*
  280. * trylock || pending
  281. *
  282. * 0,0,0 -> 0,0,1 ; trylock
  283. * 0,0,1 -> 0,1,1 ; pending
  284. */
  285. for (;;) {
  286. /*
  287. * If we observe any contention; queue.
  288. */
  289. if (val & ~_Q_LOCKED_MASK)
  290. goto queue;
  291. new = _Q_LOCKED_VAL;
  292. if (val == new)
  293. new |= _Q_PENDING_VAL;
  294. /*
  295. * Acquire semantic is required here as the function may
  296. * return immediately if the lock was free.
  297. */
  298. old = atomic_cmpxchg_acquire(&lock->val, val, new);
  299. if (old == val)
  300. break;
  301. val = old;
  302. }
  303. /*
  304. * we won the trylock
  305. */
  306. if (new == _Q_LOCKED_VAL)
  307. return;
  308. /*
  309. * we're pending, wait for the owner to go away.
  310. *
  311. * *,1,1 -> *,1,0
  312. *
  313. * this wait loop must be a load-acquire such that we match the
  314. * store-release that clears the locked bit and create lock
  315. * sequentiality; this is because not all clear_pending_set_locked()
  316. * implementations imply full barriers.
  317. */
  318. while ((val = smp_load_acquire(&lock->val.counter)) & _Q_LOCKED_MASK)
  319. cpu_relax();
  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. node->locked = 0;
  337. node->next = NULL;
  338. pv_init_node(node);
  339. /*
  340. * We touched a (possibly) cold cacheline in the per-cpu queue node;
  341. * attempt the trylock once more in the hope someone let go while we
  342. * weren't watching.
  343. */
  344. if (queued_spin_trylock(lock))
  345. goto release;
  346. /*
  347. * We have already touched the queueing cacheline; don't bother with
  348. * pending stuff.
  349. *
  350. * p,*,* -> n,*,*
  351. */
  352. old = xchg_tail(lock, tail);
  353. next = NULL;
  354. /*
  355. * if there was a previous node; link it and wait until reaching the
  356. * head of the waitqueue.
  357. */
  358. if (old & _Q_TAIL_MASK) {
  359. prev = decode_tail(old);
  360. WRITE_ONCE(prev->next, node);
  361. pv_wait_node(node, prev);
  362. arch_mcs_spin_lock_contended(&node->locked);
  363. /*
  364. * While waiting for the MCS lock, the next pointer may have
  365. * been set by another lock waiter. We optimistically load
  366. * the next pointer & prefetch the cacheline for writing
  367. * to reduce latency in the upcoming MCS unlock operation.
  368. */
  369. next = READ_ONCE(node->next);
  370. if (next)
  371. prefetchw(next);
  372. }
  373. /*
  374. * we're at the head of the waitqueue, wait for the owner & pending to
  375. * go away.
  376. *
  377. * *,x,y -> *,0,0
  378. *
  379. * this wait loop must use a load-acquire such that we match the
  380. * store-release that clears the locked bit and create lock
  381. * sequentiality; this is because the set_locked() function below
  382. * does not imply a full barrier.
  383. *
  384. * The PV pv_wait_head_or_lock function, if active, will acquire
  385. * the lock and return a non-zero value. So we have to skip the
  386. * smp_load_acquire() call. As the next PV queue head hasn't been
  387. * designated yet, there is no way for the locked value to become
  388. * _Q_SLOW_VAL. So both the set_locked() and the
  389. * atomic_cmpxchg_relaxed() calls will be safe.
  390. *
  391. * If PV isn't active, 0 will be returned instead.
  392. *
  393. */
  394. if ((val = pv_wait_head_or_lock(lock, node)))
  395. goto locked;
  396. smp_cond_acquire(!((val = atomic_read(&lock->val)) & _Q_LOCKED_PENDING_MASK));
  397. locked:
  398. /*
  399. * claim the lock:
  400. *
  401. * n,0,0 -> 0,0,1 : lock, uncontended
  402. * *,0,0 -> *,0,1 : lock, contended
  403. *
  404. * If the queue head is the only one in the queue (lock value == tail),
  405. * clear the tail code and grab the lock. Otherwise, we only need
  406. * to grab the lock.
  407. */
  408. for (;;) {
  409. /* In the PV case we might already have _Q_LOCKED_VAL set */
  410. if ((val & _Q_TAIL_MASK) != tail) {
  411. set_locked(lock);
  412. break;
  413. }
  414. /*
  415. * The smp_load_acquire() call above has provided the necessary
  416. * acquire semantics required for locking. At most two
  417. * iterations of this loop may be ran.
  418. */
  419. old = atomic_cmpxchg_relaxed(&lock->val, val, _Q_LOCKED_VAL);
  420. if (old == val)
  421. goto release; /* No contention */
  422. val = old;
  423. }
  424. /*
  425. * contended path; wait for next if not observed yet, release.
  426. */
  427. if (!next) {
  428. while (!(next = READ_ONCE(node->next)))
  429. cpu_relax();
  430. }
  431. arch_mcs_spin_unlock_contended(&next->locked);
  432. pv_kick_node(lock, next);
  433. release:
  434. /*
  435. * release the node
  436. */
  437. this_cpu_dec(mcs_nodes[0].count);
  438. }
  439. EXPORT_SYMBOL(queued_spin_lock_slowpath);
  440. /*
  441. * Generate the paravirt code for queued_spin_unlock_slowpath().
  442. */
  443. #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
  444. #define _GEN_PV_LOCK_SLOWPATH
  445. #undef pv_enabled
  446. #define pv_enabled() true
  447. #undef pv_init_node
  448. #undef pv_wait_node
  449. #undef pv_kick_node
  450. #undef pv_wait_head_or_lock
  451. #undef queued_spin_lock_slowpath
  452. #define queued_spin_lock_slowpath __pv_queued_spin_lock_slowpath
  453. #include "qspinlock_paravirt.h"
  454. #include "qspinlock.c"
  455. #endif