srcutree.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Sleepable Read-Copy Update mechanism for mutual exclusion.
  4. *
  5. * Copyright (C) IBM Corporation, 2006
  6. * Copyright (C) Fujitsu, 2012
  7. *
  8. * Authors: Paul McKenney <[email protected]>
  9. * Lai Jiangshan <[email protected]>
  10. *
  11. * For detailed explanation of Read-Copy Update mechanism see -
  12. * Documentation/RCU/ *.txt
  13. *
  14. */
  15. #define pr_fmt(fmt) "rcu: " fmt
  16. #include <linux/export.h>
  17. #include <linux/mutex.h>
  18. #include <linux/percpu.h>
  19. #include <linux/preempt.h>
  20. #include <linux/rcupdate_wait.h>
  21. #include <linux/sched.h>
  22. #include <linux/smp.h>
  23. #include <linux/delay.h>
  24. #include <linux/module.h>
  25. #include <linux/slab.h>
  26. #include <linux/srcu.h>
  27. #include "rcu.h"
  28. #include "rcu_segcblist.h"
  29. /* Holdoff in nanoseconds for auto-expediting. */
  30. #define DEFAULT_SRCU_EXP_HOLDOFF (25 * 1000)
  31. static ulong exp_holdoff = DEFAULT_SRCU_EXP_HOLDOFF;
  32. module_param(exp_holdoff, ulong, 0444);
  33. /* Overflow-check frequency. N bits roughly says every 2**N grace periods. */
  34. static ulong counter_wrap_check = (ULONG_MAX >> 2);
  35. module_param(counter_wrap_check, ulong, 0444);
  36. /*
  37. * Control conversion to SRCU_SIZE_BIG:
  38. * 0: Don't convert at all.
  39. * 1: Convert at init_srcu_struct() time.
  40. * 2: Convert when rcutorture invokes srcu_torture_stats_print().
  41. * 3: Decide at boot time based on system shape (default).
  42. * 0x1x: Convert when excessive contention encountered.
  43. */
  44. #define SRCU_SIZING_NONE 0
  45. #define SRCU_SIZING_INIT 1
  46. #define SRCU_SIZING_TORTURE 2
  47. #define SRCU_SIZING_AUTO 3
  48. #define SRCU_SIZING_CONTEND 0x10
  49. #define SRCU_SIZING_IS(x) ((convert_to_big & ~SRCU_SIZING_CONTEND) == x)
  50. #define SRCU_SIZING_IS_NONE() (SRCU_SIZING_IS(SRCU_SIZING_NONE))
  51. #define SRCU_SIZING_IS_INIT() (SRCU_SIZING_IS(SRCU_SIZING_INIT))
  52. #define SRCU_SIZING_IS_TORTURE() (SRCU_SIZING_IS(SRCU_SIZING_TORTURE))
  53. #define SRCU_SIZING_IS_CONTEND() (convert_to_big & SRCU_SIZING_CONTEND)
  54. static int convert_to_big = SRCU_SIZING_AUTO;
  55. module_param(convert_to_big, int, 0444);
  56. /* Number of CPUs to trigger init_srcu_struct()-time transition to big. */
  57. static int big_cpu_lim __read_mostly = 128;
  58. module_param(big_cpu_lim, int, 0444);
  59. /* Contention events per jiffy to initiate transition to big. */
  60. static int small_contention_lim __read_mostly = 100;
  61. module_param(small_contention_lim, int, 0444);
  62. /* Early-boot callback-management, so early that no lock is required! */
  63. static LIST_HEAD(srcu_boot_list);
  64. static bool __read_mostly srcu_init_done;
  65. static void srcu_invoke_callbacks(struct work_struct *work);
  66. static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay);
  67. static void process_srcu(struct work_struct *work);
  68. static void srcu_delay_timer(struct timer_list *t);
  69. /* Wrappers for lock acquisition and release, see raw_spin_lock_rcu_node(). */
  70. #define spin_lock_rcu_node(p) \
  71. do { \
  72. spin_lock(&ACCESS_PRIVATE(p, lock)); \
  73. smp_mb__after_unlock_lock(); \
  74. } while (0)
  75. #define spin_unlock_rcu_node(p) spin_unlock(&ACCESS_PRIVATE(p, lock))
  76. #define spin_lock_irq_rcu_node(p) \
  77. do { \
  78. spin_lock_irq(&ACCESS_PRIVATE(p, lock)); \
  79. smp_mb__after_unlock_lock(); \
  80. } while (0)
  81. #define spin_unlock_irq_rcu_node(p) \
  82. spin_unlock_irq(&ACCESS_PRIVATE(p, lock))
  83. #define spin_lock_irqsave_rcu_node(p, flags) \
  84. do { \
  85. spin_lock_irqsave(&ACCESS_PRIVATE(p, lock), flags); \
  86. smp_mb__after_unlock_lock(); \
  87. } while (0)
  88. #define spin_trylock_irqsave_rcu_node(p, flags) \
  89. ({ \
  90. bool ___locked = spin_trylock_irqsave(&ACCESS_PRIVATE(p, lock), flags); \
  91. \
  92. if (___locked) \
  93. smp_mb__after_unlock_lock(); \
  94. ___locked; \
  95. })
  96. #define spin_unlock_irqrestore_rcu_node(p, flags) \
  97. spin_unlock_irqrestore(&ACCESS_PRIVATE(p, lock), flags) \
  98. /*
  99. * Initialize SRCU per-CPU data. Note that statically allocated
  100. * srcu_struct structures might already have srcu_read_lock() and
  101. * srcu_read_unlock() running against them. So if the is_static parameter
  102. * is set, don't initialize ->srcu_lock_count[] and ->srcu_unlock_count[].
  103. */
  104. static void init_srcu_struct_data(struct srcu_struct *ssp)
  105. {
  106. int cpu;
  107. struct srcu_data *sdp;
  108. /*
  109. * Initialize the per-CPU srcu_data array, which feeds into the
  110. * leaves of the srcu_node tree.
  111. */
  112. WARN_ON_ONCE(ARRAY_SIZE(sdp->srcu_lock_count) !=
  113. ARRAY_SIZE(sdp->srcu_unlock_count));
  114. for_each_possible_cpu(cpu) {
  115. sdp = per_cpu_ptr(ssp->sda, cpu);
  116. spin_lock_init(&ACCESS_PRIVATE(sdp, lock));
  117. rcu_segcblist_init(&sdp->srcu_cblist);
  118. sdp->srcu_cblist_invoking = false;
  119. sdp->srcu_gp_seq_needed = ssp->srcu_gp_seq;
  120. sdp->srcu_gp_seq_needed_exp = ssp->srcu_gp_seq;
  121. sdp->mynode = NULL;
  122. sdp->cpu = cpu;
  123. INIT_WORK(&sdp->work, srcu_invoke_callbacks);
  124. timer_setup(&sdp->delay_work, srcu_delay_timer, 0);
  125. sdp->ssp = ssp;
  126. }
  127. }
  128. /* Invalid seq state, used during snp node initialization */
  129. #define SRCU_SNP_INIT_SEQ 0x2
  130. /*
  131. * Check whether sequence number corresponding to snp node,
  132. * is invalid.
  133. */
  134. static inline bool srcu_invl_snp_seq(unsigned long s)
  135. {
  136. return rcu_seq_state(s) == SRCU_SNP_INIT_SEQ;
  137. }
  138. /*
  139. * Allocated and initialize SRCU combining tree. Returns @true if
  140. * allocation succeeded and @false otherwise.
  141. */
  142. static bool init_srcu_struct_nodes(struct srcu_struct *ssp, gfp_t gfp_flags)
  143. {
  144. int cpu;
  145. int i;
  146. int level = 0;
  147. int levelspread[RCU_NUM_LVLS];
  148. struct srcu_data *sdp;
  149. struct srcu_node *snp;
  150. struct srcu_node *snp_first;
  151. /* Initialize geometry if it has not already been initialized. */
  152. rcu_init_geometry();
  153. ssp->node = kcalloc(rcu_num_nodes, sizeof(*ssp->node), gfp_flags);
  154. if (!ssp->node)
  155. return false;
  156. /* Work out the overall tree geometry. */
  157. ssp->level[0] = &ssp->node[0];
  158. for (i = 1; i < rcu_num_lvls; i++)
  159. ssp->level[i] = ssp->level[i - 1] + num_rcu_lvl[i - 1];
  160. rcu_init_levelspread(levelspread, num_rcu_lvl);
  161. /* Each pass through this loop initializes one srcu_node structure. */
  162. srcu_for_each_node_breadth_first(ssp, snp) {
  163. spin_lock_init(&ACCESS_PRIVATE(snp, lock));
  164. WARN_ON_ONCE(ARRAY_SIZE(snp->srcu_have_cbs) !=
  165. ARRAY_SIZE(snp->srcu_data_have_cbs));
  166. for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++) {
  167. snp->srcu_have_cbs[i] = SRCU_SNP_INIT_SEQ;
  168. snp->srcu_data_have_cbs[i] = 0;
  169. }
  170. snp->srcu_gp_seq_needed_exp = SRCU_SNP_INIT_SEQ;
  171. snp->grplo = -1;
  172. snp->grphi = -1;
  173. if (snp == &ssp->node[0]) {
  174. /* Root node, special case. */
  175. snp->srcu_parent = NULL;
  176. continue;
  177. }
  178. /* Non-root node. */
  179. if (snp == ssp->level[level + 1])
  180. level++;
  181. snp->srcu_parent = ssp->level[level - 1] +
  182. (snp - ssp->level[level]) /
  183. levelspread[level - 1];
  184. }
  185. /*
  186. * Initialize the per-CPU srcu_data array, which feeds into the
  187. * leaves of the srcu_node tree.
  188. */
  189. level = rcu_num_lvls - 1;
  190. snp_first = ssp->level[level];
  191. for_each_possible_cpu(cpu) {
  192. sdp = per_cpu_ptr(ssp->sda, cpu);
  193. sdp->mynode = &snp_first[cpu / levelspread[level]];
  194. for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) {
  195. if (snp->grplo < 0)
  196. snp->grplo = cpu;
  197. snp->grphi = cpu;
  198. }
  199. sdp->grpmask = 1UL << (cpu - sdp->mynode->grplo);
  200. }
  201. smp_store_release(&ssp->srcu_size_state, SRCU_SIZE_WAIT_BARRIER);
  202. return true;
  203. }
  204. /*
  205. * Initialize non-compile-time initialized fields, including the
  206. * associated srcu_node and srcu_data structures. The is_static parameter
  207. * tells us that ->sda has already been wired up to srcu_data.
  208. */
  209. static int init_srcu_struct_fields(struct srcu_struct *ssp, bool is_static)
  210. {
  211. ssp->srcu_size_state = SRCU_SIZE_SMALL;
  212. ssp->node = NULL;
  213. mutex_init(&ssp->srcu_cb_mutex);
  214. mutex_init(&ssp->srcu_gp_mutex);
  215. ssp->srcu_idx = 0;
  216. ssp->srcu_gp_seq = 0;
  217. ssp->srcu_barrier_seq = 0;
  218. mutex_init(&ssp->srcu_barrier_mutex);
  219. atomic_set(&ssp->srcu_barrier_cpu_cnt, 0);
  220. INIT_DELAYED_WORK(&ssp->work, process_srcu);
  221. ssp->sda_is_static = is_static;
  222. if (!is_static)
  223. ssp->sda = alloc_percpu(struct srcu_data);
  224. if (!ssp->sda)
  225. return -ENOMEM;
  226. init_srcu_struct_data(ssp);
  227. ssp->srcu_gp_seq_needed_exp = 0;
  228. ssp->srcu_last_gp_end = ktime_get_mono_fast_ns();
  229. if (READ_ONCE(ssp->srcu_size_state) == SRCU_SIZE_SMALL && SRCU_SIZING_IS_INIT()) {
  230. if (!init_srcu_struct_nodes(ssp, GFP_ATOMIC)) {
  231. if (!ssp->sda_is_static) {
  232. free_percpu(ssp->sda);
  233. ssp->sda = NULL;
  234. return -ENOMEM;
  235. }
  236. } else {
  237. WRITE_ONCE(ssp->srcu_size_state, SRCU_SIZE_BIG);
  238. }
  239. }
  240. smp_store_release(&ssp->srcu_gp_seq_needed, 0); /* Init done. */
  241. return 0;
  242. }
  243. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  244. int __init_srcu_struct(struct srcu_struct *ssp, const char *name,
  245. struct lock_class_key *key)
  246. {
  247. /* Don't re-initialize a lock while it is held. */
  248. debug_check_no_locks_freed((void *)ssp, sizeof(*ssp));
  249. lockdep_init_map(&ssp->dep_map, name, key, 0);
  250. spin_lock_init(&ACCESS_PRIVATE(ssp, lock));
  251. return init_srcu_struct_fields(ssp, false);
  252. }
  253. EXPORT_SYMBOL_GPL(__init_srcu_struct);
  254. #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  255. /**
  256. * init_srcu_struct - initialize a sleep-RCU structure
  257. * @ssp: structure to initialize.
  258. *
  259. * Must invoke this on a given srcu_struct before passing that srcu_struct
  260. * to any other function. Each srcu_struct represents a separate domain
  261. * of SRCU protection.
  262. */
  263. int init_srcu_struct(struct srcu_struct *ssp)
  264. {
  265. spin_lock_init(&ACCESS_PRIVATE(ssp, lock));
  266. return init_srcu_struct_fields(ssp, false);
  267. }
  268. EXPORT_SYMBOL_GPL(init_srcu_struct);
  269. #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  270. /*
  271. * Initiate a transition to SRCU_SIZE_BIG with lock held.
  272. */
  273. static void __srcu_transition_to_big(struct srcu_struct *ssp)
  274. {
  275. lockdep_assert_held(&ACCESS_PRIVATE(ssp, lock));
  276. smp_store_release(&ssp->srcu_size_state, SRCU_SIZE_ALLOC);
  277. }
  278. /*
  279. * Initiate an idempotent transition to SRCU_SIZE_BIG.
  280. */
  281. static void srcu_transition_to_big(struct srcu_struct *ssp)
  282. {
  283. unsigned long flags;
  284. /* Double-checked locking on ->srcu_size-state. */
  285. if (smp_load_acquire(&ssp->srcu_size_state) != SRCU_SIZE_SMALL)
  286. return;
  287. spin_lock_irqsave_rcu_node(ssp, flags);
  288. if (smp_load_acquire(&ssp->srcu_size_state) != SRCU_SIZE_SMALL) {
  289. spin_unlock_irqrestore_rcu_node(ssp, flags);
  290. return;
  291. }
  292. __srcu_transition_to_big(ssp);
  293. spin_unlock_irqrestore_rcu_node(ssp, flags);
  294. }
  295. /*
  296. * Check to see if the just-encountered contention event justifies
  297. * a transition to SRCU_SIZE_BIG.
  298. */
  299. static void spin_lock_irqsave_check_contention(struct srcu_struct *ssp)
  300. {
  301. unsigned long j;
  302. if (!SRCU_SIZING_IS_CONTEND() || ssp->srcu_size_state)
  303. return;
  304. j = jiffies;
  305. if (ssp->srcu_size_jiffies != j) {
  306. ssp->srcu_size_jiffies = j;
  307. ssp->srcu_n_lock_retries = 0;
  308. }
  309. if (++ssp->srcu_n_lock_retries <= small_contention_lim)
  310. return;
  311. __srcu_transition_to_big(ssp);
  312. }
  313. /*
  314. * Acquire the specified srcu_data structure's ->lock, but check for
  315. * excessive contention, which results in initiation of a transition
  316. * to SRCU_SIZE_BIG. But only if the srcutree.convert_to_big module
  317. * parameter permits this.
  318. */
  319. static void spin_lock_irqsave_sdp_contention(struct srcu_data *sdp, unsigned long *flags)
  320. {
  321. struct srcu_struct *ssp = sdp->ssp;
  322. if (spin_trylock_irqsave_rcu_node(sdp, *flags))
  323. return;
  324. spin_lock_irqsave_rcu_node(ssp, *flags);
  325. spin_lock_irqsave_check_contention(ssp);
  326. spin_unlock_irqrestore_rcu_node(ssp, *flags);
  327. spin_lock_irqsave_rcu_node(sdp, *flags);
  328. }
  329. /*
  330. * Acquire the specified srcu_struct structure's ->lock, but check for
  331. * excessive contention, which results in initiation of a transition
  332. * to SRCU_SIZE_BIG. But only if the srcutree.convert_to_big module
  333. * parameter permits this.
  334. */
  335. static void spin_lock_irqsave_ssp_contention(struct srcu_struct *ssp, unsigned long *flags)
  336. {
  337. if (spin_trylock_irqsave_rcu_node(ssp, *flags))
  338. return;
  339. spin_lock_irqsave_rcu_node(ssp, *flags);
  340. spin_lock_irqsave_check_contention(ssp);
  341. }
  342. /*
  343. * First-use initialization of statically allocated srcu_struct
  344. * structure. Wiring up the combining tree is more than can be
  345. * done with compile-time initialization, so this check is added
  346. * to each update-side SRCU primitive. Use ssp->lock, which -is-
  347. * compile-time initialized, to resolve races involving multiple
  348. * CPUs trying to garner first-use privileges.
  349. */
  350. static void check_init_srcu_struct(struct srcu_struct *ssp)
  351. {
  352. unsigned long flags;
  353. /* The smp_load_acquire() pairs with the smp_store_release(). */
  354. if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_gp_seq_needed))) /*^^^*/
  355. return; /* Already initialized. */
  356. spin_lock_irqsave_rcu_node(ssp, flags);
  357. if (!rcu_seq_state(ssp->srcu_gp_seq_needed)) {
  358. spin_unlock_irqrestore_rcu_node(ssp, flags);
  359. return;
  360. }
  361. init_srcu_struct_fields(ssp, true);
  362. spin_unlock_irqrestore_rcu_node(ssp, flags);
  363. }
  364. /*
  365. * Returns approximate total of the readers' ->srcu_lock_count[] values
  366. * for the rank of per-CPU counters specified by idx.
  367. */
  368. static unsigned long srcu_readers_lock_idx(struct srcu_struct *ssp, int idx)
  369. {
  370. int cpu;
  371. unsigned long sum = 0;
  372. for_each_possible_cpu(cpu) {
  373. struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu);
  374. sum += READ_ONCE(cpuc->srcu_lock_count[idx]);
  375. }
  376. return sum;
  377. }
  378. /*
  379. * Returns approximate total of the readers' ->srcu_unlock_count[] values
  380. * for the rank of per-CPU counters specified by idx.
  381. */
  382. static unsigned long srcu_readers_unlock_idx(struct srcu_struct *ssp, int idx)
  383. {
  384. int cpu;
  385. unsigned long sum = 0;
  386. for_each_possible_cpu(cpu) {
  387. struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu);
  388. sum += READ_ONCE(cpuc->srcu_unlock_count[idx]);
  389. }
  390. return sum;
  391. }
  392. /*
  393. * Return true if the number of pre-existing readers is determined to
  394. * be zero.
  395. */
  396. static bool srcu_readers_active_idx_check(struct srcu_struct *ssp, int idx)
  397. {
  398. unsigned long unlocks;
  399. unlocks = srcu_readers_unlock_idx(ssp, idx);
  400. /*
  401. * Make sure that a lock is always counted if the corresponding
  402. * unlock is counted. Needs to be a smp_mb() as the read side may
  403. * contain a read from a variable that is written to before the
  404. * synchronize_srcu() in the write side. In this case smp_mb()s
  405. * A and B act like the store buffering pattern.
  406. *
  407. * This smp_mb() also pairs with smp_mb() C to prevent accesses
  408. * after the synchronize_srcu() from being executed before the
  409. * grace period ends.
  410. */
  411. smp_mb(); /* A */
  412. /*
  413. * If the locks are the same as the unlocks, then there must have
  414. * been no readers on this index at some time in between. This does
  415. * not mean that there are no more readers, as one could have read
  416. * the current index but not have incremented the lock counter yet.
  417. *
  418. * So suppose that the updater is preempted here for so long
  419. * that more than ULONG_MAX non-nested readers come and go in
  420. * the meantime. It turns out that this cannot result in overflow
  421. * because if a reader modifies its unlock count after we read it
  422. * above, then that reader's next load of ->srcu_idx is guaranteed
  423. * to get the new value, which will cause it to operate on the
  424. * other bank of counters, where it cannot contribute to the
  425. * overflow of these counters. This means that there is a maximum
  426. * of 2*NR_CPUS increments, which cannot overflow given current
  427. * systems, especially not on 64-bit systems.
  428. *
  429. * OK, how about nesting? This does impose a limit on nesting
  430. * of floor(ULONG_MAX/NR_CPUS/2), which should be sufficient,
  431. * especially on 64-bit systems.
  432. */
  433. return srcu_readers_lock_idx(ssp, idx) == unlocks;
  434. }
  435. /**
  436. * srcu_readers_active - returns true if there are readers. and false
  437. * otherwise
  438. * @ssp: which srcu_struct to count active readers (holding srcu_read_lock).
  439. *
  440. * Note that this is not an atomic primitive, and can therefore suffer
  441. * severe errors when invoked on an active srcu_struct. That said, it
  442. * can be useful as an error check at cleanup time.
  443. */
  444. static bool srcu_readers_active(struct srcu_struct *ssp)
  445. {
  446. int cpu;
  447. unsigned long sum = 0;
  448. for_each_possible_cpu(cpu) {
  449. struct srcu_data *cpuc = per_cpu_ptr(ssp->sda, cpu);
  450. sum += READ_ONCE(cpuc->srcu_lock_count[0]);
  451. sum += READ_ONCE(cpuc->srcu_lock_count[1]);
  452. sum -= READ_ONCE(cpuc->srcu_unlock_count[0]);
  453. sum -= READ_ONCE(cpuc->srcu_unlock_count[1]);
  454. }
  455. return sum;
  456. }
  457. /*
  458. * We use an adaptive strategy for synchronize_srcu() and especially for
  459. * synchronize_srcu_expedited(). We spin for a fixed time period
  460. * (defined below, boot time configurable) to allow SRCU readers to exit
  461. * their read-side critical sections. If there are still some readers
  462. * after one jiffy, we repeatedly block for one jiffy time periods.
  463. * The blocking time is increased as the grace-period age increases,
  464. * with max blocking time capped at 10 jiffies.
  465. */
  466. #define SRCU_DEFAULT_RETRY_CHECK_DELAY 5
  467. static ulong srcu_retry_check_delay = SRCU_DEFAULT_RETRY_CHECK_DELAY;
  468. module_param(srcu_retry_check_delay, ulong, 0444);
  469. #define SRCU_INTERVAL 1 // Base delay if no expedited GPs pending.
  470. #define SRCU_MAX_INTERVAL 10 // Maximum incremental delay from slow readers.
  471. #define SRCU_DEFAULT_MAX_NODELAY_PHASE_LO 3UL // Lowmark on default per-GP-phase
  472. // no-delay instances.
  473. #define SRCU_DEFAULT_MAX_NODELAY_PHASE_HI 1000UL // Highmark on default per-GP-phase
  474. // no-delay instances.
  475. #define SRCU_UL_CLAMP_LO(val, low) ((val) > (low) ? (val) : (low))
  476. #define SRCU_UL_CLAMP_HI(val, high) ((val) < (high) ? (val) : (high))
  477. #define SRCU_UL_CLAMP(val, low, high) SRCU_UL_CLAMP_HI(SRCU_UL_CLAMP_LO((val), (low)), (high))
  478. // per-GP-phase no-delay instances adjusted to allow non-sleeping poll upto
  479. // one jiffies time duration. Mult by 2 is done to factor in the srcu_get_delay()
  480. // called from process_srcu().
  481. #define SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED \
  482. (2UL * USEC_PER_SEC / HZ / SRCU_DEFAULT_RETRY_CHECK_DELAY)
  483. // Maximum per-GP-phase consecutive no-delay instances.
  484. #define SRCU_DEFAULT_MAX_NODELAY_PHASE \
  485. SRCU_UL_CLAMP(SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED, \
  486. SRCU_DEFAULT_MAX_NODELAY_PHASE_LO, \
  487. SRCU_DEFAULT_MAX_NODELAY_PHASE_HI)
  488. static ulong srcu_max_nodelay_phase = SRCU_DEFAULT_MAX_NODELAY_PHASE;
  489. module_param(srcu_max_nodelay_phase, ulong, 0444);
  490. // Maximum consecutive no-delay instances.
  491. #define SRCU_DEFAULT_MAX_NODELAY (SRCU_DEFAULT_MAX_NODELAY_PHASE > 100 ? \
  492. SRCU_DEFAULT_MAX_NODELAY_PHASE : 100)
  493. static ulong srcu_max_nodelay = SRCU_DEFAULT_MAX_NODELAY;
  494. module_param(srcu_max_nodelay, ulong, 0444);
  495. /*
  496. * Return grace-period delay, zero if there are expedited grace
  497. * periods pending, SRCU_INTERVAL otherwise.
  498. */
  499. static unsigned long srcu_get_delay(struct srcu_struct *ssp)
  500. {
  501. unsigned long gpstart;
  502. unsigned long j;
  503. unsigned long jbase = SRCU_INTERVAL;
  504. if (ULONG_CMP_LT(READ_ONCE(ssp->srcu_gp_seq), READ_ONCE(ssp->srcu_gp_seq_needed_exp)))
  505. jbase = 0;
  506. if (rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq))) {
  507. j = jiffies - 1;
  508. gpstart = READ_ONCE(ssp->srcu_gp_start);
  509. if (time_after(j, gpstart))
  510. jbase += j - gpstart;
  511. if (!jbase) {
  512. WRITE_ONCE(ssp->srcu_n_exp_nodelay, READ_ONCE(ssp->srcu_n_exp_nodelay) + 1);
  513. if (READ_ONCE(ssp->srcu_n_exp_nodelay) > srcu_max_nodelay_phase)
  514. jbase = 1;
  515. }
  516. }
  517. return jbase > SRCU_MAX_INTERVAL ? SRCU_MAX_INTERVAL : jbase;
  518. }
  519. /**
  520. * cleanup_srcu_struct - deconstruct a sleep-RCU structure
  521. * @ssp: structure to clean up.
  522. *
  523. * Must invoke this after you are finished using a given srcu_struct that
  524. * was initialized via init_srcu_struct(), else you leak memory.
  525. */
  526. void cleanup_srcu_struct(struct srcu_struct *ssp)
  527. {
  528. int cpu;
  529. if (WARN_ON(!srcu_get_delay(ssp)))
  530. return; /* Just leak it! */
  531. if (WARN_ON(srcu_readers_active(ssp)))
  532. return; /* Just leak it! */
  533. flush_delayed_work(&ssp->work);
  534. for_each_possible_cpu(cpu) {
  535. struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu);
  536. del_timer_sync(&sdp->delay_work);
  537. flush_work(&sdp->work);
  538. if (WARN_ON(rcu_segcblist_n_cbs(&sdp->srcu_cblist)))
  539. return; /* Forgot srcu_barrier(), so just leak it! */
  540. }
  541. if (WARN_ON(rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)) != SRCU_STATE_IDLE) ||
  542. WARN_ON(rcu_seq_current(&ssp->srcu_gp_seq) != ssp->srcu_gp_seq_needed) ||
  543. WARN_ON(srcu_readers_active(ssp))) {
  544. pr_info("%s: Active srcu_struct %p read state: %d gp state: %lu/%lu\n",
  545. __func__, ssp, rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)),
  546. rcu_seq_current(&ssp->srcu_gp_seq), ssp->srcu_gp_seq_needed);
  547. return; /* Caller forgot to stop doing call_srcu()? */
  548. }
  549. if (!ssp->sda_is_static) {
  550. free_percpu(ssp->sda);
  551. ssp->sda = NULL;
  552. }
  553. kfree(ssp->node);
  554. ssp->node = NULL;
  555. ssp->srcu_size_state = SRCU_SIZE_SMALL;
  556. }
  557. EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
  558. /*
  559. * Counts the new reader in the appropriate per-CPU element of the
  560. * srcu_struct.
  561. * Returns an index that must be passed to the matching srcu_read_unlock().
  562. */
  563. int __srcu_read_lock(struct srcu_struct *ssp)
  564. {
  565. int idx;
  566. idx = READ_ONCE(ssp->srcu_idx) & 0x1;
  567. this_cpu_inc(ssp->sda->srcu_lock_count[idx]);
  568. smp_mb(); /* B */ /* Avoid leaking the critical section. */
  569. return idx;
  570. }
  571. EXPORT_SYMBOL_GPL(__srcu_read_lock);
  572. /*
  573. * Removes the count for the old reader from the appropriate per-CPU
  574. * element of the srcu_struct. Note that this may well be a different
  575. * CPU than that which was incremented by the corresponding srcu_read_lock().
  576. */
  577. void __srcu_read_unlock(struct srcu_struct *ssp, int idx)
  578. {
  579. smp_mb(); /* C */ /* Avoid leaking the critical section. */
  580. this_cpu_inc(ssp->sda->srcu_unlock_count[idx]);
  581. }
  582. EXPORT_SYMBOL_GPL(__srcu_read_unlock);
  583. /*
  584. * Start an SRCU grace period.
  585. */
  586. static void srcu_gp_start(struct srcu_struct *ssp)
  587. {
  588. struct srcu_data *sdp;
  589. int state;
  590. if (smp_load_acquire(&ssp->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER)
  591. sdp = per_cpu_ptr(ssp->sda, get_boot_cpu_id());
  592. else
  593. sdp = this_cpu_ptr(ssp->sda);
  594. lockdep_assert_held(&ACCESS_PRIVATE(ssp, lock));
  595. WARN_ON_ONCE(ULONG_CMP_GE(ssp->srcu_gp_seq, ssp->srcu_gp_seq_needed));
  596. spin_lock_rcu_node(sdp); /* Interrupts already disabled. */
  597. rcu_segcblist_advance(&sdp->srcu_cblist,
  598. rcu_seq_current(&ssp->srcu_gp_seq));
  599. (void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
  600. rcu_seq_snap(&ssp->srcu_gp_seq));
  601. spin_unlock_rcu_node(sdp); /* Interrupts remain disabled. */
  602. WRITE_ONCE(ssp->srcu_gp_start, jiffies);
  603. WRITE_ONCE(ssp->srcu_n_exp_nodelay, 0);
  604. smp_mb(); /* Order prior store to ->srcu_gp_seq_needed vs. GP start. */
  605. rcu_seq_start(&ssp->srcu_gp_seq);
  606. state = rcu_seq_state(ssp->srcu_gp_seq);
  607. WARN_ON_ONCE(state != SRCU_STATE_SCAN1);
  608. }
  609. static void srcu_delay_timer(struct timer_list *t)
  610. {
  611. struct srcu_data *sdp = container_of(t, struct srcu_data, delay_work);
  612. queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);
  613. }
  614. static void srcu_queue_delayed_work_on(struct srcu_data *sdp,
  615. unsigned long delay)
  616. {
  617. if (!delay) {
  618. queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);
  619. return;
  620. }
  621. timer_reduce(&sdp->delay_work, jiffies + delay);
  622. }
  623. /*
  624. * Schedule callback invocation for the specified srcu_data structure,
  625. * if possible, on the corresponding CPU.
  626. */
  627. static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay)
  628. {
  629. srcu_queue_delayed_work_on(sdp, delay);
  630. }
  631. /*
  632. * Schedule callback invocation for all srcu_data structures associated
  633. * with the specified srcu_node structure that have callbacks for the
  634. * just-completed grace period, the one corresponding to idx. If possible,
  635. * schedule this invocation on the corresponding CPUs.
  636. */
  637. static void srcu_schedule_cbs_snp(struct srcu_struct *ssp, struct srcu_node *snp,
  638. unsigned long mask, unsigned long delay)
  639. {
  640. int cpu;
  641. for (cpu = snp->grplo; cpu <= snp->grphi; cpu++) {
  642. if (!(mask & (1UL << (cpu - snp->grplo))))
  643. continue;
  644. srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, cpu), delay);
  645. }
  646. }
  647. /*
  648. * Note the end of an SRCU grace period. Initiates callback invocation
  649. * and starts a new grace period if needed.
  650. *
  651. * The ->srcu_cb_mutex acquisition does not protect any data, but
  652. * instead prevents more than one grace period from starting while we
  653. * are initiating callback invocation. This allows the ->srcu_have_cbs[]
  654. * array to have a finite number of elements.
  655. */
  656. static void srcu_gp_end(struct srcu_struct *ssp)
  657. {
  658. unsigned long cbdelay = 1;
  659. bool cbs;
  660. bool last_lvl;
  661. int cpu;
  662. unsigned long flags;
  663. unsigned long gpseq;
  664. int idx;
  665. unsigned long mask;
  666. struct srcu_data *sdp;
  667. unsigned long sgsne;
  668. struct srcu_node *snp;
  669. int ss_state;
  670. /* Prevent more than one additional grace period. */
  671. mutex_lock(&ssp->srcu_cb_mutex);
  672. /* End the current grace period. */
  673. spin_lock_irq_rcu_node(ssp);
  674. idx = rcu_seq_state(ssp->srcu_gp_seq);
  675. WARN_ON_ONCE(idx != SRCU_STATE_SCAN2);
  676. if (ULONG_CMP_LT(READ_ONCE(ssp->srcu_gp_seq), READ_ONCE(ssp->srcu_gp_seq_needed_exp)))
  677. cbdelay = 0;
  678. WRITE_ONCE(ssp->srcu_last_gp_end, ktime_get_mono_fast_ns());
  679. rcu_seq_end(&ssp->srcu_gp_seq);
  680. gpseq = rcu_seq_current(&ssp->srcu_gp_seq);
  681. if (ULONG_CMP_LT(ssp->srcu_gp_seq_needed_exp, gpseq))
  682. WRITE_ONCE(ssp->srcu_gp_seq_needed_exp, gpseq);
  683. spin_unlock_irq_rcu_node(ssp);
  684. mutex_unlock(&ssp->srcu_gp_mutex);
  685. /* A new grace period can start at this point. But only one. */
  686. /* Initiate callback invocation as needed. */
  687. ss_state = smp_load_acquire(&ssp->srcu_size_state);
  688. if (ss_state < SRCU_SIZE_WAIT_BARRIER) {
  689. srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, get_boot_cpu_id()),
  690. cbdelay);
  691. } else {
  692. idx = rcu_seq_ctr(gpseq) % ARRAY_SIZE(snp->srcu_have_cbs);
  693. srcu_for_each_node_breadth_first(ssp, snp) {
  694. spin_lock_irq_rcu_node(snp);
  695. cbs = false;
  696. last_lvl = snp >= ssp->level[rcu_num_lvls - 1];
  697. if (last_lvl)
  698. cbs = ss_state < SRCU_SIZE_BIG || snp->srcu_have_cbs[idx] == gpseq;
  699. snp->srcu_have_cbs[idx] = gpseq;
  700. rcu_seq_set_state(&snp->srcu_have_cbs[idx], 1);
  701. sgsne = snp->srcu_gp_seq_needed_exp;
  702. if (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, gpseq))
  703. WRITE_ONCE(snp->srcu_gp_seq_needed_exp, gpseq);
  704. if (ss_state < SRCU_SIZE_BIG)
  705. mask = ~0;
  706. else
  707. mask = snp->srcu_data_have_cbs[idx];
  708. snp->srcu_data_have_cbs[idx] = 0;
  709. spin_unlock_irq_rcu_node(snp);
  710. if (cbs)
  711. srcu_schedule_cbs_snp(ssp, snp, mask, cbdelay);
  712. }
  713. }
  714. /* Occasionally prevent srcu_data counter wrap. */
  715. if (!(gpseq & counter_wrap_check))
  716. for_each_possible_cpu(cpu) {
  717. sdp = per_cpu_ptr(ssp->sda, cpu);
  718. spin_lock_irqsave_rcu_node(sdp, flags);
  719. if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed + 100))
  720. sdp->srcu_gp_seq_needed = gpseq;
  721. if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed_exp + 100))
  722. sdp->srcu_gp_seq_needed_exp = gpseq;
  723. spin_unlock_irqrestore_rcu_node(sdp, flags);
  724. }
  725. /* Callback initiation done, allow grace periods after next. */
  726. mutex_unlock(&ssp->srcu_cb_mutex);
  727. /* Start a new grace period if needed. */
  728. spin_lock_irq_rcu_node(ssp);
  729. gpseq = rcu_seq_current(&ssp->srcu_gp_seq);
  730. if (!rcu_seq_state(gpseq) &&
  731. ULONG_CMP_LT(gpseq, ssp->srcu_gp_seq_needed)) {
  732. srcu_gp_start(ssp);
  733. spin_unlock_irq_rcu_node(ssp);
  734. srcu_reschedule(ssp, 0);
  735. } else {
  736. spin_unlock_irq_rcu_node(ssp);
  737. }
  738. /* Transition to big if needed. */
  739. if (ss_state != SRCU_SIZE_SMALL && ss_state != SRCU_SIZE_BIG) {
  740. if (ss_state == SRCU_SIZE_ALLOC)
  741. init_srcu_struct_nodes(ssp, GFP_KERNEL);
  742. else
  743. smp_store_release(&ssp->srcu_size_state, ss_state + 1);
  744. }
  745. }
  746. /*
  747. * Funnel-locking scheme to scalably mediate many concurrent expedited
  748. * grace-period requests. This function is invoked for the first known
  749. * expedited request for a grace period that has already been requested,
  750. * but without expediting. To start a completely new grace period,
  751. * whether expedited or not, use srcu_funnel_gp_start() instead.
  752. */
  753. static void srcu_funnel_exp_start(struct srcu_struct *ssp, struct srcu_node *snp,
  754. unsigned long s)
  755. {
  756. unsigned long flags;
  757. unsigned long sgsne;
  758. if (snp)
  759. for (; snp != NULL; snp = snp->srcu_parent) {
  760. sgsne = READ_ONCE(snp->srcu_gp_seq_needed_exp);
  761. if (rcu_seq_done(&ssp->srcu_gp_seq, s) ||
  762. (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s)))
  763. return;
  764. spin_lock_irqsave_rcu_node(snp, flags);
  765. sgsne = snp->srcu_gp_seq_needed_exp;
  766. if (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s)) {
  767. spin_unlock_irqrestore_rcu_node(snp, flags);
  768. return;
  769. }
  770. WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s);
  771. spin_unlock_irqrestore_rcu_node(snp, flags);
  772. }
  773. spin_lock_irqsave_ssp_contention(ssp, &flags);
  774. if (ULONG_CMP_LT(ssp->srcu_gp_seq_needed_exp, s))
  775. WRITE_ONCE(ssp->srcu_gp_seq_needed_exp, s);
  776. spin_unlock_irqrestore_rcu_node(ssp, flags);
  777. }
  778. /*
  779. * Funnel-locking scheme to scalably mediate many concurrent grace-period
  780. * requests. The winner has to do the work of actually starting grace
  781. * period s. Losers must either ensure that their desired grace-period
  782. * number is recorded on at least their leaf srcu_node structure, or they
  783. * must take steps to invoke their own callbacks.
  784. *
  785. * Note that this function also does the work of srcu_funnel_exp_start(),
  786. * in some cases by directly invoking it.
  787. */
  788. static void srcu_funnel_gp_start(struct srcu_struct *ssp, struct srcu_data *sdp,
  789. unsigned long s, bool do_norm)
  790. {
  791. unsigned long flags;
  792. int idx = rcu_seq_ctr(s) % ARRAY_SIZE(sdp->mynode->srcu_have_cbs);
  793. unsigned long sgsne;
  794. struct srcu_node *snp;
  795. struct srcu_node *snp_leaf;
  796. unsigned long snp_seq;
  797. /* Ensure that snp node tree is fully initialized before traversing it */
  798. if (smp_load_acquire(&ssp->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER)
  799. snp_leaf = NULL;
  800. else
  801. snp_leaf = sdp->mynode;
  802. if (snp_leaf)
  803. /* Each pass through the loop does one level of the srcu_node tree. */
  804. for (snp = snp_leaf; snp != NULL; snp = snp->srcu_parent) {
  805. if (rcu_seq_done(&ssp->srcu_gp_seq, s) && snp != snp_leaf)
  806. return; /* GP already done and CBs recorded. */
  807. spin_lock_irqsave_rcu_node(snp, flags);
  808. snp_seq = snp->srcu_have_cbs[idx];
  809. if (!srcu_invl_snp_seq(snp_seq) && ULONG_CMP_GE(snp_seq, s)) {
  810. if (snp == snp_leaf && snp_seq == s)
  811. snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
  812. spin_unlock_irqrestore_rcu_node(snp, flags);
  813. if (snp == snp_leaf && snp_seq != s) {
  814. srcu_schedule_cbs_sdp(sdp, do_norm ? SRCU_INTERVAL : 0);
  815. return;
  816. }
  817. if (!do_norm)
  818. srcu_funnel_exp_start(ssp, snp, s);
  819. return;
  820. }
  821. snp->srcu_have_cbs[idx] = s;
  822. if (snp == snp_leaf)
  823. snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
  824. sgsne = snp->srcu_gp_seq_needed_exp;
  825. if (!do_norm && (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, s)))
  826. WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s);
  827. spin_unlock_irqrestore_rcu_node(snp, flags);
  828. }
  829. /* Top of tree, must ensure the grace period will be started. */
  830. spin_lock_irqsave_ssp_contention(ssp, &flags);
  831. if (ULONG_CMP_LT(ssp->srcu_gp_seq_needed, s)) {
  832. /*
  833. * Record need for grace period s. Pair with load
  834. * acquire setting up for initialization.
  835. */
  836. smp_store_release(&ssp->srcu_gp_seq_needed, s); /*^^^*/
  837. }
  838. if (!do_norm && ULONG_CMP_LT(ssp->srcu_gp_seq_needed_exp, s))
  839. WRITE_ONCE(ssp->srcu_gp_seq_needed_exp, s);
  840. /* If grace period not already done and none in progress, start it. */
  841. if (!rcu_seq_done(&ssp->srcu_gp_seq, s) &&
  842. rcu_seq_state(ssp->srcu_gp_seq) == SRCU_STATE_IDLE) {
  843. WARN_ON_ONCE(ULONG_CMP_GE(ssp->srcu_gp_seq, ssp->srcu_gp_seq_needed));
  844. srcu_gp_start(ssp);
  845. // And how can that list_add() in the "else" clause
  846. // possibly be safe for concurrent execution? Well,
  847. // it isn't. And it does not have to be. After all, it
  848. // can only be executed during early boot when there is only
  849. // the one boot CPU running with interrupts still disabled.
  850. if (likely(srcu_init_done))
  851. queue_delayed_work(rcu_gp_wq, &ssp->work,
  852. !!srcu_get_delay(ssp));
  853. else if (list_empty(&ssp->work.work.entry))
  854. list_add(&ssp->work.work.entry, &srcu_boot_list);
  855. }
  856. spin_unlock_irqrestore_rcu_node(ssp, flags);
  857. }
  858. /*
  859. * Wait until all readers counted by array index idx complete, but
  860. * loop an additional time if there is an expedited grace period pending.
  861. * The caller must ensure that ->srcu_idx is not changed while checking.
  862. */
  863. static bool try_check_zero(struct srcu_struct *ssp, int idx, int trycount)
  864. {
  865. unsigned long curdelay;
  866. curdelay = !srcu_get_delay(ssp);
  867. for (;;) {
  868. if (srcu_readers_active_idx_check(ssp, idx))
  869. return true;
  870. if ((--trycount + curdelay) <= 0)
  871. return false;
  872. udelay(srcu_retry_check_delay);
  873. }
  874. }
  875. /*
  876. * Increment the ->srcu_idx counter so that future SRCU readers will
  877. * use the other rank of the ->srcu_(un)lock_count[] arrays. This allows
  878. * us to wait for pre-existing readers in a starvation-free manner.
  879. */
  880. static void srcu_flip(struct srcu_struct *ssp)
  881. {
  882. /*
  883. * Ensure that if this updater saw a given reader's increment
  884. * from __srcu_read_lock(), that reader was using an old value
  885. * of ->srcu_idx. Also ensure that if a given reader sees the
  886. * new value of ->srcu_idx, this updater's earlier scans cannot
  887. * have seen that reader's increments (which is OK, because this
  888. * grace period need not wait on that reader).
  889. */
  890. smp_mb(); /* E */ /* Pairs with B and C. */
  891. WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 1);
  892. /*
  893. * Ensure that if the updater misses an __srcu_read_unlock()
  894. * increment, that task's next __srcu_read_lock() will see the
  895. * above counter update. Note that both this memory barrier
  896. * and the one in srcu_readers_active_idx_check() provide the
  897. * guarantee for __srcu_read_lock().
  898. */
  899. smp_mb(); /* D */ /* Pairs with C. */
  900. }
  901. /*
  902. * If SRCU is likely idle, return true, otherwise return false.
  903. *
  904. * Note that it is OK for several current from-idle requests for a new
  905. * grace period from idle to specify expediting because they will all end
  906. * up requesting the same grace period anyhow. So no loss.
  907. *
  908. * Note also that if any CPU (including the current one) is still invoking
  909. * callbacks, this function will nevertheless say "idle". This is not
  910. * ideal, but the overhead of checking all CPUs' callback lists is even
  911. * less ideal, especially on large systems. Furthermore, the wakeup
  912. * can happen before the callback is fully removed, so we have no choice
  913. * but to accept this type of error.
  914. *
  915. * This function is also subject to counter-wrap errors, but let's face
  916. * it, if this function was preempted for enough time for the counters
  917. * to wrap, it really doesn't matter whether or not we expedite the grace
  918. * period. The extra overhead of a needlessly expedited grace period is
  919. * negligible when amortized over that time period, and the extra latency
  920. * of a needlessly non-expedited grace period is similarly negligible.
  921. */
  922. static bool srcu_might_be_idle(struct srcu_struct *ssp)
  923. {
  924. unsigned long curseq;
  925. unsigned long flags;
  926. struct srcu_data *sdp;
  927. unsigned long t;
  928. unsigned long tlast;
  929. check_init_srcu_struct(ssp);
  930. /* If the local srcu_data structure has callbacks, not idle. */
  931. sdp = raw_cpu_ptr(ssp->sda);
  932. spin_lock_irqsave_rcu_node(sdp, flags);
  933. if (rcu_segcblist_pend_cbs(&sdp->srcu_cblist)) {
  934. spin_unlock_irqrestore_rcu_node(sdp, flags);
  935. return false; /* Callbacks already present, so not idle. */
  936. }
  937. spin_unlock_irqrestore_rcu_node(sdp, flags);
  938. /*
  939. * No local callbacks, so probabilistically probe global state.
  940. * Exact information would require acquiring locks, which would
  941. * kill scalability, hence the probabilistic nature of the probe.
  942. */
  943. /* First, see if enough time has passed since the last GP. */
  944. t = ktime_get_mono_fast_ns();
  945. tlast = READ_ONCE(ssp->srcu_last_gp_end);
  946. if (exp_holdoff == 0 ||
  947. time_in_range_open(t, tlast, tlast + exp_holdoff))
  948. return false; /* Too soon after last GP. */
  949. /* Next, check for probable idleness. */
  950. curseq = rcu_seq_current(&ssp->srcu_gp_seq);
  951. smp_mb(); /* Order ->srcu_gp_seq with ->srcu_gp_seq_needed. */
  952. if (ULONG_CMP_LT(curseq, READ_ONCE(ssp->srcu_gp_seq_needed)))
  953. return false; /* Grace period in progress, so not idle. */
  954. smp_mb(); /* Order ->srcu_gp_seq with prior access. */
  955. if (curseq != rcu_seq_current(&ssp->srcu_gp_seq))
  956. return false; /* GP # changed, so not idle. */
  957. return true; /* With reasonable probability, idle! */
  958. }
  959. /*
  960. * SRCU callback function to leak a callback.
  961. */
  962. static void srcu_leak_callback(struct rcu_head *rhp)
  963. {
  964. }
  965. /*
  966. * Start an SRCU grace period, and also queue the callback if non-NULL.
  967. */
  968. static unsigned long srcu_gp_start_if_needed(struct srcu_struct *ssp,
  969. struct rcu_head *rhp, bool do_norm)
  970. {
  971. unsigned long flags;
  972. int idx;
  973. bool needexp = false;
  974. bool needgp = false;
  975. unsigned long s;
  976. struct srcu_data *sdp;
  977. struct srcu_node *sdp_mynode;
  978. int ss_state;
  979. check_init_srcu_struct(ssp);
  980. idx = srcu_read_lock(ssp);
  981. ss_state = smp_load_acquire(&ssp->srcu_size_state);
  982. if (ss_state < SRCU_SIZE_WAIT_CALL)
  983. sdp = per_cpu_ptr(ssp->sda, get_boot_cpu_id());
  984. else
  985. sdp = raw_cpu_ptr(ssp->sda);
  986. spin_lock_irqsave_sdp_contention(sdp, &flags);
  987. if (rhp)
  988. rcu_segcblist_enqueue(&sdp->srcu_cblist, rhp);
  989. rcu_segcblist_advance(&sdp->srcu_cblist,
  990. rcu_seq_current(&ssp->srcu_gp_seq));
  991. s = rcu_seq_snap(&ssp->srcu_gp_seq);
  992. (void)rcu_segcblist_accelerate(&sdp->srcu_cblist, s);
  993. if (ULONG_CMP_LT(sdp->srcu_gp_seq_needed, s)) {
  994. sdp->srcu_gp_seq_needed = s;
  995. needgp = true;
  996. }
  997. if (!do_norm && ULONG_CMP_LT(sdp->srcu_gp_seq_needed_exp, s)) {
  998. sdp->srcu_gp_seq_needed_exp = s;
  999. needexp = true;
  1000. }
  1001. spin_unlock_irqrestore_rcu_node(sdp, flags);
  1002. /* Ensure that snp node tree is fully initialized before traversing it */
  1003. if (ss_state < SRCU_SIZE_WAIT_BARRIER)
  1004. sdp_mynode = NULL;
  1005. else
  1006. sdp_mynode = sdp->mynode;
  1007. if (needgp)
  1008. srcu_funnel_gp_start(ssp, sdp, s, do_norm);
  1009. else if (needexp)
  1010. srcu_funnel_exp_start(ssp, sdp_mynode, s);
  1011. srcu_read_unlock(ssp, idx);
  1012. return s;
  1013. }
  1014. /*
  1015. * Enqueue an SRCU callback on the srcu_data structure associated with
  1016. * the current CPU and the specified srcu_struct structure, initiating
  1017. * grace-period processing if it is not already running.
  1018. *
  1019. * Note that all CPUs must agree that the grace period extended beyond
  1020. * all pre-existing SRCU read-side critical section. On systems with
  1021. * more than one CPU, this means that when "func()" is invoked, each CPU
  1022. * is guaranteed to have executed a full memory barrier since the end of
  1023. * its last corresponding SRCU read-side critical section whose beginning
  1024. * preceded the call to call_srcu(). It also means that each CPU executing
  1025. * an SRCU read-side critical section that continues beyond the start of
  1026. * "func()" must have executed a memory barrier after the call_srcu()
  1027. * but before the beginning of that SRCU read-side critical section.
  1028. * Note that these guarantees include CPUs that are offline, idle, or
  1029. * executing in user mode, as well as CPUs that are executing in the kernel.
  1030. *
  1031. * Furthermore, if CPU A invoked call_srcu() and CPU B invoked the
  1032. * resulting SRCU callback function "func()", then both CPU A and CPU
  1033. * B are guaranteed to execute a full memory barrier during the time
  1034. * interval between the call to call_srcu() and the invocation of "func()".
  1035. * This guarantee applies even if CPU A and CPU B are the same CPU (but
  1036. * again only if the system has more than one CPU).
  1037. *
  1038. * Of course, these guarantees apply only for invocations of call_srcu(),
  1039. * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
  1040. * srcu_struct structure.
  1041. */
  1042. static void __call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp,
  1043. rcu_callback_t func, bool do_norm)
  1044. {
  1045. if (debug_rcu_head_queue(rhp)) {
  1046. /* Probable double call_srcu(), so leak the callback. */
  1047. WRITE_ONCE(rhp->func, srcu_leak_callback);
  1048. WARN_ONCE(1, "call_srcu(): Leaked duplicate callback\n");
  1049. return;
  1050. }
  1051. rhp->func = func;
  1052. (void)srcu_gp_start_if_needed(ssp, rhp, do_norm);
  1053. }
  1054. /**
  1055. * call_srcu() - Queue a callback for invocation after an SRCU grace period
  1056. * @ssp: srcu_struct in queue the callback
  1057. * @rhp: structure to be used for queueing the SRCU callback.
  1058. * @func: function to be invoked after the SRCU grace period
  1059. *
  1060. * The callback function will be invoked some time after a full SRCU
  1061. * grace period elapses, in other words after all pre-existing SRCU
  1062. * read-side critical sections have completed. However, the callback
  1063. * function might well execute concurrently with other SRCU read-side
  1064. * critical sections that started after call_srcu() was invoked. SRCU
  1065. * read-side critical sections are delimited by srcu_read_lock() and
  1066. * srcu_read_unlock(), and may be nested.
  1067. *
  1068. * The callback will be invoked from process context, but must nevertheless
  1069. * be fast and must not block.
  1070. */
  1071. void call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp,
  1072. rcu_callback_t func)
  1073. {
  1074. __call_srcu(ssp, rhp, func, true);
  1075. }
  1076. EXPORT_SYMBOL_GPL(call_srcu);
  1077. /*
  1078. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  1079. */
  1080. static void __synchronize_srcu(struct srcu_struct *ssp, bool do_norm)
  1081. {
  1082. struct rcu_synchronize rcu;
  1083. RCU_LOCKDEP_WARN(lockdep_is_held(ssp) ||
  1084. lock_is_held(&rcu_bh_lock_map) ||
  1085. lock_is_held(&rcu_lock_map) ||
  1086. lock_is_held(&rcu_sched_lock_map),
  1087. "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
  1088. if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
  1089. return;
  1090. might_sleep();
  1091. check_init_srcu_struct(ssp);
  1092. init_completion(&rcu.completion);
  1093. init_rcu_head_on_stack(&rcu.head);
  1094. __call_srcu(ssp, &rcu.head, wakeme_after_rcu, do_norm);
  1095. wait_for_completion(&rcu.completion);
  1096. destroy_rcu_head_on_stack(&rcu.head);
  1097. /*
  1098. * Make sure that later code is ordered after the SRCU grace
  1099. * period. This pairs with the spin_lock_irq_rcu_node()
  1100. * in srcu_invoke_callbacks(). Unlike Tree RCU, this is needed
  1101. * because the current CPU might have been totally uninvolved with
  1102. * (and thus unordered against) that grace period.
  1103. */
  1104. smp_mb();
  1105. }
  1106. /**
  1107. * synchronize_srcu_expedited - Brute-force SRCU grace period
  1108. * @ssp: srcu_struct with which to synchronize.
  1109. *
  1110. * Wait for an SRCU grace period to elapse, but be more aggressive about
  1111. * spinning rather than blocking when waiting.
  1112. *
  1113. * Note that synchronize_srcu_expedited() has the same deadlock and
  1114. * memory-ordering properties as does synchronize_srcu().
  1115. */
  1116. void synchronize_srcu_expedited(struct srcu_struct *ssp)
  1117. {
  1118. __synchronize_srcu(ssp, rcu_gp_is_normal());
  1119. }
  1120. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  1121. /**
  1122. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  1123. * @ssp: srcu_struct with which to synchronize.
  1124. *
  1125. * Wait for the count to drain to zero of both indexes. To avoid the
  1126. * possible starvation of synchronize_srcu(), it waits for the count of
  1127. * the index=((->srcu_idx & 1) ^ 1) to drain to zero at first,
  1128. * and then flip the srcu_idx and wait for the count of the other index.
  1129. *
  1130. * Can block; must be called from process context.
  1131. *
  1132. * Note that it is illegal to call synchronize_srcu() from the corresponding
  1133. * SRCU read-side critical section; doing so will result in deadlock.
  1134. * However, it is perfectly legal to call synchronize_srcu() on one
  1135. * srcu_struct from some other srcu_struct's read-side critical section,
  1136. * as long as the resulting graph of srcu_structs is acyclic.
  1137. *
  1138. * There are memory-ordering constraints implied by synchronize_srcu().
  1139. * On systems with more than one CPU, when synchronize_srcu() returns,
  1140. * each CPU is guaranteed to have executed a full memory barrier since
  1141. * the end of its last corresponding SRCU read-side critical section
  1142. * whose beginning preceded the call to synchronize_srcu(). In addition,
  1143. * each CPU having an SRCU read-side critical section that extends beyond
  1144. * the return from synchronize_srcu() is guaranteed to have executed a
  1145. * full memory barrier after the beginning of synchronize_srcu() and before
  1146. * the beginning of that SRCU read-side critical section. Note that these
  1147. * guarantees include CPUs that are offline, idle, or executing in user mode,
  1148. * as well as CPUs that are executing in the kernel.
  1149. *
  1150. * Furthermore, if CPU A invoked synchronize_srcu(), which returned
  1151. * to its caller on CPU B, then both CPU A and CPU B are guaranteed
  1152. * to have executed a full memory barrier during the execution of
  1153. * synchronize_srcu(). This guarantee applies even if CPU A and CPU B
  1154. * are the same CPU, but again only if the system has more than one CPU.
  1155. *
  1156. * Of course, these memory-ordering guarantees apply only when
  1157. * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
  1158. * passed the same srcu_struct structure.
  1159. *
  1160. * Implementation of these memory-ordering guarantees is similar to
  1161. * that of synchronize_rcu().
  1162. *
  1163. * If SRCU is likely idle, expedite the first request. This semantic
  1164. * was provided by Classic SRCU, and is relied upon by its users, so TREE
  1165. * SRCU must also provide it. Note that detecting idleness is heuristic
  1166. * and subject to both false positives and negatives.
  1167. */
  1168. void synchronize_srcu(struct srcu_struct *ssp)
  1169. {
  1170. if (srcu_might_be_idle(ssp) || rcu_gp_is_expedited())
  1171. synchronize_srcu_expedited(ssp);
  1172. else
  1173. __synchronize_srcu(ssp, true);
  1174. }
  1175. EXPORT_SYMBOL_GPL(synchronize_srcu);
  1176. /**
  1177. * get_state_synchronize_srcu - Provide an end-of-grace-period cookie
  1178. * @ssp: srcu_struct to provide cookie for.
  1179. *
  1180. * This function returns a cookie that can be passed to
  1181. * poll_state_synchronize_srcu(), which will return true if a full grace
  1182. * period has elapsed in the meantime. It is the caller's responsibility
  1183. * to make sure that grace period happens, for example, by invoking
  1184. * call_srcu() after return from get_state_synchronize_srcu().
  1185. */
  1186. unsigned long get_state_synchronize_srcu(struct srcu_struct *ssp)
  1187. {
  1188. // Any prior manipulation of SRCU-protected data must happen
  1189. // before the load from ->srcu_gp_seq.
  1190. smp_mb();
  1191. return rcu_seq_snap(&ssp->srcu_gp_seq);
  1192. }
  1193. EXPORT_SYMBOL_GPL(get_state_synchronize_srcu);
  1194. /**
  1195. * start_poll_synchronize_srcu - Provide cookie and start grace period
  1196. * @ssp: srcu_struct to provide cookie for.
  1197. *
  1198. * This function returns a cookie that can be passed to
  1199. * poll_state_synchronize_srcu(), which will return true if a full grace
  1200. * period has elapsed in the meantime. Unlike get_state_synchronize_srcu(),
  1201. * this function also ensures that any needed SRCU grace period will be
  1202. * started. This convenience does come at a cost in terms of CPU overhead.
  1203. */
  1204. unsigned long start_poll_synchronize_srcu(struct srcu_struct *ssp)
  1205. {
  1206. return srcu_gp_start_if_needed(ssp, NULL, true);
  1207. }
  1208. EXPORT_SYMBOL_GPL(start_poll_synchronize_srcu);
  1209. /**
  1210. * poll_state_synchronize_srcu - Has cookie's grace period ended?
  1211. * @ssp: srcu_struct to provide cookie for.
  1212. * @cookie: Return value from get_state_synchronize_srcu() or start_poll_synchronize_srcu().
  1213. *
  1214. * This function takes the cookie that was returned from either
  1215. * get_state_synchronize_srcu() or start_poll_synchronize_srcu(), and
  1216. * returns @true if an SRCU grace period elapsed since the time that the
  1217. * cookie was created.
  1218. *
  1219. * Because cookies are finite in size, wrapping/overflow is possible.
  1220. * This is more pronounced on 32-bit systems where cookies are 32 bits,
  1221. * where in theory wrapping could happen in about 14 hours assuming
  1222. * 25-microsecond expedited SRCU grace periods. However, a more likely
  1223. * overflow lower bound is on the order of 24 days in the case of
  1224. * one-millisecond SRCU grace periods. Of course, wrapping in a 64-bit
  1225. * system requires geologic timespans, as in more than seven million years
  1226. * even for expedited SRCU grace periods.
  1227. *
  1228. * Wrapping/overflow is much more of an issue for CONFIG_SMP=n systems
  1229. * that also have CONFIG_PREEMPTION=n, which selects Tiny SRCU. This uses
  1230. * a 16-bit cookie, which rcutorture routinely wraps in a matter of a
  1231. * few minutes. If this proves to be a problem, this counter will be
  1232. * expanded to the same size as for Tree SRCU.
  1233. */
  1234. bool poll_state_synchronize_srcu(struct srcu_struct *ssp, unsigned long cookie)
  1235. {
  1236. if (!rcu_seq_done(&ssp->srcu_gp_seq, cookie))
  1237. return false;
  1238. // Ensure that the end of the SRCU grace period happens before
  1239. // any subsequent code that the caller might execute.
  1240. smp_mb(); // ^^^
  1241. return true;
  1242. }
  1243. EXPORT_SYMBOL_GPL(poll_state_synchronize_srcu);
  1244. /*
  1245. * Callback function for srcu_barrier() use.
  1246. */
  1247. static void srcu_barrier_cb(struct rcu_head *rhp)
  1248. {
  1249. struct srcu_data *sdp;
  1250. struct srcu_struct *ssp;
  1251. sdp = container_of(rhp, struct srcu_data, srcu_barrier_head);
  1252. ssp = sdp->ssp;
  1253. if (atomic_dec_and_test(&ssp->srcu_barrier_cpu_cnt))
  1254. complete(&ssp->srcu_barrier_completion);
  1255. }
  1256. /*
  1257. * Enqueue an srcu_barrier() callback on the specified srcu_data
  1258. * structure's ->cblist. but only if that ->cblist already has at least one
  1259. * callback enqueued. Note that if a CPU already has callbacks enqueue,
  1260. * it must have already registered the need for a future grace period,
  1261. * so all we need do is enqueue a callback that will use the same grace
  1262. * period as the last callback already in the queue.
  1263. */
  1264. static void srcu_barrier_one_cpu(struct srcu_struct *ssp, struct srcu_data *sdp)
  1265. {
  1266. spin_lock_irq_rcu_node(sdp);
  1267. atomic_inc(&ssp->srcu_barrier_cpu_cnt);
  1268. sdp->srcu_barrier_head.func = srcu_barrier_cb;
  1269. debug_rcu_head_queue(&sdp->srcu_barrier_head);
  1270. if (!rcu_segcblist_entrain(&sdp->srcu_cblist,
  1271. &sdp->srcu_barrier_head)) {
  1272. debug_rcu_head_unqueue(&sdp->srcu_barrier_head);
  1273. atomic_dec(&ssp->srcu_barrier_cpu_cnt);
  1274. }
  1275. spin_unlock_irq_rcu_node(sdp);
  1276. }
  1277. /**
  1278. * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
  1279. * @ssp: srcu_struct on which to wait for in-flight callbacks.
  1280. */
  1281. void srcu_barrier(struct srcu_struct *ssp)
  1282. {
  1283. int cpu;
  1284. int idx;
  1285. unsigned long s = rcu_seq_snap(&ssp->srcu_barrier_seq);
  1286. check_init_srcu_struct(ssp);
  1287. mutex_lock(&ssp->srcu_barrier_mutex);
  1288. if (rcu_seq_done(&ssp->srcu_barrier_seq, s)) {
  1289. smp_mb(); /* Force ordering following return. */
  1290. mutex_unlock(&ssp->srcu_barrier_mutex);
  1291. return; /* Someone else did our work for us. */
  1292. }
  1293. rcu_seq_start(&ssp->srcu_barrier_seq);
  1294. init_completion(&ssp->srcu_barrier_completion);
  1295. /* Initial count prevents reaching zero until all CBs are posted. */
  1296. atomic_set(&ssp->srcu_barrier_cpu_cnt, 1);
  1297. idx = srcu_read_lock(ssp);
  1298. if (smp_load_acquire(&ssp->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER)
  1299. srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda, get_boot_cpu_id()));
  1300. else
  1301. for_each_possible_cpu(cpu)
  1302. srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda, cpu));
  1303. srcu_read_unlock(ssp, idx);
  1304. /* Remove the initial count, at which point reaching zero can happen. */
  1305. if (atomic_dec_and_test(&ssp->srcu_barrier_cpu_cnt))
  1306. complete(&ssp->srcu_barrier_completion);
  1307. wait_for_completion(&ssp->srcu_barrier_completion);
  1308. rcu_seq_end(&ssp->srcu_barrier_seq);
  1309. mutex_unlock(&ssp->srcu_barrier_mutex);
  1310. }
  1311. EXPORT_SYMBOL_GPL(srcu_barrier);
  1312. /**
  1313. * srcu_batches_completed - return batches completed.
  1314. * @ssp: srcu_struct on which to report batch completion.
  1315. *
  1316. * Report the number of batches, correlated with, but not necessarily
  1317. * precisely the same as, the number of grace periods that have elapsed.
  1318. */
  1319. unsigned long srcu_batches_completed(struct srcu_struct *ssp)
  1320. {
  1321. return READ_ONCE(ssp->srcu_idx);
  1322. }
  1323. EXPORT_SYMBOL_GPL(srcu_batches_completed);
  1324. /*
  1325. * Core SRCU state machine. Push state bits of ->srcu_gp_seq
  1326. * to SRCU_STATE_SCAN2, and invoke srcu_gp_end() when scan has
  1327. * completed in that state.
  1328. */
  1329. static void srcu_advance_state(struct srcu_struct *ssp)
  1330. {
  1331. int idx;
  1332. mutex_lock(&ssp->srcu_gp_mutex);
  1333. /*
  1334. * Because readers might be delayed for an extended period after
  1335. * fetching ->srcu_idx for their index, at any point in time there
  1336. * might well be readers using both idx=0 and idx=1. We therefore
  1337. * need to wait for readers to clear from both index values before
  1338. * invoking a callback.
  1339. *
  1340. * The load-acquire ensures that we see the accesses performed
  1341. * by the prior grace period.
  1342. */
  1343. idx = rcu_seq_state(smp_load_acquire(&ssp->srcu_gp_seq)); /* ^^^ */
  1344. if (idx == SRCU_STATE_IDLE) {
  1345. spin_lock_irq_rcu_node(ssp);
  1346. if (ULONG_CMP_GE(ssp->srcu_gp_seq, ssp->srcu_gp_seq_needed)) {
  1347. WARN_ON_ONCE(rcu_seq_state(ssp->srcu_gp_seq));
  1348. spin_unlock_irq_rcu_node(ssp);
  1349. mutex_unlock(&ssp->srcu_gp_mutex);
  1350. return;
  1351. }
  1352. idx = rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq));
  1353. if (idx == SRCU_STATE_IDLE)
  1354. srcu_gp_start(ssp);
  1355. spin_unlock_irq_rcu_node(ssp);
  1356. if (idx != SRCU_STATE_IDLE) {
  1357. mutex_unlock(&ssp->srcu_gp_mutex);
  1358. return; /* Someone else started the grace period. */
  1359. }
  1360. }
  1361. if (rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)) == SRCU_STATE_SCAN1) {
  1362. idx = 1 ^ (ssp->srcu_idx & 1);
  1363. if (!try_check_zero(ssp, idx, 1)) {
  1364. mutex_unlock(&ssp->srcu_gp_mutex);
  1365. return; /* readers present, retry later. */
  1366. }
  1367. srcu_flip(ssp);
  1368. spin_lock_irq_rcu_node(ssp);
  1369. rcu_seq_set_state(&ssp->srcu_gp_seq, SRCU_STATE_SCAN2);
  1370. ssp->srcu_n_exp_nodelay = 0;
  1371. spin_unlock_irq_rcu_node(ssp);
  1372. }
  1373. if (rcu_seq_state(READ_ONCE(ssp->srcu_gp_seq)) == SRCU_STATE_SCAN2) {
  1374. /*
  1375. * SRCU read-side critical sections are normally short,
  1376. * so check at least twice in quick succession after a flip.
  1377. */
  1378. idx = 1 ^ (ssp->srcu_idx & 1);
  1379. if (!try_check_zero(ssp, idx, 2)) {
  1380. mutex_unlock(&ssp->srcu_gp_mutex);
  1381. return; /* readers present, retry later. */
  1382. }
  1383. ssp->srcu_n_exp_nodelay = 0;
  1384. srcu_gp_end(ssp); /* Releases ->srcu_gp_mutex. */
  1385. }
  1386. }
  1387. /*
  1388. * Invoke a limited number of SRCU callbacks that have passed through
  1389. * their grace period. If there are more to do, SRCU will reschedule
  1390. * the workqueue. Note that needed memory barriers have been executed
  1391. * in this task's context by srcu_readers_active_idx_check().
  1392. */
  1393. static void srcu_invoke_callbacks(struct work_struct *work)
  1394. {
  1395. long len;
  1396. bool more;
  1397. struct rcu_cblist ready_cbs;
  1398. struct rcu_head *rhp;
  1399. struct srcu_data *sdp;
  1400. struct srcu_struct *ssp;
  1401. sdp = container_of(work, struct srcu_data, work);
  1402. ssp = sdp->ssp;
  1403. rcu_cblist_init(&ready_cbs);
  1404. spin_lock_irq_rcu_node(sdp);
  1405. rcu_segcblist_advance(&sdp->srcu_cblist,
  1406. rcu_seq_current(&ssp->srcu_gp_seq));
  1407. if (sdp->srcu_cblist_invoking ||
  1408. !rcu_segcblist_ready_cbs(&sdp->srcu_cblist)) {
  1409. spin_unlock_irq_rcu_node(sdp);
  1410. return; /* Someone else on the job or nothing to do. */
  1411. }
  1412. /* We are on the job! Extract and invoke ready callbacks. */
  1413. sdp->srcu_cblist_invoking = true;
  1414. rcu_segcblist_extract_done_cbs(&sdp->srcu_cblist, &ready_cbs);
  1415. len = ready_cbs.len;
  1416. spin_unlock_irq_rcu_node(sdp);
  1417. rhp = rcu_cblist_dequeue(&ready_cbs);
  1418. for (; rhp != NULL; rhp = rcu_cblist_dequeue(&ready_cbs)) {
  1419. debug_rcu_head_unqueue(rhp);
  1420. local_bh_disable();
  1421. rhp->func(rhp);
  1422. local_bh_enable();
  1423. }
  1424. WARN_ON_ONCE(ready_cbs.len);
  1425. /*
  1426. * Update counts, accelerate new callbacks, and if needed,
  1427. * schedule another round of callback invocation.
  1428. */
  1429. spin_lock_irq_rcu_node(sdp);
  1430. rcu_segcblist_add_len(&sdp->srcu_cblist, -len);
  1431. (void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
  1432. rcu_seq_snap(&ssp->srcu_gp_seq));
  1433. sdp->srcu_cblist_invoking = false;
  1434. more = rcu_segcblist_ready_cbs(&sdp->srcu_cblist);
  1435. spin_unlock_irq_rcu_node(sdp);
  1436. if (more)
  1437. srcu_schedule_cbs_sdp(sdp, 0);
  1438. }
  1439. /*
  1440. * Finished one round of SRCU grace period. Start another if there are
  1441. * more SRCU callbacks queued, otherwise put SRCU into not-running state.
  1442. */
  1443. static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay)
  1444. {
  1445. bool pushgp = true;
  1446. spin_lock_irq_rcu_node(ssp);
  1447. if (ULONG_CMP_GE(ssp->srcu_gp_seq, ssp->srcu_gp_seq_needed)) {
  1448. if (!WARN_ON_ONCE(rcu_seq_state(ssp->srcu_gp_seq))) {
  1449. /* All requests fulfilled, time to go idle. */
  1450. pushgp = false;
  1451. }
  1452. } else if (!rcu_seq_state(ssp->srcu_gp_seq)) {
  1453. /* Outstanding request and no GP. Start one. */
  1454. srcu_gp_start(ssp);
  1455. }
  1456. spin_unlock_irq_rcu_node(ssp);
  1457. if (pushgp)
  1458. queue_delayed_work(rcu_gp_wq, &ssp->work, delay);
  1459. }
  1460. /*
  1461. * This is the work-queue function that handles SRCU grace periods.
  1462. */
  1463. static void process_srcu(struct work_struct *work)
  1464. {
  1465. unsigned long curdelay;
  1466. unsigned long j;
  1467. struct srcu_struct *ssp;
  1468. ssp = container_of(work, struct srcu_struct, work.work);
  1469. srcu_advance_state(ssp);
  1470. curdelay = srcu_get_delay(ssp);
  1471. if (curdelay) {
  1472. WRITE_ONCE(ssp->reschedule_count, 0);
  1473. } else {
  1474. j = jiffies;
  1475. if (READ_ONCE(ssp->reschedule_jiffies) == j) {
  1476. WRITE_ONCE(ssp->reschedule_count, READ_ONCE(ssp->reschedule_count) + 1);
  1477. if (READ_ONCE(ssp->reschedule_count) > srcu_max_nodelay)
  1478. curdelay = 1;
  1479. } else {
  1480. WRITE_ONCE(ssp->reschedule_count, 1);
  1481. WRITE_ONCE(ssp->reschedule_jiffies, j);
  1482. }
  1483. }
  1484. srcu_reschedule(ssp, curdelay);
  1485. }
  1486. void srcutorture_get_gp_data(enum rcutorture_type test_type,
  1487. struct srcu_struct *ssp, int *flags,
  1488. unsigned long *gp_seq)
  1489. {
  1490. if (test_type != SRCU_FLAVOR)
  1491. return;
  1492. *flags = 0;
  1493. *gp_seq = rcu_seq_current(&ssp->srcu_gp_seq);
  1494. }
  1495. EXPORT_SYMBOL_GPL(srcutorture_get_gp_data);
  1496. static const char * const srcu_size_state_name[] = {
  1497. "SRCU_SIZE_SMALL",
  1498. "SRCU_SIZE_ALLOC",
  1499. "SRCU_SIZE_WAIT_BARRIER",
  1500. "SRCU_SIZE_WAIT_CALL",
  1501. "SRCU_SIZE_WAIT_CBS1",
  1502. "SRCU_SIZE_WAIT_CBS2",
  1503. "SRCU_SIZE_WAIT_CBS3",
  1504. "SRCU_SIZE_WAIT_CBS4",
  1505. "SRCU_SIZE_BIG",
  1506. "SRCU_SIZE_???",
  1507. };
  1508. void srcu_torture_stats_print(struct srcu_struct *ssp, char *tt, char *tf)
  1509. {
  1510. int cpu;
  1511. int idx;
  1512. unsigned long s0 = 0, s1 = 0;
  1513. int ss_state = READ_ONCE(ssp->srcu_size_state);
  1514. int ss_state_idx = ss_state;
  1515. idx = ssp->srcu_idx & 0x1;
  1516. if (ss_state < 0 || ss_state >= ARRAY_SIZE(srcu_size_state_name))
  1517. ss_state_idx = ARRAY_SIZE(srcu_size_state_name) - 1;
  1518. pr_alert("%s%s Tree SRCU g%ld state %d (%s)",
  1519. tt, tf, rcu_seq_current(&ssp->srcu_gp_seq), ss_state,
  1520. srcu_size_state_name[ss_state_idx]);
  1521. if (!ssp->sda) {
  1522. // Called after cleanup_srcu_struct(), perhaps.
  1523. pr_cont(" No per-CPU srcu_data structures (->sda == NULL).\n");
  1524. } else {
  1525. pr_cont(" per-CPU(idx=%d):", idx);
  1526. for_each_possible_cpu(cpu) {
  1527. unsigned long l0, l1;
  1528. unsigned long u0, u1;
  1529. long c0, c1;
  1530. struct srcu_data *sdp;
  1531. sdp = per_cpu_ptr(ssp->sda, cpu);
  1532. u0 = data_race(sdp->srcu_unlock_count[!idx]);
  1533. u1 = data_race(sdp->srcu_unlock_count[idx]);
  1534. /*
  1535. * Make sure that a lock is always counted if the corresponding
  1536. * unlock is counted.
  1537. */
  1538. smp_rmb();
  1539. l0 = data_race(sdp->srcu_lock_count[!idx]);
  1540. l1 = data_race(sdp->srcu_lock_count[idx]);
  1541. c0 = l0 - u0;
  1542. c1 = l1 - u1;
  1543. pr_cont(" %d(%ld,%ld %c)",
  1544. cpu, c0, c1,
  1545. "C."[rcu_segcblist_empty(&sdp->srcu_cblist)]);
  1546. s0 += c0;
  1547. s1 += c1;
  1548. }
  1549. pr_cont(" T(%ld,%ld)\n", s0, s1);
  1550. }
  1551. if (SRCU_SIZING_IS_TORTURE())
  1552. srcu_transition_to_big(ssp);
  1553. }
  1554. EXPORT_SYMBOL_GPL(srcu_torture_stats_print);
  1555. static int __init srcu_bootup_announce(void)
  1556. {
  1557. pr_info("Hierarchical SRCU implementation.\n");
  1558. if (exp_holdoff != DEFAULT_SRCU_EXP_HOLDOFF)
  1559. pr_info("\tNon-default auto-expedite holdoff of %lu ns.\n", exp_holdoff);
  1560. if (srcu_retry_check_delay != SRCU_DEFAULT_RETRY_CHECK_DELAY)
  1561. pr_info("\tNon-default retry check delay of %lu us.\n", srcu_retry_check_delay);
  1562. if (srcu_max_nodelay != SRCU_DEFAULT_MAX_NODELAY)
  1563. pr_info("\tNon-default max no-delay of %lu.\n", srcu_max_nodelay);
  1564. pr_info("\tMax phase no-delay instances is %lu.\n", srcu_max_nodelay_phase);
  1565. return 0;
  1566. }
  1567. early_initcall(srcu_bootup_announce);
  1568. void __init srcu_init(void)
  1569. {
  1570. struct srcu_struct *ssp;
  1571. /* Decide on srcu_struct-size strategy. */
  1572. if (SRCU_SIZING_IS(SRCU_SIZING_AUTO)) {
  1573. if (nr_cpu_ids >= big_cpu_lim) {
  1574. convert_to_big = SRCU_SIZING_INIT; // Don't bother waiting for contention.
  1575. pr_info("%s: Setting srcu_struct sizes to big.\n", __func__);
  1576. } else {
  1577. convert_to_big = SRCU_SIZING_NONE | SRCU_SIZING_CONTEND;
  1578. pr_info("%s: Setting srcu_struct sizes based on contention.\n", __func__);
  1579. }
  1580. }
  1581. /*
  1582. * Once that is set, call_srcu() can follow the normal path and
  1583. * queue delayed work. This must follow RCU workqueues creation
  1584. * and timers initialization.
  1585. */
  1586. srcu_init_done = true;
  1587. while (!list_empty(&srcu_boot_list)) {
  1588. ssp = list_first_entry(&srcu_boot_list, struct srcu_struct,
  1589. work.work.entry);
  1590. list_del_init(&ssp->work.work.entry);
  1591. if (SRCU_SIZING_IS(SRCU_SIZING_INIT) && ssp->srcu_size_state == SRCU_SIZE_SMALL)
  1592. ssp->srcu_size_state = SRCU_SIZE_ALLOC;
  1593. queue_work(rcu_gp_wq, &ssp->work.work);
  1594. }
  1595. }
  1596. #ifdef CONFIG_MODULES
  1597. /* Initialize any global-scope srcu_struct structures used by this module. */
  1598. static int srcu_module_coming(struct module *mod)
  1599. {
  1600. int i;
  1601. struct srcu_struct **sspp = mod->srcu_struct_ptrs;
  1602. int ret;
  1603. for (i = 0; i < mod->num_srcu_structs; i++) {
  1604. ret = init_srcu_struct(*(sspp++));
  1605. if (WARN_ON_ONCE(ret))
  1606. return ret;
  1607. }
  1608. return 0;
  1609. }
  1610. /* Clean up any global-scope srcu_struct structures used by this module. */
  1611. static void srcu_module_going(struct module *mod)
  1612. {
  1613. int i;
  1614. struct srcu_struct **sspp = mod->srcu_struct_ptrs;
  1615. for (i = 0; i < mod->num_srcu_structs; i++)
  1616. cleanup_srcu_struct(*(sspp++));
  1617. }
  1618. /* Handle one module, either coming or going. */
  1619. static int srcu_module_notify(struct notifier_block *self,
  1620. unsigned long val, void *data)
  1621. {
  1622. struct module *mod = data;
  1623. int ret = 0;
  1624. switch (val) {
  1625. case MODULE_STATE_COMING:
  1626. ret = srcu_module_coming(mod);
  1627. break;
  1628. case MODULE_STATE_GOING:
  1629. srcu_module_going(mod);
  1630. break;
  1631. default:
  1632. break;
  1633. }
  1634. return ret;
  1635. }
  1636. static struct notifier_block srcu_module_nb = {
  1637. .notifier_call = srcu_module_notify,
  1638. .priority = 0,
  1639. };
  1640. static __init int init_srcu_module_notifier(void)
  1641. {
  1642. int ret;
  1643. ret = register_module_notifier(&srcu_module_nb);
  1644. if (ret)
  1645. pr_warn("Failed to register srcu module notifier\n");
  1646. return ret;
  1647. }
  1648. late_initcall(init_srcu_module_notifier);
  1649. #endif /* #ifdef CONFIG_MODULES */