rwsem-xadd.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* rwsem.c: R/W semaphores: contention handling functions
  2. *
  3. * Written by David Howells (dhowells@redhat.com).
  4. * Derived from arch/i386/kernel/semaphore.c
  5. *
  6. * Writer lock-stealing by Alex Shi <alex.shi@intel.com>
  7. * and Michel Lespinasse <walken@google.com>
  8. *
  9. * Optimistic spinning by Tim Chen <tim.c.chen@intel.com>
  10. * and Davidlohr Bueso <davidlohr@hp.com>. Based on mutexes.
  11. */
  12. #include <linux/rwsem.h>
  13. #include <linux/sched.h>
  14. #include <linux/init.h>
  15. #include <linux/export.h>
  16. #include <linux/sched/rt.h>
  17. #include "mcs_spinlock.h"
  18. /*
  19. * Guide to the rw_semaphore's count field for common values.
  20. * (32-bit case illustrated, similar for 64-bit)
  21. *
  22. * 0x0000000X (1) X readers active or attempting lock, no writer waiting
  23. * X = #active_readers + #readers attempting to lock
  24. * (X*ACTIVE_BIAS)
  25. *
  26. * 0x00000000 rwsem is unlocked, and no one is waiting for the lock or
  27. * attempting to read lock or write lock.
  28. *
  29. * 0xffff000X (1) X readers active or attempting lock, with waiters for lock
  30. * X = #active readers + # readers attempting lock
  31. * (X*ACTIVE_BIAS + WAITING_BIAS)
  32. * (2) 1 writer attempting lock, no waiters for lock
  33. * X-1 = #active readers + #readers attempting lock
  34. * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
  35. * (3) 1 writer active, no waiters for lock
  36. * X-1 = #active readers + #readers attempting lock
  37. * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
  38. *
  39. * 0xffff0001 (1) 1 reader active or attempting lock, waiters for lock
  40. * (WAITING_BIAS + ACTIVE_BIAS)
  41. * (2) 1 writer active or attempting lock, no waiters for lock
  42. * (ACTIVE_WRITE_BIAS)
  43. *
  44. * 0xffff0000 (1) There are writers or readers queued but none active
  45. * or in the process of attempting lock.
  46. * (WAITING_BIAS)
  47. * Note: writer can attempt to steal lock for this count by adding
  48. * ACTIVE_WRITE_BIAS in cmpxchg and checking the old count
  49. *
  50. * 0xfffe0001 (1) 1 writer active, or attempting lock. Waiters on queue.
  51. * (ACTIVE_WRITE_BIAS + WAITING_BIAS)
  52. *
  53. * Note: Readers attempt to lock by adding ACTIVE_BIAS in down_read and checking
  54. * the count becomes more than 0 for successful lock acquisition,
  55. * i.e. the case where there are only readers or nobody has lock.
  56. * (1st and 2nd case above).
  57. *
  58. * Writers attempt to lock by adding ACTIVE_WRITE_BIAS in down_write and
  59. * checking the count becomes ACTIVE_WRITE_BIAS for successful lock
  60. * acquisition (i.e. nobody else has lock or attempts lock). If
  61. * unsuccessful, in rwsem_down_write_failed, we'll check to see if there
  62. * are only waiters but none active (5th case above), and attempt to
  63. * steal the lock.
  64. *
  65. */
  66. /*
  67. * Initialize an rwsem:
  68. */
  69. void __init_rwsem(struct rw_semaphore *sem, const char *name,
  70. struct lock_class_key *key)
  71. {
  72. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  73. /*
  74. * Make sure we are not reinitializing a held semaphore:
  75. */
  76. debug_check_no_locks_freed((void *)sem, sizeof(*sem));
  77. lockdep_init_map(&sem->dep_map, name, key, 0);
  78. #endif
  79. sem->count = RWSEM_UNLOCKED_VALUE;
  80. raw_spin_lock_init(&sem->wait_lock);
  81. INIT_LIST_HEAD(&sem->wait_list);
  82. #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
  83. sem->owner = NULL;
  84. osq_lock_init(&sem->osq);
  85. #endif
  86. }
  87. EXPORT_SYMBOL(__init_rwsem);
  88. enum rwsem_waiter_type {
  89. RWSEM_WAITING_FOR_WRITE,
  90. RWSEM_WAITING_FOR_READ
  91. };
  92. struct rwsem_waiter {
  93. struct list_head list;
  94. struct task_struct *task;
  95. enum rwsem_waiter_type type;
  96. };
  97. enum rwsem_wake_type {
  98. RWSEM_WAKE_ANY, /* Wake whatever's at head of wait list */
  99. RWSEM_WAKE_READERS, /* Wake readers only */
  100. RWSEM_WAKE_READ_OWNED /* Waker thread holds the read lock */
  101. };
  102. /*
  103. * handle the lock release when processes blocked on it that can now run
  104. * - if we come here from up_xxxx(), then:
  105. * - the 'active part' of count (&0x0000ffff) reached 0 (but may have changed)
  106. * - the 'waiting part' of count (&0xffff0000) is -ve (and will still be so)
  107. * - there must be someone on the queue
  108. * - the spinlock must be held by the caller
  109. * - woken process blocks are discarded from the list after having task zeroed
  110. * - writers are only woken if downgrading is false
  111. */
  112. static struct rw_semaphore *
  113. __rwsem_do_wake(struct rw_semaphore *sem, enum rwsem_wake_type wake_type)
  114. {
  115. struct rwsem_waiter *waiter;
  116. struct task_struct *tsk;
  117. struct list_head *next;
  118. long oldcount, woken, loop, adjustment;
  119. waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list);
  120. if (waiter->type == RWSEM_WAITING_FOR_WRITE) {
  121. if (wake_type == RWSEM_WAKE_ANY)
  122. /* Wake writer at the front of the queue, but do not
  123. * grant it the lock yet as we want other writers
  124. * to be able to steal it. Readers, on the other hand,
  125. * will block as they will notice the queued writer.
  126. */
  127. wake_up_process(waiter->task);
  128. goto out;
  129. }
  130. /* Writers might steal the lock before we grant it to the next reader.
  131. * We prefer to do the first reader grant before counting readers
  132. * so we can bail out early if a writer stole the lock.
  133. */
  134. adjustment = 0;
  135. if (wake_type != RWSEM_WAKE_READ_OWNED) {
  136. adjustment = RWSEM_ACTIVE_READ_BIAS;
  137. try_reader_grant:
  138. oldcount = rwsem_atomic_update(adjustment, sem) - adjustment;
  139. if (unlikely(oldcount < RWSEM_WAITING_BIAS)) {
  140. /* A writer stole the lock. Undo our reader grant. */
  141. if (rwsem_atomic_update(-adjustment, sem) &
  142. RWSEM_ACTIVE_MASK)
  143. goto out;
  144. /* Last active locker left. Retry waking readers. */
  145. goto try_reader_grant;
  146. }
  147. }
  148. /* Grant an infinite number of read locks to the readers at the front
  149. * of the queue. Note we increment the 'active part' of the count by
  150. * the number of readers before waking any processes up.
  151. */
  152. woken = 0;
  153. do {
  154. woken++;
  155. if (waiter->list.next == &sem->wait_list)
  156. break;
  157. waiter = list_entry(waiter->list.next,
  158. struct rwsem_waiter, list);
  159. } while (waiter->type != RWSEM_WAITING_FOR_WRITE);
  160. adjustment = woken * RWSEM_ACTIVE_READ_BIAS - adjustment;
  161. if (waiter->type != RWSEM_WAITING_FOR_WRITE)
  162. /* hit end of list above */
  163. adjustment -= RWSEM_WAITING_BIAS;
  164. if (adjustment)
  165. rwsem_atomic_add(adjustment, sem);
  166. next = sem->wait_list.next;
  167. loop = woken;
  168. do {
  169. waiter = list_entry(next, struct rwsem_waiter, list);
  170. next = waiter->list.next;
  171. tsk = waiter->task;
  172. smp_mb();
  173. waiter->task = NULL;
  174. wake_up_process(tsk);
  175. put_task_struct(tsk);
  176. } while (--loop);
  177. sem->wait_list.next = next;
  178. next->prev = &sem->wait_list;
  179. out:
  180. return sem;
  181. }
  182. /*
  183. * Wait for the read lock to be granted
  184. */
  185. __visible
  186. struct rw_semaphore __sched *rwsem_down_read_failed(struct rw_semaphore *sem)
  187. {
  188. long count, adjustment = -RWSEM_ACTIVE_READ_BIAS;
  189. struct rwsem_waiter waiter;
  190. struct task_struct *tsk = current;
  191. /* set up my own style of waitqueue */
  192. waiter.task = tsk;
  193. waiter.type = RWSEM_WAITING_FOR_READ;
  194. get_task_struct(tsk);
  195. raw_spin_lock_irq(&sem->wait_lock);
  196. if (list_empty(&sem->wait_list))
  197. adjustment += RWSEM_WAITING_BIAS;
  198. list_add_tail(&waiter.list, &sem->wait_list);
  199. /* we're now waiting on the lock, but no longer actively locking */
  200. count = rwsem_atomic_update(adjustment, sem);
  201. /* If there are no active locks, wake the front queued process(es).
  202. *
  203. * If there are no writers and we are first in the queue,
  204. * wake our own waiter to join the existing active readers !
  205. */
  206. if (count == RWSEM_WAITING_BIAS ||
  207. (count > RWSEM_WAITING_BIAS &&
  208. adjustment != -RWSEM_ACTIVE_READ_BIAS))
  209. sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
  210. raw_spin_unlock_irq(&sem->wait_lock);
  211. /* wait to be given the lock */
  212. while (true) {
  213. set_task_state(tsk, TASK_UNINTERRUPTIBLE);
  214. if (!waiter.task)
  215. break;
  216. schedule();
  217. }
  218. __set_task_state(tsk, TASK_RUNNING);
  219. return sem;
  220. }
  221. EXPORT_SYMBOL(rwsem_down_read_failed);
  222. static inline bool rwsem_try_write_lock(long count, struct rw_semaphore *sem)
  223. {
  224. /*
  225. * Try acquiring the write lock. Check count first in order
  226. * to reduce unnecessary expensive cmpxchg() operations.
  227. */
  228. if (count == RWSEM_WAITING_BIAS &&
  229. cmpxchg(&sem->count, RWSEM_WAITING_BIAS,
  230. RWSEM_ACTIVE_WRITE_BIAS) == RWSEM_WAITING_BIAS) {
  231. if (!list_is_singular(&sem->wait_list))
  232. rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
  233. return true;
  234. }
  235. return false;
  236. }
  237. #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
  238. /*
  239. * Try to acquire write lock before the writer has been put on wait queue.
  240. */
  241. static inline bool rwsem_try_write_lock_unqueued(struct rw_semaphore *sem)
  242. {
  243. long old, count = ACCESS_ONCE(sem->count);
  244. while (true) {
  245. if (!(count == 0 || count == RWSEM_WAITING_BIAS))
  246. return false;
  247. old = cmpxchg(&sem->count, count, count + RWSEM_ACTIVE_WRITE_BIAS);
  248. if (old == count)
  249. return true;
  250. count = old;
  251. }
  252. }
  253. static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
  254. {
  255. struct task_struct *owner;
  256. bool on_cpu = false;
  257. if (need_resched())
  258. return false;
  259. rcu_read_lock();
  260. owner = ACCESS_ONCE(sem->owner);
  261. if (owner)
  262. on_cpu = owner->on_cpu;
  263. rcu_read_unlock();
  264. /*
  265. * If sem->owner is not set, yet we have just recently entered the
  266. * slowpath, then there is a possibility reader(s) may have the lock.
  267. * To be safe, avoid spinning in these situations.
  268. */
  269. return on_cpu;
  270. }
  271. static inline bool owner_running(struct rw_semaphore *sem,
  272. struct task_struct *owner)
  273. {
  274. if (sem->owner != owner)
  275. return false;
  276. /*
  277. * Ensure we emit the owner->on_cpu, dereference _after_ checking
  278. * sem->owner still matches owner, if that fails, owner might
  279. * point to free()d memory, if it still matches, the rcu_read_lock()
  280. * ensures the memory stays valid.
  281. */
  282. barrier();
  283. return owner->on_cpu;
  284. }
  285. static noinline
  286. bool rwsem_spin_on_owner(struct rw_semaphore *sem, struct task_struct *owner)
  287. {
  288. rcu_read_lock();
  289. while (owner_running(sem, owner)) {
  290. if (need_resched())
  291. break;
  292. cpu_relax_lowlatency();
  293. }
  294. rcu_read_unlock();
  295. /*
  296. * We break out the loop above on need_resched() or when the
  297. * owner changed, which is a sign for heavy contention. Return
  298. * success only when sem->owner is NULL.
  299. */
  300. return sem->owner == NULL;
  301. }
  302. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  303. {
  304. struct task_struct *owner;
  305. bool taken = false;
  306. preempt_disable();
  307. /* sem->wait_lock should not be held when doing optimistic spinning */
  308. if (!rwsem_can_spin_on_owner(sem))
  309. goto done;
  310. if (!osq_lock(&sem->osq))
  311. goto done;
  312. while (true) {
  313. owner = ACCESS_ONCE(sem->owner);
  314. if (owner && !rwsem_spin_on_owner(sem, owner))
  315. break;
  316. /* wait_lock will be acquired if write_lock is obtained */
  317. if (rwsem_try_write_lock_unqueued(sem)) {
  318. taken = true;
  319. break;
  320. }
  321. /*
  322. * When there's no owner, we might have preempted between the
  323. * owner acquiring the lock and setting the owner field. If
  324. * we're an RT task that will live-lock because we won't let
  325. * the owner complete.
  326. */
  327. if (!owner && (need_resched() || rt_task(current)))
  328. break;
  329. /*
  330. * The cpu_relax() call is a compiler barrier which forces
  331. * everything in this loop to be re-loaded. We don't need
  332. * memory barriers as we'll eventually observe the right
  333. * values at the cost of a few extra spins.
  334. */
  335. cpu_relax_lowlatency();
  336. }
  337. osq_unlock(&sem->osq);
  338. done:
  339. preempt_enable();
  340. return taken;
  341. }
  342. #else
  343. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  344. {
  345. return false;
  346. }
  347. #endif
  348. /*
  349. * Wait until we successfully acquire the write lock
  350. */
  351. __visible
  352. struct rw_semaphore __sched *rwsem_down_write_failed(struct rw_semaphore *sem)
  353. {
  354. long count;
  355. bool waiting = true; /* any queued threads before us */
  356. struct rwsem_waiter waiter;
  357. /* undo write bias from down_write operation, stop active locking */
  358. count = rwsem_atomic_update(-RWSEM_ACTIVE_WRITE_BIAS, sem);
  359. /* do optimistic spinning and steal lock if possible */
  360. if (rwsem_optimistic_spin(sem))
  361. return sem;
  362. /*
  363. * Optimistic spinning failed, proceed to the slowpath
  364. * and block until we can acquire the sem.
  365. */
  366. waiter.task = current;
  367. waiter.type = RWSEM_WAITING_FOR_WRITE;
  368. raw_spin_lock_irq(&sem->wait_lock);
  369. /* account for this before adding a new element to the list */
  370. if (list_empty(&sem->wait_list))
  371. waiting = false;
  372. list_add_tail(&waiter.list, &sem->wait_list);
  373. /* we're now waiting on the lock, but no longer actively locking */
  374. if (waiting) {
  375. count = ACCESS_ONCE(sem->count);
  376. /*
  377. * If there were already threads queued before us and there are
  378. * no active writers, the lock must be read owned; so we try to
  379. * wake any read locks that were queued ahead of us.
  380. */
  381. if (count > RWSEM_WAITING_BIAS)
  382. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READERS);
  383. } else
  384. count = rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
  385. /* wait until we successfully acquire the lock */
  386. set_current_state(TASK_UNINTERRUPTIBLE);
  387. while (true) {
  388. if (rwsem_try_write_lock(count, sem))
  389. break;
  390. raw_spin_unlock_irq(&sem->wait_lock);
  391. /* Block until there are no active lockers. */
  392. do {
  393. schedule();
  394. set_current_state(TASK_UNINTERRUPTIBLE);
  395. } while ((count = sem->count) & RWSEM_ACTIVE_MASK);
  396. raw_spin_lock_irq(&sem->wait_lock);
  397. }
  398. __set_current_state(TASK_RUNNING);
  399. list_del(&waiter.list);
  400. raw_spin_unlock_irq(&sem->wait_lock);
  401. return sem;
  402. }
  403. EXPORT_SYMBOL(rwsem_down_write_failed);
  404. /*
  405. * handle waking up a waiter on the semaphore
  406. * - up_read/up_write has decremented the active part of count if we come here
  407. */
  408. __visible
  409. struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem)
  410. {
  411. unsigned long flags;
  412. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  413. /* do nothing if list empty */
  414. if (!list_empty(&sem->wait_list))
  415. sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
  416. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  417. return sem;
  418. }
  419. EXPORT_SYMBOL(rwsem_wake);
  420. /*
  421. * downgrade a write lock into a read lock
  422. * - caller incremented waiting part of count and discovered it still negative
  423. * - just wake up any readers at the front of the queue
  424. */
  425. __visible
  426. struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem)
  427. {
  428. unsigned long flags;
  429. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  430. /* do nothing if list empty */
  431. if (!list_empty(&sem->wait_list))
  432. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READ_OWNED);
  433. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  434. return sem;
  435. }
  436. EXPORT_SYMBOL(rwsem_downgrade_wake);