rwsem-xadd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 <linux/osq_lock.h>
  18. #include "rwsem.h"
  19. /*
  20. * Guide to the rw_semaphore's count field for common values.
  21. * (32-bit case illustrated, similar for 64-bit)
  22. *
  23. * 0x0000000X (1) X readers active or attempting lock, no writer waiting
  24. * X = #active_readers + #readers attempting to lock
  25. * (X*ACTIVE_BIAS)
  26. *
  27. * 0x00000000 rwsem is unlocked, and no one is waiting for the lock or
  28. * attempting to read lock or write lock.
  29. *
  30. * 0xffff000X (1) X readers active or attempting lock, with waiters for lock
  31. * X = #active readers + # readers attempting lock
  32. * (X*ACTIVE_BIAS + WAITING_BIAS)
  33. * (2) 1 writer attempting lock, no waiters for lock
  34. * X-1 = #active readers + #readers attempting lock
  35. * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
  36. * (3) 1 writer active, no waiters for lock
  37. * X-1 = #active readers + #readers attempting lock
  38. * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
  39. *
  40. * 0xffff0001 (1) 1 reader active or attempting lock, waiters for lock
  41. * (WAITING_BIAS + ACTIVE_BIAS)
  42. * (2) 1 writer active or attempting lock, no waiters for lock
  43. * (ACTIVE_WRITE_BIAS)
  44. *
  45. * 0xffff0000 (1) There are writers or readers queued but none active
  46. * or in the process of attempting lock.
  47. * (WAITING_BIAS)
  48. * Note: writer can attempt to steal lock for this count by adding
  49. * ACTIVE_WRITE_BIAS in cmpxchg and checking the old count
  50. *
  51. * 0xfffe0001 (1) 1 writer active, or attempting lock. Waiters on queue.
  52. * (ACTIVE_WRITE_BIAS + WAITING_BIAS)
  53. *
  54. * Note: Readers attempt to lock by adding ACTIVE_BIAS in down_read and checking
  55. * the count becomes more than 0 for successful lock acquisition,
  56. * i.e. the case where there are only readers or nobody has lock.
  57. * (1st and 2nd case above).
  58. *
  59. * Writers attempt to lock by adding ACTIVE_WRITE_BIAS in down_write and
  60. * checking the count becomes ACTIVE_WRITE_BIAS for successful lock
  61. * acquisition (i.e. nobody else has lock or attempts lock). If
  62. * unsuccessful, in rwsem_down_write_failed, we'll check to see if there
  63. * are only waiters but none active (5th case above), and attempt to
  64. * steal the lock.
  65. *
  66. */
  67. /*
  68. * Initialize an rwsem:
  69. */
  70. void __init_rwsem(struct rw_semaphore *sem, const char *name,
  71. struct lock_class_key *key)
  72. {
  73. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  74. /*
  75. * Make sure we are not reinitializing a held semaphore:
  76. */
  77. debug_check_no_locks_freed((void *)sem, sizeof(*sem));
  78. lockdep_init_map(&sem->dep_map, name, key, 0);
  79. #endif
  80. sem->count = RWSEM_UNLOCKED_VALUE;
  81. raw_spin_lock_init(&sem->wait_lock);
  82. INIT_LIST_HEAD(&sem->wait_list);
  83. #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
  84. sem->owner = NULL;
  85. osq_lock_init(&sem->osq);
  86. #endif
  87. }
  88. EXPORT_SYMBOL(__init_rwsem);
  89. enum rwsem_waiter_type {
  90. RWSEM_WAITING_FOR_WRITE,
  91. RWSEM_WAITING_FOR_READ
  92. };
  93. struct rwsem_waiter {
  94. struct list_head list;
  95. struct task_struct *task;
  96. enum rwsem_waiter_type type;
  97. };
  98. enum rwsem_wake_type {
  99. RWSEM_WAKE_ANY, /* Wake whatever's at head of wait list */
  100. RWSEM_WAKE_READERS, /* Wake readers only */
  101. RWSEM_WAKE_READ_OWNED /* Waker thread holds the read lock */
  102. };
  103. /*
  104. * handle the lock release when processes blocked on it that can now run
  105. * - if we come here from up_xxxx(), then:
  106. * - the 'active part' of count (&0x0000ffff) reached 0 (but may have changed)
  107. * - the 'waiting part' of count (&0xffff0000) is -ve (and will still be so)
  108. * - there must be someone on the queue
  109. * - the spinlock must be held by the caller
  110. * - woken process blocks are discarded from the list after having task zeroed
  111. * - writers are only woken if downgrading is false
  112. */
  113. static struct rw_semaphore *
  114. __rwsem_do_wake(struct rw_semaphore *sem, enum rwsem_wake_type wake_type)
  115. {
  116. struct rwsem_waiter *waiter;
  117. struct task_struct *tsk;
  118. struct list_head *next;
  119. long oldcount, woken, loop, adjustment;
  120. waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list);
  121. if (waiter->type == RWSEM_WAITING_FOR_WRITE) {
  122. if (wake_type == RWSEM_WAKE_ANY)
  123. /* Wake writer at the front of the queue, but do not
  124. * grant it the lock yet as we want other writers
  125. * to be able to steal it. Readers, on the other hand,
  126. * will block as they will notice the queued writer.
  127. */
  128. wake_up_process(waiter->task);
  129. goto out;
  130. }
  131. /* Writers might steal the lock before we grant it to the next reader.
  132. * We prefer to do the first reader grant before counting readers
  133. * so we can bail out early if a writer stole the lock.
  134. */
  135. adjustment = 0;
  136. if (wake_type != RWSEM_WAKE_READ_OWNED) {
  137. adjustment = RWSEM_ACTIVE_READ_BIAS;
  138. try_reader_grant:
  139. oldcount = rwsem_atomic_update(adjustment, sem) - adjustment;
  140. if (unlikely(oldcount < RWSEM_WAITING_BIAS)) {
  141. /* A writer stole the lock. Undo our reader grant. */
  142. if (rwsem_atomic_update(-adjustment, sem) &
  143. RWSEM_ACTIVE_MASK)
  144. goto out;
  145. /* Last active locker left. Retry waking readers. */
  146. goto try_reader_grant;
  147. }
  148. }
  149. /* Grant an infinite number of read locks to the readers at the front
  150. * of the queue. Note we increment the 'active part' of the count by
  151. * the number of readers before waking any processes up.
  152. */
  153. woken = 0;
  154. do {
  155. woken++;
  156. if (waiter->list.next == &sem->wait_list)
  157. break;
  158. waiter = list_entry(waiter->list.next,
  159. struct rwsem_waiter, list);
  160. } while (waiter->type != RWSEM_WAITING_FOR_WRITE);
  161. adjustment = woken * RWSEM_ACTIVE_READ_BIAS - adjustment;
  162. if (waiter->type != RWSEM_WAITING_FOR_WRITE)
  163. /* hit end of list above */
  164. adjustment -= RWSEM_WAITING_BIAS;
  165. if (adjustment)
  166. rwsem_atomic_add(adjustment, sem);
  167. next = sem->wait_list.next;
  168. loop = woken;
  169. do {
  170. waiter = list_entry(next, struct rwsem_waiter, list);
  171. next = waiter->list.next;
  172. tsk = waiter->task;
  173. /*
  174. * Make sure we do not wakeup the next reader before
  175. * setting the nil condition to grant the next reader;
  176. * otherwise we could miss the wakeup on the other
  177. * side and end up sleeping again. See the pairing
  178. * in rwsem_down_read_failed().
  179. */
  180. smp_mb();
  181. waiter->task = NULL;
  182. wake_up_process(tsk);
  183. put_task_struct(tsk);
  184. } while (--loop);
  185. sem->wait_list.next = next;
  186. next->prev = &sem->wait_list;
  187. out:
  188. return sem;
  189. }
  190. /*
  191. * Wait for the read lock to be granted
  192. */
  193. __visible
  194. struct rw_semaphore __sched *rwsem_down_read_failed(struct rw_semaphore *sem)
  195. {
  196. long count, adjustment = -RWSEM_ACTIVE_READ_BIAS;
  197. struct rwsem_waiter waiter;
  198. struct task_struct *tsk = current;
  199. /* set up my own style of waitqueue */
  200. waiter.task = tsk;
  201. waiter.type = RWSEM_WAITING_FOR_READ;
  202. get_task_struct(tsk);
  203. raw_spin_lock_irq(&sem->wait_lock);
  204. if (list_empty(&sem->wait_list))
  205. adjustment += RWSEM_WAITING_BIAS;
  206. list_add_tail(&waiter.list, &sem->wait_list);
  207. /* we're now waiting on the lock, but no longer actively locking */
  208. count = rwsem_atomic_update(adjustment, sem);
  209. /* If there are no active locks, wake the front queued process(es).
  210. *
  211. * If there are no writers and we are first in the queue,
  212. * wake our own waiter to join the existing active readers !
  213. */
  214. if (count == RWSEM_WAITING_BIAS ||
  215. (count > RWSEM_WAITING_BIAS &&
  216. adjustment != -RWSEM_ACTIVE_READ_BIAS))
  217. sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
  218. raw_spin_unlock_irq(&sem->wait_lock);
  219. /* wait to be given the lock */
  220. while (true) {
  221. set_task_state(tsk, TASK_UNINTERRUPTIBLE);
  222. if (!waiter.task)
  223. break;
  224. schedule();
  225. }
  226. __set_task_state(tsk, TASK_RUNNING);
  227. return sem;
  228. }
  229. EXPORT_SYMBOL(rwsem_down_read_failed);
  230. static inline bool rwsem_try_write_lock(long count, struct rw_semaphore *sem)
  231. {
  232. /*
  233. * Try acquiring the write lock. Check count first in order
  234. * to reduce unnecessary expensive cmpxchg() operations.
  235. */
  236. if (count == RWSEM_WAITING_BIAS &&
  237. cmpxchg_acquire(&sem->count, RWSEM_WAITING_BIAS,
  238. RWSEM_ACTIVE_WRITE_BIAS) == RWSEM_WAITING_BIAS) {
  239. if (!list_is_singular(&sem->wait_list))
  240. rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
  241. rwsem_set_owner(sem);
  242. return true;
  243. }
  244. return false;
  245. }
  246. #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
  247. /*
  248. * Try to acquire write lock before the writer has been put on wait queue.
  249. */
  250. static inline bool rwsem_try_write_lock_unqueued(struct rw_semaphore *sem)
  251. {
  252. long old, count = READ_ONCE(sem->count);
  253. while (true) {
  254. if (!(count == 0 || count == RWSEM_WAITING_BIAS))
  255. return false;
  256. old = cmpxchg_acquire(&sem->count, count,
  257. count + RWSEM_ACTIVE_WRITE_BIAS);
  258. if (old == count) {
  259. rwsem_set_owner(sem);
  260. return true;
  261. }
  262. count = old;
  263. }
  264. }
  265. static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
  266. {
  267. struct task_struct *owner;
  268. bool ret = true;
  269. if (need_resched())
  270. return false;
  271. rcu_read_lock();
  272. owner = READ_ONCE(sem->owner);
  273. if (!owner) {
  274. long count = READ_ONCE(sem->count);
  275. /*
  276. * If sem->owner is not set, yet we have just recently entered the
  277. * slowpath with the lock being active, then there is a possibility
  278. * reader(s) may have the lock. To be safe, bail spinning in these
  279. * situations.
  280. */
  281. if (count & RWSEM_ACTIVE_MASK)
  282. ret = false;
  283. goto done;
  284. }
  285. ret = owner->on_cpu;
  286. done:
  287. rcu_read_unlock();
  288. return ret;
  289. }
  290. static noinline
  291. bool rwsem_spin_on_owner(struct rw_semaphore *sem, struct task_struct *owner)
  292. {
  293. long count;
  294. rcu_read_lock();
  295. while (sem->owner == owner) {
  296. /*
  297. * Ensure we emit the owner->on_cpu, dereference _after_
  298. * checking sem->owner still matches owner, if that fails,
  299. * owner might point to free()d memory, if it still matches,
  300. * the rcu_read_lock() ensures the memory stays valid.
  301. */
  302. barrier();
  303. /* abort spinning when need_resched or owner is not running */
  304. if (!owner->on_cpu || need_resched()) {
  305. rcu_read_unlock();
  306. return false;
  307. }
  308. cpu_relax_lowlatency();
  309. }
  310. rcu_read_unlock();
  311. if (READ_ONCE(sem->owner))
  312. return true; /* new owner, continue spinning */
  313. /*
  314. * When the owner is not set, the lock could be free or
  315. * held by readers. Check the counter to verify the
  316. * state.
  317. */
  318. count = READ_ONCE(sem->count);
  319. return (count == 0 || count == RWSEM_WAITING_BIAS);
  320. }
  321. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  322. {
  323. struct task_struct *owner;
  324. bool taken = false;
  325. preempt_disable();
  326. /* sem->wait_lock should not be held when doing optimistic spinning */
  327. if (!rwsem_can_spin_on_owner(sem))
  328. goto done;
  329. if (!osq_lock(&sem->osq))
  330. goto done;
  331. while (true) {
  332. owner = READ_ONCE(sem->owner);
  333. if (owner && !rwsem_spin_on_owner(sem, owner))
  334. break;
  335. /* wait_lock will be acquired if write_lock is obtained */
  336. if (rwsem_try_write_lock_unqueued(sem)) {
  337. taken = true;
  338. break;
  339. }
  340. /*
  341. * When there's no owner, we might have preempted between the
  342. * owner acquiring the lock and setting the owner field. If
  343. * we're an RT task that will live-lock because we won't let
  344. * the owner complete.
  345. */
  346. if (!owner && (need_resched() || rt_task(current)))
  347. break;
  348. /*
  349. * The cpu_relax() call is a compiler barrier which forces
  350. * everything in this loop to be re-loaded. We don't need
  351. * memory barriers as we'll eventually observe the right
  352. * values at the cost of a few extra spins.
  353. */
  354. cpu_relax_lowlatency();
  355. }
  356. osq_unlock(&sem->osq);
  357. done:
  358. preempt_enable();
  359. return taken;
  360. }
  361. /*
  362. * Return true if the rwsem has active spinner
  363. */
  364. static inline bool rwsem_has_spinner(struct rw_semaphore *sem)
  365. {
  366. return osq_is_locked(&sem->osq);
  367. }
  368. #else
  369. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  370. {
  371. return false;
  372. }
  373. static inline bool rwsem_has_spinner(struct rw_semaphore *sem)
  374. {
  375. return false;
  376. }
  377. #endif
  378. /*
  379. * Wait until we successfully acquire the write lock
  380. */
  381. __visible
  382. struct rw_semaphore __sched *rwsem_down_write_failed(struct rw_semaphore *sem)
  383. {
  384. long count;
  385. bool waiting = true; /* any queued threads before us */
  386. struct rwsem_waiter waiter;
  387. /* undo write bias from down_write operation, stop active locking */
  388. count = rwsem_atomic_update(-RWSEM_ACTIVE_WRITE_BIAS, sem);
  389. /* do optimistic spinning and steal lock if possible */
  390. if (rwsem_optimistic_spin(sem))
  391. return sem;
  392. /*
  393. * Optimistic spinning failed, proceed to the slowpath
  394. * and block until we can acquire the sem.
  395. */
  396. waiter.task = current;
  397. waiter.type = RWSEM_WAITING_FOR_WRITE;
  398. raw_spin_lock_irq(&sem->wait_lock);
  399. /* account for this before adding a new element to the list */
  400. if (list_empty(&sem->wait_list))
  401. waiting = false;
  402. list_add_tail(&waiter.list, &sem->wait_list);
  403. /* we're now waiting on the lock, but no longer actively locking */
  404. if (waiting) {
  405. count = READ_ONCE(sem->count);
  406. /*
  407. * If there were already threads queued before us and there are
  408. * no active writers, the lock must be read owned; so we try to
  409. * wake any read locks that were queued ahead of us.
  410. */
  411. if (count > RWSEM_WAITING_BIAS)
  412. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READERS);
  413. } else
  414. count = rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
  415. /* wait until we successfully acquire the lock */
  416. set_current_state(TASK_UNINTERRUPTIBLE);
  417. while (true) {
  418. if (rwsem_try_write_lock(count, sem))
  419. break;
  420. raw_spin_unlock_irq(&sem->wait_lock);
  421. /* Block until there are no active lockers. */
  422. do {
  423. schedule();
  424. set_current_state(TASK_UNINTERRUPTIBLE);
  425. } while ((count = sem->count) & RWSEM_ACTIVE_MASK);
  426. raw_spin_lock_irq(&sem->wait_lock);
  427. }
  428. __set_current_state(TASK_RUNNING);
  429. list_del(&waiter.list);
  430. raw_spin_unlock_irq(&sem->wait_lock);
  431. return sem;
  432. }
  433. EXPORT_SYMBOL(rwsem_down_write_failed);
  434. /*
  435. * handle waking up a waiter on the semaphore
  436. * - up_read/up_write has decremented the active part of count if we come here
  437. */
  438. __visible
  439. struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem)
  440. {
  441. unsigned long flags;
  442. /*
  443. * __rwsem_down_write_failed_common(sem)
  444. * rwsem_optimistic_spin(sem)
  445. * osq_unlock(sem->osq)
  446. * ...
  447. * atomic_long_add_return(&sem->count)
  448. *
  449. * - VS -
  450. *
  451. * __up_write()
  452. * if (atomic_long_sub_return_release(&sem->count) < 0)
  453. * rwsem_wake(sem)
  454. * osq_is_locked(&sem->osq)
  455. *
  456. * And __up_write() must observe !osq_is_locked() when it observes the
  457. * atomic_long_add_return() in order to not miss a wakeup.
  458. *
  459. * This boils down to:
  460. *
  461. * [S.rel] X = 1 [RmW] r0 = (Y += 0)
  462. * MB RMB
  463. * [RmW] Y += 1 [L] r1 = X
  464. *
  465. * exists (r0=1 /\ r1=0)
  466. */
  467. smp_rmb();
  468. /*
  469. * If a spinner is present, it is not necessary to do the wakeup.
  470. * Try to do wakeup only if the trylock succeeds to minimize
  471. * spinlock contention which may introduce too much delay in the
  472. * unlock operation.
  473. *
  474. * spinning writer up_write/up_read caller
  475. * --------------- -----------------------
  476. * [S] osq_unlock() [L] osq
  477. * MB RMB
  478. * [RmW] rwsem_try_write_lock() [RmW] spin_trylock(wait_lock)
  479. *
  480. * Here, it is important to make sure that there won't be a missed
  481. * wakeup while the rwsem is free and the only spinning writer goes
  482. * to sleep without taking the rwsem. Even when the spinning writer
  483. * is just going to break out of the waiting loop, it will still do
  484. * a trylock in rwsem_down_write_failed() before sleeping. IOW, if
  485. * rwsem_has_spinner() is true, it will guarantee at least one
  486. * trylock attempt on the rwsem later on.
  487. */
  488. if (rwsem_has_spinner(sem)) {
  489. /*
  490. * The smp_rmb() here is to make sure that the spinner
  491. * state is consulted before reading the wait_lock.
  492. */
  493. smp_rmb();
  494. if (!raw_spin_trylock_irqsave(&sem->wait_lock, flags))
  495. return sem;
  496. goto locked;
  497. }
  498. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  499. locked:
  500. /* do nothing if list empty */
  501. if (!list_empty(&sem->wait_list))
  502. sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
  503. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  504. return sem;
  505. }
  506. EXPORT_SYMBOL(rwsem_wake);
  507. /*
  508. * downgrade a write lock into a read lock
  509. * - caller incremented waiting part of count and discovered it still negative
  510. * - just wake up any readers at the front of the queue
  511. */
  512. __visible
  513. struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem)
  514. {
  515. unsigned long flags;
  516. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  517. /* do nothing if list empty */
  518. if (!list_empty(&sem->wait_list))
  519. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READ_OWNED);
  520. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  521. return sem;
  522. }
  523. EXPORT_SYMBOL(rwsem_downgrade_wake);