rwsem-xadd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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(&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(&sem->count, count, count + RWSEM_ACTIVE_WRITE_BIAS);
  257. if (old == count) {
  258. rwsem_set_owner(sem);
  259. return true;
  260. }
  261. count = old;
  262. }
  263. }
  264. static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
  265. {
  266. struct task_struct *owner;
  267. bool ret = true;
  268. if (need_resched())
  269. return false;
  270. rcu_read_lock();
  271. owner = READ_ONCE(sem->owner);
  272. if (!owner) {
  273. long count = READ_ONCE(sem->count);
  274. /*
  275. * If sem->owner is not set, yet we have just recently entered the
  276. * slowpath with the lock being active, then there is a possibility
  277. * reader(s) may have the lock. To be safe, bail spinning in these
  278. * situations.
  279. */
  280. if (count & RWSEM_ACTIVE_MASK)
  281. ret = false;
  282. goto done;
  283. }
  284. ret = owner->on_cpu;
  285. done:
  286. rcu_read_unlock();
  287. return ret;
  288. }
  289. static noinline
  290. bool rwsem_spin_on_owner(struct rw_semaphore *sem, struct task_struct *owner)
  291. {
  292. long count;
  293. rcu_read_lock();
  294. while (sem->owner == owner) {
  295. /*
  296. * Ensure we emit the owner->on_cpu, dereference _after_
  297. * checking sem->owner still matches owner, if that fails,
  298. * owner might point to free()d memory, if it still matches,
  299. * the rcu_read_lock() ensures the memory stays valid.
  300. */
  301. barrier();
  302. /* abort spinning when need_resched or owner is not running */
  303. if (!owner->on_cpu || need_resched()) {
  304. rcu_read_unlock();
  305. return false;
  306. }
  307. cpu_relax_lowlatency();
  308. }
  309. rcu_read_unlock();
  310. if (READ_ONCE(sem->owner))
  311. return true; /* new owner, continue spinning */
  312. /*
  313. * When the owner is not set, the lock could be free or
  314. * held by readers. Check the counter to verify the
  315. * state.
  316. */
  317. count = READ_ONCE(sem->count);
  318. return (count == 0 || count == RWSEM_WAITING_BIAS);
  319. }
  320. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  321. {
  322. struct task_struct *owner;
  323. bool taken = false;
  324. preempt_disable();
  325. /* sem->wait_lock should not be held when doing optimistic spinning */
  326. if (!rwsem_can_spin_on_owner(sem))
  327. goto done;
  328. if (!osq_lock(&sem->osq))
  329. goto done;
  330. while (true) {
  331. owner = READ_ONCE(sem->owner);
  332. if (owner && !rwsem_spin_on_owner(sem, owner))
  333. break;
  334. /* wait_lock will be acquired if write_lock is obtained */
  335. if (rwsem_try_write_lock_unqueued(sem)) {
  336. taken = true;
  337. break;
  338. }
  339. /*
  340. * When there's no owner, we might have preempted between the
  341. * owner acquiring the lock and setting the owner field. If
  342. * we're an RT task that will live-lock because we won't let
  343. * the owner complete.
  344. */
  345. if (!owner && (need_resched() || rt_task(current)))
  346. break;
  347. /*
  348. * The cpu_relax() call is a compiler barrier which forces
  349. * everything in this loop to be re-loaded. We don't need
  350. * memory barriers as we'll eventually observe the right
  351. * values at the cost of a few extra spins.
  352. */
  353. cpu_relax_lowlatency();
  354. }
  355. osq_unlock(&sem->osq);
  356. done:
  357. preempt_enable();
  358. return taken;
  359. }
  360. /*
  361. * Return true if the rwsem has active spinner
  362. */
  363. static inline bool rwsem_has_spinner(struct rw_semaphore *sem)
  364. {
  365. return osq_is_locked(&sem->osq);
  366. }
  367. #else
  368. static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
  369. {
  370. return false;
  371. }
  372. static inline bool rwsem_has_spinner(struct rw_semaphore *sem)
  373. {
  374. return false;
  375. }
  376. #endif
  377. /*
  378. * Wait until we successfully acquire the write lock
  379. */
  380. __visible
  381. struct rw_semaphore __sched *rwsem_down_write_failed(struct rw_semaphore *sem)
  382. {
  383. long count;
  384. bool waiting = true; /* any queued threads before us */
  385. struct rwsem_waiter waiter;
  386. /* undo write bias from down_write operation, stop active locking */
  387. count = rwsem_atomic_update(-RWSEM_ACTIVE_WRITE_BIAS, sem);
  388. /* do optimistic spinning and steal lock if possible */
  389. if (rwsem_optimistic_spin(sem))
  390. return sem;
  391. /*
  392. * Optimistic spinning failed, proceed to the slowpath
  393. * and block until we can acquire the sem.
  394. */
  395. waiter.task = current;
  396. waiter.type = RWSEM_WAITING_FOR_WRITE;
  397. raw_spin_lock_irq(&sem->wait_lock);
  398. /* account for this before adding a new element to the list */
  399. if (list_empty(&sem->wait_list))
  400. waiting = false;
  401. list_add_tail(&waiter.list, &sem->wait_list);
  402. /* we're now waiting on the lock, but no longer actively locking */
  403. if (waiting) {
  404. count = READ_ONCE(sem->count);
  405. /*
  406. * If there were already threads queued before us and there are
  407. * no active writers, the lock must be read owned; so we try to
  408. * wake any read locks that were queued ahead of us.
  409. */
  410. if (count > RWSEM_WAITING_BIAS)
  411. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READERS);
  412. } else
  413. count = rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
  414. /* wait until we successfully acquire the lock */
  415. set_current_state(TASK_UNINTERRUPTIBLE);
  416. while (true) {
  417. if (rwsem_try_write_lock(count, sem))
  418. break;
  419. raw_spin_unlock_irq(&sem->wait_lock);
  420. /* Block until there are no active lockers. */
  421. do {
  422. schedule();
  423. set_current_state(TASK_UNINTERRUPTIBLE);
  424. } while ((count = sem->count) & RWSEM_ACTIVE_MASK);
  425. raw_spin_lock_irq(&sem->wait_lock);
  426. }
  427. __set_current_state(TASK_RUNNING);
  428. list_del(&waiter.list);
  429. raw_spin_unlock_irq(&sem->wait_lock);
  430. return sem;
  431. }
  432. EXPORT_SYMBOL(rwsem_down_write_failed);
  433. /*
  434. * handle waking up a waiter on the semaphore
  435. * - up_read/up_write has decremented the active part of count if we come here
  436. */
  437. __visible
  438. struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem)
  439. {
  440. unsigned long flags;
  441. /*
  442. * If a spinner is present, it is not necessary to do the wakeup.
  443. * Try to do wakeup only if the trylock succeeds to minimize
  444. * spinlock contention which may introduce too much delay in the
  445. * unlock operation.
  446. *
  447. * spinning writer up_write/up_read caller
  448. * --------------- -----------------------
  449. * [S] osq_unlock() [L] osq
  450. * MB RMB
  451. * [RmW] rwsem_try_write_lock() [RmW] spin_trylock(wait_lock)
  452. *
  453. * Here, it is important to make sure that there won't be a missed
  454. * wakeup while the rwsem is free and the only spinning writer goes
  455. * to sleep without taking the rwsem. Even when the spinning writer
  456. * is just going to break out of the waiting loop, it will still do
  457. * a trylock in rwsem_down_write_failed() before sleeping. IOW, if
  458. * rwsem_has_spinner() is true, it will guarantee at least one
  459. * trylock attempt on the rwsem later on.
  460. */
  461. if (rwsem_has_spinner(sem)) {
  462. /*
  463. * The smp_rmb() here is to make sure that the spinner
  464. * state is consulted before reading the wait_lock.
  465. */
  466. smp_rmb();
  467. if (!raw_spin_trylock_irqsave(&sem->wait_lock, flags))
  468. return sem;
  469. goto locked;
  470. }
  471. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  472. locked:
  473. /* do nothing if list empty */
  474. if (!list_empty(&sem->wait_list))
  475. sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
  476. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  477. return sem;
  478. }
  479. EXPORT_SYMBOL(rwsem_wake);
  480. /*
  481. * downgrade a write lock into a read lock
  482. * - caller incremented waiting part of count and discovered it still negative
  483. * - just wake up any readers at the front of the queue
  484. */
  485. __visible
  486. struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem)
  487. {
  488. unsigned long flags;
  489. raw_spin_lock_irqsave(&sem->wait_lock, flags);
  490. /* do nothing if list empty */
  491. if (!list_empty(&sem->wait_list))
  492. sem = __rwsem_do_wake(sem, RWSEM_WAKE_READ_OWNED);
  493. raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
  494. return sem;
  495. }
  496. EXPORT_SYMBOL(rwsem_downgrade_wake);