srcu.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * Sleepable Read-Copy Update mechanism for mutual exclusion.
  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. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17. *
  18. * Copyright (C) IBM Corporation, 2006
  19. *
  20. * Author: Paul McKenney <paulmck@us.ibm.com>
  21. *
  22. * For detailed explanation of Read-Copy Update mechanism see -
  23. * Documentation/RCU/ *.txt
  24. *
  25. */
  26. #include <linux/export.h>
  27. #include <linux/mutex.h>
  28. #include <linux/percpu.h>
  29. #include <linux/preempt.h>
  30. #include <linux/rcupdate.h>
  31. #include <linux/sched.h>
  32. #include <linux/smp.h>
  33. #include <linux/delay.h>
  34. #include <linux/srcu.h>
  35. static int init_srcu_struct_fields(struct srcu_struct *sp)
  36. {
  37. sp->completed = 0;
  38. mutex_init(&sp->mutex);
  39. sp->per_cpu_ref = alloc_percpu(struct srcu_struct_array);
  40. return sp->per_cpu_ref ? 0 : -ENOMEM;
  41. }
  42. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  43. int __init_srcu_struct(struct srcu_struct *sp, const char *name,
  44. struct lock_class_key *key)
  45. {
  46. /* Don't re-initialize a lock while it is held. */
  47. debug_check_no_locks_freed((void *)sp, sizeof(*sp));
  48. lockdep_init_map(&sp->dep_map, name, key, 0);
  49. return init_srcu_struct_fields(sp);
  50. }
  51. EXPORT_SYMBOL_GPL(__init_srcu_struct);
  52. #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  53. /**
  54. * init_srcu_struct - initialize a sleep-RCU structure
  55. * @sp: structure to initialize.
  56. *
  57. * Must invoke this on a given srcu_struct before passing that srcu_struct
  58. * to any other function. Each srcu_struct represents a separate domain
  59. * of SRCU protection.
  60. */
  61. int init_srcu_struct(struct srcu_struct *sp)
  62. {
  63. return init_srcu_struct_fields(sp);
  64. }
  65. EXPORT_SYMBOL_GPL(init_srcu_struct);
  66. #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  67. /*
  68. * Returns approximate total of the readers' ->seq[] values for the
  69. * rank of per-CPU counters specified by idx.
  70. */
  71. static unsigned long srcu_readers_seq_idx(struct srcu_struct *sp, int idx)
  72. {
  73. int cpu;
  74. unsigned long sum = 0;
  75. unsigned long t;
  76. for_each_possible_cpu(cpu) {
  77. t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->seq[idx]);
  78. sum += t;
  79. }
  80. return sum;
  81. }
  82. /*
  83. * Returns approximate number of readers active on the specified rank
  84. * of the per-CPU ->c[] counters.
  85. */
  86. static unsigned long srcu_readers_active_idx(struct srcu_struct *sp, int idx)
  87. {
  88. int cpu;
  89. unsigned long sum = 0;
  90. unsigned long t;
  91. for_each_possible_cpu(cpu) {
  92. t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[idx]);
  93. sum += t;
  94. }
  95. return sum;
  96. }
  97. /*
  98. * Return true if the number of pre-existing readers is determined to
  99. * be stably zero. An example unstable zero can occur if the call
  100. * to srcu_readers_active_idx() misses an __srcu_read_lock() increment,
  101. * but due to task migration, sees the corresponding __srcu_read_unlock()
  102. * decrement. This can happen because srcu_readers_active_idx() takes
  103. * time to sum the array, and might in fact be interrupted or preempted
  104. * partway through the summation.
  105. */
  106. static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
  107. {
  108. unsigned long seq;
  109. seq = srcu_readers_seq_idx(sp, idx);
  110. /*
  111. * The following smp_mb() A pairs with the smp_mb() B located in
  112. * __srcu_read_lock(). This pairing ensures that if an
  113. * __srcu_read_lock() increments its counter after the summation
  114. * in srcu_readers_active_idx(), then the corresponding SRCU read-side
  115. * critical section will see any changes made prior to the start
  116. * of the current SRCU grace period.
  117. *
  118. * Also, if the above call to srcu_readers_seq_idx() saw the
  119. * increment of ->seq[], then the call to srcu_readers_active_idx()
  120. * must see the increment of ->c[].
  121. */
  122. smp_mb(); /* A */
  123. /*
  124. * Note that srcu_readers_active_idx() can incorrectly return
  125. * zero even though there is a pre-existing reader throughout.
  126. * To see this, suppose that task A is in a very long SRCU
  127. * read-side critical section that started on CPU 0, and that
  128. * no other reader exists, so that the sum of the counters
  129. * is equal to one. Then suppose that task B starts executing
  130. * srcu_readers_active_idx(), summing up to CPU 1, and then that
  131. * task C starts reading on CPU 0, so that its increment is not
  132. * summed, but finishes reading on CPU 2, so that its decrement
  133. * -is- summed. Then when task B completes its sum, it will
  134. * incorrectly get zero, despite the fact that task A has been
  135. * in its SRCU read-side critical section the whole time.
  136. *
  137. * We therefore do a validation step should srcu_readers_active_idx()
  138. * return zero.
  139. */
  140. if (srcu_readers_active_idx(sp, idx) != 0)
  141. return false;
  142. /*
  143. * The remainder of this function is the validation step.
  144. * The following smp_mb() D pairs with the smp_mb() C in
  145. * __srcu_read_unlock(). If the __srcu_read_unlock() was seen
  146. * by srcu_readers_active_idx() above, then any destructive
  147. * operation performed after the grace period will happen after
  148. * the corresponding SRCU read-side critical section.
  149. *
  150. * Note that there can be at most NR_CPUS worth of readers using
  151. * the old index, which is not enough to overflow even a 32-bit
  152. * integer. (Yes, this does mean that systems having more than
  153. * a billion or so CPUs need to be 64-bit systems.) Therefore,
  154. * the sum of the ->seq[] counters cannot possibly overflow.
  155. * Therefore, the only way that the return values of the two
  156. * calls to srcu_readers_seq_idx() can be equal is if there were
  157. * no increments of the corresponding rank of ->seq[] counts
  158. * in the interim. But the missed-increment scenario laid out
  159. * above includes an increment of the ->seq[] counter by
  160. * the corresponding __srcu_read_lock(). Therefore, if this
  161. * scenario occurs, the return values from the two calls to
  162. * srcu_readers_seq_idx() will differ, and thus the validation
  163. * step below suffices.
  164. */
  165. smp_mb(); /* D */
  166. return srcu_readers_seq_idx(sp, idx) == seq;
  167. }
  168. /**
  169. * srcu_readers_active - returns approximate number of readers.
  170. * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
  171. *
  172. * Note that this is not an atomic primitive, and can therefore suffer
  173. * severe errors when invoked on an active srcu_struct. That said, it
  174. * can be useful as an error check at cleanup time.
  175. */
  176. static int srcu_readers_active(struct srcu_struct *sp)
  177. {
  178. int cpu;
  179. unsigned long sum = 0;
  180. for_each_possible_cpu(cpu) {
  181. sum += ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[0]);
  182. sum += ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[1]);
  183. }
  184. return sum;
  185. }
  186. /**
  187. * cleanup_srcu_struct - deconstruct a sleep-RCU structure
  188. * @sp: structure to clean up.
  189. *
  190. * Must invoke this after you are finished using a given srcu_struct that
  191. * was initialized via init_srcu_struct(), else you leak memory.
  192. */
  193. void cleanup_srcu_struct(struct srcu_struct *sp)
  194. {
  195. int sum;
  196. sum = srcu_readers_active(sp);
  197. WARN_ON(sum); /* Leakage unless caller handles error. */
  198. if (sum != 0)
  199. return;
  200. free_percpu(sp->per_cpu_ref);
  201. sp->per_cpu_ref = NULL;
  202. }
  203. EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
  204. /*
  205. * Counts the new reader in the appropriate per-CPU element of the
  206. * srcu_struct. Must be called from process context.
  207. * Returns an index that must be passed to the matching srcu_read_unlock().
  208. */
  209. int __srcu_read_lock(struct srcu_struct *sp)
  210. {
  211. int idx;
  212. preempt_disable();
  213. idx = rcu_dereference_index_check(sp->completed,
  214. rcu_read_lock_sched_held()) & 0x1;
  215. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) += 1;
  216. smp_mb(); /* B */ /* Avoid leaking the critical section. */
  217. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->seq[idx]) += 1;
  218. preempt_enable();
  219. return idx;
  220. }
  221. EXPORT_SYMBOL_GPL(__srcu_read_lock);
  222. /*
  223. * Removes the count for the old reader from the appropriate per-CPU
  224. * element of the srcu_struct. Note that this may well be a different
  225. * CPU than that which was incremented by the corresponding srcu_read_lock().
  226. * Must be called from process context.
  227. */
  228. void __srcu_read_unlock(struct srcu_struct *sp, int idx)
  229. {
  230. preempt_disable();
  231. smp_mb(); /* C */ /* Avoid leaking the critical section. */
  232. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) -= 1;
  233. preempt_enable();
  234. }
  235. EXPORT_SYMBOL_GPL(__srcu_read_unlock);
  236. /*
  237. * We use an adaptive strategy for synchronize_srcu() and especially for
  238. * synchronize_srcu_expedited(). We spin for a fixed time period
  239. * (defined below) to allow SRCU readers to exit their read-side critical
  240. * sections. If there are still some readers after 10 microseconds,
  241. * we repeatedly block for 1-millisecond time periods. This approach
  242. * has done well in testing, so there is no need for a config parameter.
  243. */
  244. #define SYNCHRONIZE_SRCU_READER_DELAY 5
  245. #define SYNCHRONIZE_SRCU_TRYCOUNT 2
  246. #define SYNCHRONIZE_SRCU_EXP_TRYCOUNT 12
  247. /*
  248. * Wait until all pre-existing readers complete. Such readers
  249. * will have used the index specified by "idx".
  250. */
  251. static void wait_idx(struct srcu_struct *sp, int idx, int trycount)
  252. {
  253. /*
  254. * SRCU read-side critical sections are normally short, so wait
  255. * a small amount of time before possibly blocking.
  256. */
  257. if (!srcu_readers_active_idx_check(sp, idx)) {
  258. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  259. while (!srcu_readers_active_idx_check(sp, idx)) {
  260. if (trycount > 0) {
  261. trycount--;
  262. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  263. } else
  264. schedule_timeout_interruptible(1);
  265. }
  266. }
  267. }
  268. static void srcu_flip(struct srcu_struct *sp)
  269. {
  270. sp->completed++;
  271. }
  272. /*
  273. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  274. */
  275. static void __synchronize_srcu(struct srcu_struct *sp, int trycount)
  276. {
  277. int busy_idx;
  278. rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
  279. !lock_is_held(&rcu_bh_lock_map) &&
  280. !lock_is_held(&rcu_lock_map) &&
  281. !lock_is_held(&rcu_sched_lock_map),
  282. "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
  283. mutex_lock(&sp->mutex);
  284. busy_idx = sp->completed & 0X1UL;
  285. /*
  286. * If we recently flipped the index, there will be some readers
  287. * using idx=0 and others using idx=1. Therefore, two calls to
  288. * wait_idx()s suffice to ensure that all pre-existing readers
  289. * have completed:
  290. *
  291. * __synchronize_srcu() {
  292. * wait_idx(sp, 0, trycount);
  293. * wait_idx(sp, 1, trycount);
  294. * }
  295. *
  296. * Starvation is prevented by the fact that we flip the index.
  297. * While we wait on one index to clear out, almost all new readers
  298. * will be using the other index. The number of new readers using the
  299. * index we are waiting on is sharply bounded by roughly the number
  300. * of CPUs.
  301. *
  302. * How can new readers possibly using the old pre-flip value of
  303. * the index? Consider the following sequence of events:
  304. *
  305. * Suppose that during the previous grace period, a reader
  306. * picked up the old value of the index, but did not increment
  307. * its counter until after the previous instance of
  308. * __synchronize_srcu() did the counter summation and recheck.
  309. * That previous grace period was OK because the reader did
  310. * not start until after the grace period started, so the grace
  311. * period was not obligated to wait for that reader.
  312. *
  313. * However, this sequence of events is quite improbable, so
  314. * this call to wait_idx(), which waits on really old readers
  315. * describe in this comment above, will almost never need to wait.
  316. */
  317. wait_idx(sp, 1 - busy_idx, trycount);
  318. /* Flip the index to avoid reader-induced starvation. */
  319. srcu_flip(sp);
  320. /* Wait for recent pre-existing readers. */
  321. wait_idx(sp, busy_idx, trycount);
  322. mutex_unlock(&sp->mutex);
  323. }
  324. /**
  325. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  326. * @sp: srcu_struct with which to synchronize.
  327. *
  328. * Flip the completed counter, and wait for the old count to drain to zero.
  329. * As with classic RCU, the updater must use some separate means of
  330. * synchronizing concurrent updates. Can block; must be called from
  331. * process context.
  332. *
  333. * Note that it is illegal to call synchronize_srcu() from the corresponding
  334. * SRCU read-side critical section; doing so will result in deadlock.
  335. * However, it is perfectly legal to call synchronize_srcu() on one
  336. * srcu_struct from some other srcu_struct's read-side critical section.
  337. */
  338. void synchronize_srcu(struct srcu_struct *sp)
  339. {
  340. __synchronize_srcu(sp, SYNCHRONIZE_SRCU_TRYCOUNT);
  341. }
  342. EXPORT_SYMBOL_GPL(synchronize_srcu);
  343. /**
  344. * synchronize_srcu_expedited - Brute-force SRCU grace period
  345. * @sp: srcu_struct with which to synchronize.
  346. *
  347. * Wait for an SRCU grace period to elapse, but be more aggressive about
  348. * spinning rather than blocking when waiting.
  349. *
  350. * Note that it is illegal to call this function while holding any lock
  351. * that is acquired by a CPU-hotplug notifier. It is also illegal to call
  352. * synchronize_srcu_expedited() from the corresponding SRCU read-side
  353. * critical section; doing so will result in deadlock. However, it is
  354. * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
  355. * from some other srcu_struct's read-side critical section, as long as
  356. * the resulting graph of srcu_structs is acyclic.
  357. */
  358. void synchronize_srcu_expedited(struct srcu_struct *sp)
  359. {
  360. __synchronize_srcu(sp, SYNCHRONIZE_SRCU_EXP_TRYCOUNT);
  361. }
  362. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  363. /**
  364. * srcu_batches_completed - return batches completed.
  365. * @sp: srcu_struct on which to report batch completion.
  366. *
  367. * Report the number of batches, correlated with, but not necessarily
  368. * precisely the same as, the number of grace periods that have elapsed.
  369. */
  370. long srcu_batches_completed(struct srcu_struct *sp)
  371. {
  372. return sp->completed;
  373. }
  374. EXPORT_SYMBOL_GPL(srcu_batches_completed);