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 <paulmck@linux.ibm.com> 9 * Lai Jiangshan <laijs@cn.fujitsu.com> 10 * 11 * For detailed explanation of Read-Copy Update mechanism see - 12 * Documentation/RCU/ *.txt 13 * 14 */ 15 16 #define pr_fmt(fmt) "rcu: " fmt 17 18 #include <linux/export.h> 19 #include <linux/mutex.h> 20 #include <linux/percpu.h> 21 #include <linux/preempt.h> 22 #include <linux/rcupdate_wait.h> 23 #include <linux/sched.h> 24 #include <linux/smp.h> 25 #include <linux/delay.h> 26 #include <linux/module.h> 27 #include <linux/slab.h> 28 #include <linux/srcu.h> 29 30 #include "rcu.h" 31 #include "rcu_segcblist.h" 32 33 /* Holdoff in nanoseconds for auto-expediting. */ 34 #define DEFAULT_SRCU_EXP_HOLDOFF (25 * 1000) 35 static ulong exp_holdoff = DEFAULT_SRCU_EXP_HOLDOFF; 36 module_param(exp_holdoff, ulong, 0444); 37 38 /* Overflow-check frequency. N bits roughly says every 2**N grace periods. */ 39 static ulong counter_wrap_check = (ULONG_MAX >> 2); 40 module_param(counter_wrap_check, ulong, 0444); 41 42 /* 43 * Control conversion to SRCU_SIZE_BIG: 44 * 0: Don't convert at all. 45 * 1: Convert at init_srcu_struct() time. 46 * 2: Convert when rcutorture invokes srcu_torture_stats_print(). 47 * 3: Decide at boot time based on system shape (default). 48 * 0x1x: Convert when excessive contention encountered. 49 */ 50 #define SRCU_SIZING_NONE 0 51 #define SRCU_SIZING_INIT 1 52 #define SRCU_SIZING_TORTURE 2 53 #define SRCU_SIZING_AUTO 3 54 #define SRCU_SIZING_CONTEND 0x10 55 #define SRCU_SIZING_IS(x) ((convert_to_big & ~SRCU_SIZING_CONTEND) == x) 56 #define SRCU_SIZING_IS_NONE() (SRCU_SIZING_IS(SRCU_SIZING_NONE)) 57 #define SRCU_SIZING_IS_INIT() (SRCU_SIZING_IS(SRCU_SIZING_INIT)) 58 #define SRCU_SIZING_IS_TORTURE() (SRCU_SIZING_IS(SRCU_SIZING_TORTURE)) 59 #define SRCU_SIZING_IS_CONTEND() (convert_to_big & SRCU_SIZING_CONTEND) 60 static int convert_to_big = SRCU_SIZING_AUTO; 61 module_param(convert_to_big, int, 0444); 62 63 /* Number of CPUs to trigger init_srcu_struct()-time transition to big. */ 64 static int big_cpu_lim __read_mostly = 128; 65 module_param(big_cpu_lim, int, 0444); 66 67 /* Contention events per jiffy to initiate transition to big. */ 68 static int small_contention_lim __read_mostly = 100; 69 module_param(small_contention_lim, int, 0444); 70 71 /* Early-boot callback-management, so early that no lock is required! */ 72 static LIST_HEAD(srcu_boot_list); 73 static bool __read_mostly srcu_init_done; 74 75 static void srcu_invoke_callbacks(struct work_struct *work); 76 static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay); 77 static void process_srcu(struct work_struct *work); 78 static void srcu_delay_timer(struct timer_list *t); 79 80 /* Wrappers for lock acquisition and release, see raw_spin_lock_rcu_node(). */ 81 #define spin_lock_rcu_node(p) \ 82 do { \ 83 spin_lock(&ACCESS_PRIVATE(p, lock)); \ 84 smp_mb__after_unlock_lock(); \ 85 } while (0) 86 87 #define spin_unlock_rcu_node(p) spin_unlock(&ACCESS_PRIVATE(p, lock)) 88 89 #define spin_lock_irq_rcu_node(p) \ 90 do { \ 91 spin_lock_irq(&ACCESS_PRIVATE(p, lock)); \ 92 smp_mb__after_unlock_lock(); \ 93 } while (0) 94 95 #define spin_unlock_irq_rcu_node(p) \ 96 spin_unlock_irq(&ACCESS_PRIVATE(p, lock)) 97 98 #define spin_lock_irqsave_rcu_node(p, flags) \ 99 do { \ 100 spin_lock_irqsave(&ACCESS_PRIVATE(p, lock), flags); \ 101 smp_mb__after_unlock_lock(); \ 102 } while (0) 103 104 #define spin_trylock_irqsave_rcu_node(p, flags) \ 105 ({ \ 106 bool ___locked = spin_trylock_irqsave(&ACCESS_PRIVATE(p, lock), flags); \ 107 \ 108 if (___locked) \ 109 smp_mb__after_unlock_lock(); \ 110 ___locked; \ 111 }) 112 113 #define spin_unlock_irqrestore_rcu_node(p, flags) \ 114 spin_unlock_irqrestore(&ACCESS_PRIVATE(p, lock), flags) \ 115 116 /* 117 * Initialize SRCU per-CPU data. Note that statically allocated 118 * srcu_struct structures might already have srcu_read_lock() and 119 * srcu_read_unlock() running against them. So if the is_static 120 * parameter is set, don't initialize ->srcu_ctrs[].srcu_locks and 121 * ->srcu_ctrs[].srcu_unlocks. 122 */ 123 static void init_srcu_struct_data(struct srcu_struct *ssp) 124 { 125 int cpu; 126 struct srcu_data *sdp; 127 128 /* 129 * Initialize the per-CPU srcu_data array, which feeds into the 130 * leaves of the srcu_node tree. 131 */ 132 for_each_possible_cpu(cpu) { 133 sdp = per_cpu_ptr(ssp->sda, cpu); 134 spin_lock_init(&ACCESS_PRIVATE(sdp, lock)); 135 rcu_segcblist_init(&sdp->srcu_cblist); 136 sdp->srcu_cblist_invoking = false; 137 sdp->srcu_gp_seq_needed = ssp->srcu_sup->srcu_gp_seq; 138 sdp->srcu_gp_seq_needed_exp = ssp->srcu_sup->srcu_gp_seq; 139 sdp->srcu_barrier_head.next = &sdp->srcu_barrier_head; 140 sdp->mynode = NULL; 141 sdp->cpu = cpu; 142 INIT_WORK(&sdp->work, srcu_invoke_callbacks); 143 timer_setup(&sdp->delay_work, srcu_delay_timer, 0); 144 sdp->ssp = ssp; 145 } 146 } 147 148 /* Invalid seq state, used during snp node initialization */ 149 #define SRCU_SNP_INIT_SEQ 0x2 150 151 /* 152 * Check whether sequence number corresponding to snp node, 153 * is invalid. 154 */ 155 static inline bool srcu_invl_snp_seq(unsigned long s) 156 { 157 return s == SRCU_SNP_INIT_SEQ; 158 } 159 160 /* 161 * Allocated and initialize SRCU combining tree. Returns @true if 162 * allocation succeeded and @false otherwise. 163 */ 164 static bool init_srcu_struct_nodes(struct srcu_struct *ssp, gfp_t gfp_flags) 165 { 166 int cpu; 167 int i; 168 int level = 0; 169 int levelspread[RCU_NUM_LVLS]; 170 struct srcu_data *sdp; 171 struct srcu_node *snp; 172 struct srcu_node *snp_first; 173 174 /* Initialize geometry if it has not already been initialized. */ 175 rcu_init_geometry(); 176 ssp->srcu_sup->node = kcalloc(rcu_num_nodes, sizeof(*ssp->srcu_sup->node), gfp_flags); 177 if (!ssp->srcu_sup->node) 178 return false; 179 180 /* Work out the overall tree geometry. */ 181 ssp->srcu_sup->level[0] = &ssp->srcu_sup->node[0]; 182 for (i = 1; i < rcu_num_lvls; i++) 183 ssp->srcu_sup->level[i] = ssp->srcu_sup->level[i - 1] + num_rcu_lvl[i - 1]; 184 rcu_init_levelspread(levelspread, num_rcu_lvl); 185 186 /* Each pass through this loop initializes one srcu_node structure. */ 187 srcu_for_each_node_breadth_first(ssp, snp) { 188 spin_lock_init(&ACCESS_PRIVATE(snp, lock)); 189 BUILD_BUG_ON(ARRAY_SIZE(snp->srcu_have_cbs) != 190 ARRAY_SIZE(snp->srcu_data_have_cbs)); 191 for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++) { 192 snp->srcu_have_cbs[i] = SRCU_SNP_INIT_SEQ; 193 snp->srcu_data_have_cbs[i] = 0; 194 } 195 snp->srcu_gp_seq_needed_exp = SRCU_SNP_INIT_SEQ; 196 snp->grplo = -1; 197 snp->grphi = -1; 198 if (snp == &ssp->srcu_sup->node[0]) { 199 /* Root node, special case. */ 200 snp->srcu_parent = NULL; 201 continue; 202 } 203 204 /* Non-root node. */ 205 if (snp == ssp->srcu_sup->level[level + 1]) 206 level++; 207 snp->srcu_parent = ssp->srcu_sup->level[level - 1] + 208 (snp - ssp->srcu_sup->level[level]) / 209 levelspread[level - 1]; 210 } 211 212 /* 213 * Initialize the per-CPU srcu_data array, which feeds into the 214 * leaves of the srcu_node tree. 215 */ 216 level = rcu_num_lvls - 1; 217 snp_first = ssp->srcu_sup->level[level]; 218 for_each_possible_cpu(cpu) { 219 sdp = per_cpu_ptr(ssp->sda, cpu); 220 sdp->mynode = &snp_first[cpu / levelspread[level]]; 221 for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) { 222 if (snp->grplo < 0) 223 snp->grplo = cpu; 224 snp->grphi = cpu; 225 } 226 sdp->grpmask = 1UL << (cpu - sdp->mynode->grplo); 227 } 228 smp_store_release(&ssp->srcu_sup->srcu_size_state, SRCU_SIZE_WAIT_BARRIER); 229 return true; 230 } 231 232 /* 233 * Initialize non-compile-time initialized fields, including the 234 * associated srcu_node and srcu_data structures. The is_static parameter 235 * tells us that ->sda has already been wired up to srcu_data. 236 */ 237 static int init_srcu_struct_fields(struct srcu_struct *ssp, bool is_static) 238 { 239 if (!is_static) 240 ssp->srcu_sup = kzalloc(sizeof(*ssp->srcu_sup), GFP_KERNEL); 241 if (!ssp->srcu_sup) 242 return -ENOMEM; 243 if (!is_static) 244 spin_lock_init(&ACCESS_PRIVATE(ssp->srcu_sup, lock)); 245 ssp->srcu_sup->srcu_size_state = SRCU_SIZE_SMALL; 246 ssp->srcu_sup->node = NULL; 247 mutex_init(&ssp->srcu_sup->srcu_cb_mutex); 248 mutex_init(&ssp->srcu_sup->srcu_gp_mutex); 249 ssp->srcu_sup->srcu_gp_seq = SRCU_GP_SEQ_INITIAL_VAL; 250 ssp->srcu_sup->srcu_barrier_seq = 0; 251 mutex_init(&ssp->srcu_sup->srcu_barrier_mutex); 252 atomic_set(&ssp->srcu_sup->srcu_barrier_cpu_cnt, 0); 253 INIT_DELAYED_WORK(&ssp->srcu_sup->work, process_srcu); 254 ssp->srcu_sup->sda_is_static = is_static; 255 if (!is_static) { 256 ssp->sda = alloc_percpu(struct srcu_data); 257 ssp->srcu_ctrp = &ssp->sda->srcu_ctrs[0]; 258 } 259 if (!ssp->sda) 260 goto err_free_sup; 261 init_srcu_struct_data(ssp); 262 ssp->srcu_sup->srcu_gp_seq_needed_exp = SRCU_GP_SEQ_INITIAL_VAL; 263 ssp->srcu_sup->srcu_last_gp_end = ktime_get_mono_fast_ns(); 264 if (READ_ONCE(ssp->srcu_sup->srcu_size_state) == SRCU_SIZE_SMALL && SRCU_SIZING_IS_INIT()) { 265 if (!init_srcu_struct_nodes(ssp, is_static ? GFP_ATOMIC : GFP_KERNEL)) 266 goto err_free_sda; 267 WRITE_ONCE(ssp->srcu_sup->srcu_size_state, SRCU_SIZE_BIG); 268 } 269 ssp->srcu_sup->srcu_ssp = ssp; 270 smp_store_release(&ssp->srcu_sup->srcu_gp_seq_needed, 271 SRCU_GP_SEQ_INITIAL_VAL); /* Init done. */ 272 return 0; 273 274 err_free_sda: 275 if (!is_static) { 276 free_percpu(ssp->sda); 277 ssp->sda = NULL; 278 } 279 err_free_sup: 280 if (!is_static) { 281 kfree(ssp->srcu_sup); 282 ssp->srcu_sup = NULL; 283 } 284 return -ENOMEM; 285 } 286 287 #ifdef CONFIG_DEBUG_LOCK_ALLOC 288 289 static int 290 __init_srcu_struct_common(struct srcu_struct *ssp, const char *name, struct lock_class_key *key) 291 { 292 /* Don't re-initialize a lock while it is held. */ 293 debug_check_no_locks_freed((void *)ssp, sizeof(*ssp)); 294 lockdep_init_map(&ssp->dep_map, name, key, 0); 295 return init_srcu_struct_fields(ssp, false); 296 } 297 298 int __init_srcu_struct(struct srcu_struct *ssp, const char *name, struct lock_class_key *key) 299 { 300 ssp->srcu_reader_flavor = 0; 301 return __init_srcu_struct_common(ssp, name, key); 302 } 303 EXPORT_SYMBOL_GPL(__init_srcu_struct); 304 305 int __init_srcu_struct_fast(struct srcu_struct *ssp, const char *name, struct lock_class_key *key) 306 { 307 ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST; 308 return __init_srcu_struct_common(ssp, name, key); 309 } 310 EXPORT_SYMBOL_GPL(__init_srcu_struct_fast); 311 312 int __init_srcu_struct_fast_updown(struct srcu_struct *ssp, const char *name, 313 struct lock_class_key *key) 314 { 315 ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST_UPDOWN; 316 return __init_srcu_struct_common(ssp, name, key); 317 } 318 EXPORT_SYMBOL_GPL(__init_srcu_struct_fast_updown); 319 320 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */ 321 322 /** 323 * init_srcu_struct - initialize a sleep-RCU structure 324 * @ssp: structure to initialize. 325 * 326 * Use this in place of DEFINE_SRCU() and DEFINE_STATIC_SRCU() 327 * for non-static srcu_struct structures that are to be passed to 328 * srcu_read_lock(), srcu_read_lock_nmisafe(), and friends. It is necessary 329 * to invoke this on a given srcu_struct before passing that srcu_struct 330 * to any other function. Each srcu_struct represents a separate domain 331 * of SRCU protection. 332 */ 333 int init_srcu_struct(struct srcu_struct *ssp) 334 { 335 ssp->srcu_reader_flavor = 0; 336 return init_srcu_struct_fields(ssp, false); 337 } 338 EXPORT_SYMBOL_GPL(init_srcu_struct); 339 340 /** 341 * init_srcu_struct_fast - initialize a fast-reader sleep-RCU structure 342 * @ssp: structure to initialize. 343 * 344 * Use this in place of DEFINE_SRCU_FAST() and DEFINE_STATIC_SRCU_FAST() 345 * for non-static srcu_struct structures that are to be passed to 346 * srcu_read_lock_fast() and friends. It is necessary to invoke this on a 347 * given srcu_struct before passing that srcu_struct to any other function. 348 * Each srcu_struct represents a separate domain of SRCU protection. 349 */ 350 int init_srcu_struct_fast(struct srcu_struct *ssp) 351 { 352 ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST; 353 return init_srcu_struct_fields(ssp, false); 354 } 355 EXPORT_SYMBOL_GPL(init_srcu_struct_fast); 356 357 /** 358 * init_srcu_struct_fast_updown - initialize a fast-reader up/down sleep-RCU structure 359 * @ssp: structure to initialize. 360 * 361 * Use this function in place of DEFINE_SRCU_FAST_UPDOWN() and 362 * DEFINE_STATIC_SRCU_FAST_UPDOWN() for non-static srcu_struct 363 * structures that are to be passed to srcu_read_lock_fast_updown(), 364 * srcu_down_read_fast(), and friends. It is necessary to invoke this on a 365 * given srcu_struct before passing that srcu_struct to any other function. 366 * Each srcu_struct represents a separate domain of SRCU protection. 367 */ 368 int init_srcu_struct_fast_updown(struct srcu_struct *ssp) 369 { 370 ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST_UPDOWN; 371 return init_srcu_struct_fields(ssp, false); 372 } 373 EXPORT_SYMBOL_GPL(init_srcu_struct_fast_updown); 374 375 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */ 376 377 /* 378 * Initiate a transition to SRCU_SIZE_BIG with lock held. 379 */ 380 static void __srcu_transition_to_big(struct srcu_struct *ssp) 381 { 382 lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock)); 383 smp_store_release(&ssp->srcu_sup->srcu_size_state, SRCU_SIZE_ALLOC); 384 } 385 386 /* 387 * Initiate an idempotent transition to SRCU_SIZE_BIG. 388 */ 389 static void srcu_transition_to_big(struct srcu_struct *ssp) 390 { 391 unsigned long flags; 392 393 /* Double-checked locking on ->srcu_size-state. */ 394 if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) != SRCU_SIZE_SMALL) 395 return; 396 spin_lock_irqsave_rcu_node(ssp->srcu_sup, flags); 397 if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) != SRCU_SIZE_SMALL) { 398 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags); 399 return; 400 } 401 __srcu_transition_to_big(ssp); 402 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags); 403 } 404 405 /* 406 * Check to see if the just-encountered contention event justifies 407 * a transition to SRCU_SIZE_BIG. 408 */ 409 static void spin_lock_irqsave_check_contention(struct srcu_struct *ssp) 410 { 411 unsigned long j; 412 413 if (!SRCU_SIZING_IS_CONTEND() || ssp->srcu_sup->srcu_size_state) 414 return; 415 j = jiffies; 416 if (ssp->srcu_sup->srcu_size_jiffies != j) { 417 ssp->srcu_sup->srcu_size_jiffies = j; 418 ssp->srcu_sup->srcu_n_lock_retries = 0; 419 } 420 if (++ssp->srcu_sup->srcu_n_lock_retries <= small_contention_lim) 421 return; 422 __srcu_transition_to_big(ssp); 423 } 424 425 /* 426 * Acquire the specified srcu_data structure's ->lock, but check for 427 * excessive contention, which results in initiation of a transition 428 * to SRCU_SIZE_BIG. But only if the srcutree.convert_to_big module 429 * parameter permits this. 430 */ 431 static void spin_lock_irqsave_sdp_contention(struct srcu_data *sdp, unsigned long *flags) 432 { 433 struct srcu_struct *ssp = sdp->ssp; 434 435 if (spin_trylock_irqsave_rcu_node(sdp, *flags)) 436 return; 437 spin_lock_irqsave_rcu_node(ssp->srcu_sup, *flags); 438 spin_lock_irqsave_check_contention(ssp); 439 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, *flags); 440 spin_lock_irqsave_rcu_node(sdp, *flags); 441 } 442 443 /* 444 * Acquire the specified srcu_struct structure's ->lock, but check for 445 * excessive contention, which results in initiation of a transition 446 * to SRCU_SIZE_BIG. But only if the srcutree.convert_to_big module 447 * parameter permits this. 448 */ 449 static void spin_lock_irqsave_ssp_contention(struct srcu_struct *ssp, unsigned long *flags) 450 { 451 if (spin_trylock_irqsave_rcu_node(ssp->srcu_sup, *flags)) 452 return; 453 spin_lock_irqsave_rcu_node(ssp->srcu_sup, *flags); 454 spin_lock_irqsave_check_contention(ssp); 455 } 456 457 /* 458 * First-use initialization of statically allocated srcu_struct 459 * structure. Wiring up the combining tree is more than can be 460 * done with compile-time initialization, so this check is added 461 * to each update-side SRCU primitive. Use ssp->lock, which -is- 462 * compile-time initialized, to resolve races involving multiple 463 * CPUs trying to garner first-use privileges. 464 */ 465 static void check_init_srcu_struct(struct srcu_struct *ssp) 466 { 467 unsigned long flags; 468 469 /* The smp_load_acquire() pairs with the smp_store_release(). */ 470 if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq_needed))) /*^^^*/ 471 return; /* Already initialized. */ 472 spin_lock_irqsave_rcu_node(ssp->srcu_sup, flags); 473 if (!rcu_seq_state(ssp->srcu_sup->srcu_gp_seq_needed)) { 474 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags); 475 return; 476 } 477 init_srcu_struct_fields(ssp, true); 478 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags); 479 } 480 481 /* 482 * Is the current or any upcoming grace period to be expedited? 483 */ 484 static bool srcu_gp_is_expedited(struct srcu_struct *ssp) 485 { 486 struct srcu_usage *sup = ssp->srcu_sup; 487 488 return ULONG_CMP_LT(READ_ONCE(sup->srcu_gp_seq), READ_ONCE(sup->srcu_gp_seq_needed_exp)); 489 } 490 491 /* 492 * Computes approximate total of the readers' ->srcu_ctrs[].srcu_locks 493 * values for the rank of per-CPU counters specified by idx, and returns 494 * true if the caller did the proper barrier (gp), and if the count of 495 * the locks matches that of the unlocks passed in. 496 */ 497 static bool srcu_readers_lock_idx(struct srcu_struct *ssp, int idx, bool gp, unsigned long unlocks) 498 { 499 int cpu; 500 unsigned long mask = 0; 501 unsigned long sum = 0; 502 503 for_each_possible_cpu(cpu) { 504 struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu); 505 506 sum += atomic_long_read(&sdp->srcu_ctrs[idx].srcu_locks); 507 if (IS_ENABLED(CONFIG_PROVE_RCU)) 508 mask = mask | READ_ONCE(sdp->srcu_reader_flavor); 509 } 510 WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) && (mask & (mask - 1)), 511 "Mixed reader flavors for srcu_struct at %ps.\n", ssp); 512 if (mask & SRCU_READ_FLAVOR_SLOWGP && !gp) 513 return false; 514 return sum == unlocks; 515 } 516 517 /* 518 * Returns approximate total of the readers' ->srcu_ctrs[].srcu_unlocks 519 * values for the rank of per-CPU counters specified by idx. 520 */ 521 static unsigned long srcu_readers_unlock_idx(struct srcu_struct *ssp, int idx, unsigned long *rdm) 522 { 523 int cpu; 524 unsigned long mask = ssp->srcu_reader_flavor; 525 unsigned long sum = 0; 526 527 for_each_possible_cpu(cpu) { 528 struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu); 529 530 sum += atomic_long_read(&sdp->srcu_ctrs[idx].srcu_unlocks); 531 mask = mask | READ_ONCE(sdp->srcu_reader_flavor); 532 } 533 WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) && (mask & (mask - 1)), 534 "Mixed reader flavors for srcu_struct at %ps.\n", ssp); 535 *rdm = mask; 536 return sum; 537 } 538 539 /* 540 * Return true if the number of pre-existing readers is determined to 541 * be zero. 542 */ 543 static bool srcu_readers_active_idx_check(struct srcu_struct *ssp, int idx) 544 { 545 bool did_gp; 546 unsigned long rdm; 547 unsigned long unlocks; 548 549 unlocks = srcu_readers_unlock_idx(ssp, idx, &rdm); 550 did_gp = !!(rdm & SRCU_READ_FLAVOR_SLOWGP); 551 552 /* 553 * Make sure that a lock is always counted if the corresponding 554 * unlock is counted. Needs to be a smp_mb() as the read side may 555 * contain a read from a variable that is written to before the 556 * synchronize_srcu() in the write side. In this case smp_mb()s 557 * A and B (or X and Y) act like the store buffering pattern. 558 * 559 * This smp_mb() also pairs with smp_mb() C (or, in the case of X, 560 * Z) to prevent accesses after the synchronize_srcu() from being 561 * executed before the grace period ends. 562 */ 563 if (!did_gp) 564 smp_mb(); /* A */ 565 else if (srcu_gp_is_expedited(ssp)) 566 synchronize_rcu_expedited(); /* X */ 567 else 568 synchronize_rcu(); /* X */ 569 570 /* 571 * If the locks are the same as the unlocks, then there must have 572 * been no readers on this index at some point in this function. 573 * But there might be more readers, as a task might have read 574 * the current ->srcu_ctrp but not yet have incremented its CPU's 575 * ->srcu_ctrs[idx].srcu_locks counter. In fact, it is possible 576 * that most of the tasks have been preempted between fetching 577 * ->srcu_ctrp and incrementing ->srcu_ctrs[idx].srcu_locks. And 578 * there could be almost (ULONG_MAX / sizeof(struct task_struct)) 579 * tasks in a system whose address space was fully populated 580 * with memory. Call this quantity Nt. 581 * 582 * So suppose that the updater is preempted at this 583 * point in the code for a long time. That now-preempted 584 * updater has already flipped ->srcu_ctrp (possibly during 585 * the preceding grace period), done an smp_mb() (again, 586 * possibly during the preceding grace period), and summed up 587 * the ->srcu_ctrs[idx].srcu_unlocks counters. How many times 588 * can a given one of the aforementioned Nt tasks increment the 589 * old ->srcu_ctrp value's ->srcu_ctrs[idx].srcu_locks counter, 590 * in the absence of nesting? 591 * 592 * It can clearly do so once, given that it has already fetched 593 * the old value of ->srcu_ctrp and is just about to use that 594 * value to index its increment of ->srcu_ctrs[idx].srcu_locks. 595 * But as soon as it leaves that SRCU read-side critical section, 596 * it will increment ->srcu_ctrs[idx].srcu_unlocks, which must 597 * follow the updater's above read from that same value. Thus, 598 as soon the reading task does an smp_mb() and a later fetch from 599 * ->srcu_ctrp, that task will be guaranteed to get the new index. 600 * Except that the increment of ->srcu_ctrs[idx].srcu_unlocks 601 * in __srcu_read_unlock() is after the smp_mb(), and the fetch 602 * from ->srcu_ctrp in __srcu_read_lock() is before the smp_mb(). 603 * Thus, that task might not see the new value of ->srcu_ctrp until 604 * the -second- __srcu_read_lock(), which in turn means that this 605 * task might well increment ->srcu_ctrs[idx].srcu_locks for the 606 * old value of ->srcu_ctrp twice, not just once. 607 * 608 * However, it is important to note that a given smp_mb() takes 609 * effect not just for the task executing it, but also for any 610 * later task running on that same CPU. 611 * 612 * That is, there can be almost Nt + Nc further increments 613 * of ->srcu_ctrs[idx].srcu_locks for the old index, where Nc 614 * is the number of CPUs. But this is OK because the size of 615 * the task_struct structure limits the value of Nt and current 616 * systems limit Nc to a few thousand. 617 * 618 * OK, but what about nesting? This does impose a limit on 619 * nesting of half of the size of the task_struct structure 620 * (measured in bytes), which should be sufficient. A late 2022 621 * TREE01 rcutorture run reported this size to be no less than 622 * 9408 bytes, allowing up to 4704 levels of nesting, which is 623 * comfortably beyond excessive. Especially on 64-bit systems, 624 * which are unlikely to be configured with an address space fully 625 * populated with memory, at least not anytime soon. 626 */ 627 return srcu_readers_lock_idx(ssp, idx, did_gp, unlocks); 628 } 629 630 /** 631 * srcu_readers_active - returns true if there are readers. and false 632 * otherwise 633 * @ssp: which srcu_struct to count active readers (holding srcu_read_lock). 634 * 635 * Note that this is not an atomic primitive, and can therefore suffer 636 * severe errors when invoked on an active srcu_struct. That said, it 637 * can be useful as an error check at cleanup time. 638 */ 639 static bool srcu_readers_active(struct srcu_struct *ssp) 640 { 641 int cpu; 642 unsigned long sum = 0; 643 644 for_each_possible_cpu(cpu) { 645 struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu); 646 647 sum += atomic_long_read(&sdp->srcu_ctrs[0].srcu_locks); 648 sum += atomic_long_read(&sdp->srcu_ctrs[1].srcu_locks); 649 sum -= atomic_long_read(&sdp->srcu_ctrs[0].srcu_unlocks); 650 sum -= atomic_long_read(&sdp->srcu_ctrs[1].srcu_unlocks); 651 } 652 return sum; 653 } 654 655 /* 656 * We use an adaptive strategy for synchronize_srcu() and especially for 657 * synchronize_srcu_expedited(). We spin for a fixed time period 658 * (defined below, boot time configurable) to allow SRCU readers to exit 659 * their read-side critical sections. If there are still some readers 660 * after one jiffy, we repeatedly block for one jiffy time periods. 661 * The blocking time is increased as the grace-period age increases, 662 * with max blocking time capped at 10 jiffies. 663 */ 664 #define SRCU_DEFAULT_RETRY_CHECK_DELAY 5 665 666 static ulong srcu_retry_check_delay = SRCU_DEFAULT_RETRY_CHECK_DELAY; 667 module_param(srcu_retry_check_delay, ulong, 0444); 668 669 #define SRCU_INTERVAL 1 // Base delay if no expedited GPs pending. 670 #define SRCU_MAX_INTERVAL 10 // Maximum incremental delay from slow readers. 671 672 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_LO 3UL // Lowmark on default per-GP-phase 673 // no-delay instances. 674 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_HI 1000UL // Highmark on default per-GP-phase 675 // no-delay instances. 676 677 #define SRCU_UL_CLAMP_LO(val, low) ((val) > (low) ? (val) : (low)) 678 #define SRCU_UL_CLAMP_HI(val, high) ((val) < (high) ? (val) : (high)) 679 #define SRCU_UL_CLAMP(val, low, high) SRCU_UL_CLAMP_HI(SRCU_UL_CLAMP_LO((val), (low)), (high)) 680 // per-GP-phase no-delay instances adjusted to allow non-sleeping poll upto 681 // one jiffies time duration. Mult by 2 is done to factor in the srcu_get_delay() 682 // called from process_srcu(). 683 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED \ 684 (2UL * USEC_PER_SEC / HZ / SRCU_DEFAULT_RETRY_CHECK_DELAY) 685 686 // Maximum per-GP-phase consecutive no-delay instances. 687 #define SRCU_DEFAULT_MAX_NODELAY_PHASE \ 688 SRCU_UL_CLAMP(SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED, \ 689 SRCU_DEFAULT_MAX_NODELAY_PHASE_LO, \ 690 SRCU_DEFAULT_MAX_NODELAY_PHASE_HI) 691 692 static ulong srcu_max_nodelay_phase = SRCU_DEFAULT_MAX_NODELAY_PHASE; 693 module_param(srcu_max_nodelay_phase, ulong, 0444); 694 695 // Maximum consecutive no-delay instances. 696 #define SRCU_DEFAULT_MAX_NODELAY (SRCU_DEFAULT_MAX_NODELAY_PHASE > 100 ? \ 697 SRCU_DEFAULT_MAX_NODELAY_PHASE : 100) 698 699 static ulong srcu_max_nodelay = SRCU_DEFAULT_MAX_NODELAY; 700 module_param(srcu_max_nodelay, ulong, 0444); 701 702 /* 703 * Return grace-period delay, zero if there are expedited grace 704 * periods pending, SRCU_INTERVAL otherwise. 705 */ 706 static unsigned long srcu_get_delay(struct srcu_struct *ssp) 707 { 708 unsigned long gpstart; 709 unsigned long j; 710 unsigned long jbase = SRCU_INTERVAL; 711 struct srcu_usage *sup = ssp->srcu_sup; 712 713 lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock)); 714 if (srcu_gp_is_expedited(ssp)) 715 jbase = 0; 716 if (rcu_seq_state(READ_ONCE(sup->srcu_gp_seq))) { 717 j = jiffies - 1; 718 gpstart = READ_ONCE(sup->srcu_gp_start); 719 if (time_after(j, gpstart)) 720 jbase += j - gpstart; 721 if (!jbase) { 722 ASSERT_EXCLUSIVE_WRITER(sup->srcu_n_exp_nodelay); 723 WRITE_ONCE(sup->srcu_n_exp_nodelay, READ_ONCE(sup->srcu_n_exp_nodelay) + 1); 724 if (READ_ONCE(sup->srcu_n_exp_nodelay) > srcu_max_nodelay_phase) 725 jbase = 1; 726 } 727 } 728 return jbase > SRCU_MAX_INTERVAL ? SRCU_MAX_INTERVAL : jbase; 729 } 730 731 /** 732 * cleanup_srcu_struct - deconstruct a sleep-RCU structure 733 * @ssp: structure to clean up. 734 * 735 * Must invoke this after you are finished using a given srcu_struct that 736 * was initialized via init_srcu_struct(), else you leak memory. 737 */ 738 void cleanup_srcu_struct(struct srcu_struct *ssp) 739 { 740 int cpu; 741 unsigned long delay; 742 struct srcu_usage *sup = ssp->srcu_sup; 743 744 spin_lock_irq_rcu_node(ssp->srcu_sup); 745 delay = srcu_get_delay(ssp); 746 spin_unlock_irq_rcu_node(ssp->srcu_sup); 747 if (WARN_ON(!delay)) 748 return; /* Just leak it! */ 749 if (WARN_ON(srcu_readers_active(ssp))) 750 return; /* Just leak it! */ 751 flush_delayed_work(&sup->work); 752 for_each_possible_cpu(cpu) { 753 struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu); 754 755 timer_delete_sync(&sdp->delay_work); 756 flush_work(&sdp->work); 757 if (WARN_ON(rcu_segcblist_n_cbs(&sdp->srcu_cblist))) 758 return; /* Forgot srcu_barrier(), so just leak it! */ 759 } 760 if (WARN_ON(rcu_seq_state(READ_ONCE(sup->srcu_gp_seq)) != SRCU_STATE_IDLE) || 761 WARN_ON(rcu_seq_current(&sup->srcu_gp_seq) != sup->srcu_gp_seq_needed) || 762 WARN_ON(srcu_readers_active(ssp))) { 763 pr_info("%s: Active srcu_struct %p read state: %d gp state: %lu/%lu\n", 764 __func__, ssp, rcu_seq_state(READ_ONCE(sup->srcu_gp_seq)), 765 rcu_seq_current(&sup->srcu_gp_seq), sup->srcu_gp_seq_needed); 766 return; // Caller forgot to stop doing call_srcu()? 767 // Or caller invoked start_poll_synchronize_srcu() 768 // and then cleanup_srcu_struct() before that grace 769 // period ended? 770 } 771 kfree(sup->node); 772 sup->node = NULL; 773 sup->srcu_size_state = SRCU_SIZE_SMALL; 774 if (!sup->sda_is_static) { 775 free_percpu(ssp->sda); 776 ssp->sda = NULL; 777 kfree(sup); 778 ssp->srcu_sup = NULL; 779 } 780 } 781 EXPORT_SYMBOL_GPL(cleanup_srcu_struct); 782 783 /* 784 * Check for consistent reader flavor. 785 */ 786 void __srcu_check_read_flavor(struct srcu_struct *ssp, int read_flavor) 787 { 788 int old_read_flavor; 789 struct srcu_data *sdp; 790 791 /* NMI-unsafe use in NMI is a bad sign, as is multi-bit read_flavor values. */ 792 WARN_ON_ONCE(read_flavor != SRCU_READ_FLAVOR_NMI && 793 read_flavor != SRCU_READ_FLAVOR_FAST && in_nmi()); 794 WARN_ON_ONCE(read_flavor & (read_flavor - 1)); 795 796 sdp = raw_cpu_ptr(ssp->sda); 797 old_read_flavor = READ_ONCE(sdp->srcu_reader_flavor); 798 WARN_ON_ONCE(ssp->srcu_reader_flavor && read_flavor != ssp->srcu_reader_flavor); 799 WARN_ON_ONCE(old_read_flavor && ssp->srcu_reader_flavor && 800 old_read_flavor != ssp->srcu_reader_flavor); 801 WARN_ON_ONCE(read_flavor == SRCU_READ_FLAVOR_FAST && !ssp->srcu_reader_flavor); 802 if (!old_read_flavor) { 803 old_read_flavor = cmpxchg(&sdp->srcu_reader_flavor, 0, read_flavor); 804 if (!old_read_flavor) 805 return; 806 } 807 WARN_ONCE(old_read_flavor != read_flavor, "CPU %d old state %d new state %d\n", sdp->cpu, old_read_flavor, read_flavor); 808 } 809 EXPORT_SYMBOL_GPL(__srcu_check_read_flavor); 810 811 /* 812 * Counts the new reader in the appropriate per-CPU element of the 813 * srcu_struct. 814 * Returns a guaranteed non-negative index that must be passed to the 815 * matching __srcu_read_unlock(). 816 */ 817 int __srcu_read_lock(struct srcu_struct *ssp) 818 { 819 struct srcu_ctr __percpu *scp = READ_ONCE(ssp->srcu_ctrp); 820 821 this_cpu_inc(scp->srcu_locks.counter); 822 smp_mb(); /* B */ /* Avoid leaking the critical section. */ 823 return __srcu_ptr_to_ctr(ssp, scp); 824 } 825 EXPORT_SYMBOL_GPL(__srcu_read_lock); 826 827 /* 828 * Removes the count for the old reader from the appropriate per-CPU 829 * element of the srcu_struct. Note that this may well be a different 830 * CPU than that which was incremented by the corresponding srcu_read_lock(). 831 */ 832 void __srcu_read_unlock(struct srcu_struct *ssp, int idx) 833 { 834 smp_mb(); /* C */ /* Avoid leaking the critical section. */ 835 this_cpu_inc(__srcu_ctr_to_ptr(ssp, idx)->srcu_unlocks.counter); 836 } 837 EXPORT_SYMBOL_GPL(__srcu_read_unlock); 838 839 #ifdef CONFIG_NEED_SRCU_NMI_SAFE 840 841 /* 842 * Counts the new reader in the appropriate per-CPU element of the 843 * srcu_struct, but in an NMI-safe manner using RMW atomics. 844 * Returns an index that must be passed to the matching srcu_read_unlock(). 845 */ 846 int __srcu_read_lock_nmisafe(struct srcu_struct *ssp) 847 { 848 struct srcu_ctr __percpu *scpp = READ_ONCE(ssp->srcu_ctrp); 849 struct srcu_ctr *scp = raw_cpu_ptr(scpp); 850 851 atomic_long_inc(&scp->srcu_locks); 852 smp_mb__after_atomic(); /* B */ /* Avoid leaking the critical section. */ 853 return __srcu_ptr_to_ctr(ssp, scpp); 854 } 855 EXPORT_SYMBOL_GPL(__srcu_read_lock_nmisafe); 856 857 /* 858 * Removes the count for the old reader from the appropriate per-CPU 859 * element of the srcu_struct. Note that this may well be a different 860 * CPU than that which was incremented by the corresponding srcu_read_lock(). 861 */ 862 void __srcu_read_unlock_nmisafe(struct srcu_struct *ssp, int idx) 863 { 864 smp_mb__before_atomic(); /* C */ /* Avoid leaking the critical section. */ 865 atomic_long_inc(&raw_cpu_ptr(__srcu_ctr_to_ptr(ssp, idx))->srcu_unlocks); 866 } 867 EXPORT_SYMBOL_GPL(__srcu_read_unlock_nmisafe); 868 869 #endif // CONFIG_NEED_SRCU_NMI_SAFE 870 871 /* 872 * Start an SRCU grace period. 873 */ 874 static void srcu_gp_start(struct srcu_struct *ssp) 875 { 876 int state; 877 878 lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock)); 879 WARN_ON_ONCE(ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed)); 880 WRITE_ONCE(ssp->srcu_sup->srcu_gp_start, jiffies); 881 WRITE_ONCE(ssp->srcu_sup->srcu_n_exp_nodelay, 0); 882 smp_mb(); /* Order prior store to ->srcu_gp_seq_needed vs. GP start. */ 883 rcu_seq_start(&ssp->srcu_sup->srcu_gp_seq); 884 state = rcu_seq_state(ssp->srcu_sup->srcu_gp_seq); 885 WARN_ON_ONCE(state != SRCU_STATE_SCAN1); 886 } 887 888 889 static void srcu_delay_timer(struct timer_list *t) 890 { 891 struct srcu_data *sdp = container_of(t, struct srcu_data, delay_work); 892 893 queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work); 894 } 895 896 static void srcu_queue_delayed_work_on(struct srcu_data *sdp, 897 unsigned long delay) 898 { 899 if (!delay) { 900 queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work); 901 return; 902 } 903 904 timer_reduce(&sdp->delay_work, jiffies + delay); 905 } 906 907 /* 908 * Schedule callback invocation for the specified srcu_data structure, 909 * if possible, on the corresponding CPU. 910 */ 911 static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay) 912 { 913 srcu_queue_delayed_work_on(sdp, delay); 914 } 915 916 /* 917 * Schedule callback invocation for all srcu_data structures associated 918 * with the specified srcu_node structure that have callbacks for the 919 * just-completed grace period, the one corresponding to idx. If possible, 920 * schedule this invocation on the corresponding CPUs. 921 */ 922 static void srcu_schedule_cbs_snp(struct srcu_struct *ssp, struct srcu_node *snp, 923 unsigned long mask, unsigned long delay) 924 { 925 int cpu; 926 927 for (cpu = snp->grplo; cpu <= snp->grphi; cpu++) { 928 if (!(mask & (1UL << (cpu - snp->grplo)))) 929 continue; 930 srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, cpu), delay); 931 } 932 } 933 934 /* 935 * Note the end of an SRCU grace period. Initiates callback invocation 936 * and starts a new grace period if needed. 937 * 938 * The ->srcu_cb_mutex acquisition does not protect any data, but 939 * instead prevents more than one grace period from starting while we 940 * are initiating callback invocation. This allows the ->srcu_have_cbs[] 941 * array to have a finite number of elements. 942 */ 943 static void srcu_gp_end(struct srcu_struct *ssp) 944 { 945 unsigned long cbdelay = 1; 946 bool cbs; 947 bool last_lvl; 948 int cpu; 949 unsigned long gpseq; 950 int idx; 951 unsigned long mask; 952 struct srcu_data *sdp; 953 unsigned long sgsne; 954 struct srcu_node *snp; 955 int ss_state; 956 struct srcu_usage *sup = ssp->srcu_sup; 957 958 /* Prevent more than one additional grace period. */ 959 mutex_lock(&sup->srcu_cb_mutex); 960 961 /* End the current grace period. */ 962 spin_lock_irq_rcu_node(sup); 963 idx = rcu_seq_state(sup->srcu_gp_seq); 964 WARN_ON_ONCE(idx != SRCU_STATE_SCAN2); 965 if (srcu_gp_is_expedited(ssp)) 966 cbdelay = 0; 967 968 WRITE_ONCE(sup->srcu_last_gp_end, ktime_get_mono_fast_ns()); 969 rcu_seq_end(&sup->srcu_gp_seq); 970 gpseq = rcu_seq_current(&sup->srcu_gp_seq); 971 if (ULONG_CMP_LT(sup->srcu_gp_seq_needed_exp, gpseq)) 972 WRITE_ONCE(sup->srcu_gp_seq_needed_exp, gpseq); 973 spin_unlock_irq_rcu_node(sup); 974 mutex_unlock(&sup->srcu_gp_mutex); 975 /* A new grace period can start at this point. But only one. */ 976 977 /* Initiate callback invocation as needed. */ 978 ss_state = smp_load_acquire(&sup->srcu_size_state); 979 if (ss_state < SRCU_SIZE_WAIT_BARRIER) { 980 srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, get_boot_cpu_id()), 981 cbdelay); 982 } else { 983 idx = rcu_seq_ctr(gpseq) % ARRAY_SIZE(snp->srcu_have_cbs); 984 srcu_for_each_node_breadth_first(ssp, snp) { 985 spin_lock_irq_rcu_node(snp); 986 cbs = false; 987 last_lvl = snp >= sup->level[rcu_num_lvls - 1]; 988 if (last_lvl) 989 cbs = ss_state < SRCU_SIZE_BIG || snp->srcu_have_cbs[idx] == gpseq; 990 snp->srcu_have_cbs[idx] = gpseq; 991 rcu_seq_set_state(&snp->srcu_have_cbs[idx], 1); 992 sgsne = snp->srcu_gp_seq_needed_exp; 993 if (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, gpseq)) 994 WRITE_ONCE(snp->srcu_gp_seq_needed_exp, gpseq); 995 if (ss_state < SRCU_SIZE_BIG) 996 mask = ~0; 997 else 998 mask = snp->srcu_data_have_cbs[idx]; 999 snp->srcu_data_have_cbs[idx] = 0; 1000 spin_unlock_irq_rcu_node(snp); 1001 if (cbs) 1002 srcu_schedule_cbs_snp(ssp, snp, mask, cbdelay); 1003 } 1004 } 1005 1006 /* Occasionally prevent srcu_data counter wrap. */ 1007 if (!(gpseq & counter_wrap_check)) 1008 for_each_possible_cpu(cpu) { 1009 sdp = per_cpu_ptr(ssp->sda, cpu); 1010 spin_lock_irq_rcu_node(sdp); 1011 if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed + 100)) 1012 sdp->srcu_gp_seq_needed = gpseq; 1013 if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed_exp + 100)) 1014 sdp->srcu_gp_seq_needed_exp = gpseq; 1015 spin_unlock_irq_rcu_node(sdp); 1016 } 1017 1018 /* Callback initiation done, allow grace periods after next. */ 1019 mutex_unlock(&sup->srcu_cb_mutex); 1020 1021 /* Start a new grace period if needed. */ 1022 spin_lock_irq_rcu_node(sup); 1023 gpseq = rcu_seq_current(&sup->srcu_gp_seq); 1024 if (!rcu_seq_state(gpseq) && 1025 ULONG_CMP_LT(gpseq, sup->srcu_gp_seq_needed)) { 1026 srcu_gp_start(ssp); 1027 spin_unlock_irq_rcu_node(sup); 1028 srcu_reschedule(ssp, 0); 1029 } else { 1030 spin_unlock_irq_rcu_node(sup); 1031 } 1032 1033 /* Transition to big if needed. */ 1034 if (ss_state != SRCU_SIZE_SMALL && ss_state != SRCU_SIZE_BIG) { 1035 if (ss_state == SRCU_SIZE_ALLOC) 1036 init_srcu_struct_nodes(ssp, GFP_KERNEL); 1037 else 1038 smp_store_release(&sup->srcu_size_state, ss_state + 1); 1039 } 1040 } 1041 1042 /* 1043 * Funnel-locking scheme to scalably mediate many concurrent expedited 1044 * grace-period requests. This function is invoked for the first known 1045 * expedited request for a grace period that has already been requested, 1046 * but without expediting. To start a completely new grace period, 1047 * whether expedited or not, use srcu_funnel_gp_start() instead. 1048 */ 1049 static void srcu_funnel_exp_start(struct srcu_struct *ssp, struct srcu_node *snp, 1050 unsigned long s) 1051 { 1052 unsigned long flags; 1053 unsigned long sgsne; 1054 1055 if (snp) 1056 for (; snp != NULL; snp = snp->srcu_parent) { 1057 sgsne = READ_ONCE(snp->srcu_gp_seq_needed_exp); 1058 if (WARN_ON_ONCE(rcu_seq_done(&ssp->srcu_sup->srcu_gp_seq, s)) || 1059 (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s))) 1060 return; 1061 spin_lock_irqsave_rcu_node(snp, flags); 1062 sgsne = snp->srcu_gp_seq_needed_exp; 1063 if (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s)) { 1064 spin_unlock_irqrestore_rcu_node(snp, flags); 1065 return; 1066 } 1067 WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s); 1068 spin_unlock_irqrestore_rcu_node(snp, flags); 1069 } 1070 spin_lock_irqsave_ssp_contention(ssp, &flags); 1071 if (ULONG_CMP_LT(ssp->srcu_sup->srcu_gp_seq_needed_exp, s)) 1072 WRITE_ONCE(ssp->srcu_sup->srcu_gp_seq_needed_exp, s); 1073 spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags); 1074 } 1075 1076 /* 1077 * Funnel-locking scheme to scalably mediate many concurrent grace-period 1078 * requests. The winner has to do the work of actually starting grace 1079 * period s. Losers must either ensure that their desired grace-period 1080 * number is recorded on at least their leaf srcu_node structure, or they 1081 * must take steps to invoke their own callbacks. 1082 * 1083 * Note that this function also does the work of srcu_funnel_exp_start(), 1084 * in some cases by directly invoking it. 1085 * 1086 * The srcu read lock should be hold around this function. And s is a seq snap 1087 * after holding that lock. 1088 */ 1089 static void srcu_funnel_gp_start(struct srcu_struct *ssp, struct srcu_data *sdp, 1090 unsigned long s, bool do_norm) 1091 { 1092 unsigned long flags; 1093 int idx = rcu_seq_ctr(s) % ARRAY_SIZE(sdp->mynode->srcu_have_cbs); 1094 unsigned long sgsne; 1095 struct srcu_node *snp; 1096 struct srcu_node *snp_leaf; 1097 unsigned long snp_seq; 1098 struct srcu_usage *sup = ssp->srcu_sup; 1099 1100 /* Ensure that snp node tree is fully initialized before traversing it */ 1101 if (smp_load_acquire(&sup->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER) 1102 snp_leaf = NULL; 1103 else 1104 snp_leaf = sdp->mynode; 1105 1106 if (snp_leaf) 1107 /* Each pass through the loop does one level of the srcu_node tree. */ 1108 for (snp = snp_leaf; snp != NULL; snp = snp->srcu_parent) { 1109 if (WARN_ON_ONCE(rcu_seq_done(&sup->srcu_gp_seq, s)) && snp != snp_leaf) 1110 return; /* GP already done and CBs recorded. */ 1111 spin_lock_irqsave_rcu_node(snp, flags); 1112 snp_seq = snp->srcu_have_cbs[idx]; 1113 if (!srcu_invl_snp_seq(snp_seq) && ULONG_CMP_GE(snp_seq, s)) { 1114 if (snp == snp_leaf && snp_seq == s) 1115 snp->srcu_data_have_cbs[idx] |= sdp->grpmask; 1116 spin_unlock_irqrestore_rcu_node(snp, flags); 1117 if (snp == snp_leaf && snp_seq != s) { 1118 srcu_schedule_cbs_sdp(sdp, do_norm ? SRCU_INTERVAL : 0); 1119 return; 1120 } 1121 if (!do_norm) 1122 srcu_funnel_exp_start(ssp, snp, s); 1123 return; 1124 } 1125 snp->srcu_have_cbs[idx] = s; 1126 if (snp == snp_leaf) 1127 snp->srcu_data_have_cbs[idx] |= sdp->grpmask; 1128 sgsne = snp->srcu_gp_seq_needed_exp; 1129 if (!do_norm && (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, s))) 1130 WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s); 1131 spin_unlock_irqrestore_rcu_node(snp, flags); 1132 } 1133 1134 /* Top of tree, must ensure the grace period will be started. */ 1135 spin_lock_irqsave_ssp_contention(ssp, &flags); 1136 if (ULONG_CMP_LT(sup->srcu_gp_seq_needed, s)) { 1137 /* 1138 * Record need for grace period s. Pair with load 1139 * acquire setting up for initialization. 1140 */ 1141 smp_store_release(&sup->srcu_gp_seq_needed, s); /*^^^*/ 1142 } 1143 if (!do_norm && ULONG_CMP_LT(sup->srcu_gp_seq_needed_exp, s)) 1144 WRITE_ONCE(sup->srcu_gp_seq_needed_exp, s); 1145 1146 /* If grace period not already in progress, start it. */ 1147 if (!WARN_ON_ONCE(rcu_seq_done(&sup->srcu_gp_seq, s)) && 1148 rcu_seq_state(sup->srcu_gp_seq) == SRCU_STATE_IDLE) { 1149 srcu_gp_start(ssp); 1150 1151 // And how can that list_add() in the "else" clause 1152 // possibly be safe for concurrent execution? Well, 1153 // it isn't. And it does not have to be. After all, it 1154 // can only be executed during early boot when there is only 1155 // the one boot CPU running with interrupts still disabled. 1156 if (likely(srcu_init_done)) 1157 queue_delayed_work(rcu_gp_wq, &sup->work, 1158 !!srcu_get_delay(ssp)); 1159 else if (list_empty(&sup->work.work.entry)) 1160 list_add(&sup->work.work.entry, &srcu_boot_list); 1161 } 1162 spin_unlock_irqrestore_rcu_node(sup, flags); 1163 } 1164 1165 /* 1166 * Wait until all readers counted by array index idx complete, but 1167 * loop an additional time if there is an expedited grace period pending. 1168 * The caller must ensure that ->srcu_ctrp is not changed while checking. 1169 */ 1170 static bool try_check_zero(struct srcu_struct *ssp, int idx, int trycount) 1171 { 1172 unsigned long curdelay; 1173 1174 spin_lock_irq_rcu_node(ssp->srcu_sup); 1175 curdelay = !srcu_get_delay(ssp); 1176 spin_unlock_irq_rcu_node(ssp->srcu_sup); 1177 1178 for (;;) { 1179 if (srcu_readers_active_idx_check(ssp, idx)) 1180 return true; 1181 if ((--trycount + curdelay) <= 0) 1182 return false; 1183 udelay(srcu_retry_check_delay); 1184 } 1185 } 1186 1187 /* 1188 * Increment the ->srcu_ctrp counter so that future SRCU readers will 1189 * use the other rank of the ->srcu_(un)lock_count[] arrays. This allows 1190 * us to wait for pre-existing readers in a starvation-free manner. 1191 */ 1192 static void srcu_flip(struct srcu_struct *ssp) 1193 { 1194 /* 1195 * Because the flip of ->srcu_ctrp is executed only if the 1196 * preceding call to srcu_readers_active_idx_check() found that 1197 * the ->srcu_ctrs[].srcu_unlocks and ->srcu_ctrs[].srcu_locks sums 1198 * matched and because that summing uses atomic_long_read(), 1199 * there is ordering due to a control dependency between that 1200 * summing and the WRITE_ONCE() in this call to srcu_flip(). 1201 * This ordering ensures that if this updater saw a given reader's 1202 * increment from __srcu_read_lock(), that reader was using a value 1203 * of ->srcu_ctrp from before the previous call to srcu_flip(), 1204 * which should be quite rare. This ordering thus helps forward 1205 * progress because the grace period could otherwise be delayed 1206 * by additional calls to __srcu_read_lock() using that old (soon 1207 * to be new) value of ->srcu_ctrp. 1208 * 1209 * This sum-equality check and ordering also ensures that if 1210 * a given call to __srcu_read_lock() uses the new value of 1211 * ->srcu_ctrp, this updater's earlier scans cannot have seen 1212 * that reader's increments, which is all to the good, because 1213 * this grace period need not wait on that reader. After all, 1214 * if those earlier scans had seen that reader, there would have 1215 * been a sum mismatch and this code would not be reached. 1216 * 1217 * This means that the following smp_mb() is redundant, but 1218 * it stays until either (1) Compilers learn about this sort of 1219 * control dependency or (2) Some production workload running on 1220 * a production system is unduly delayed by this slowpath smp_mb(). 1221 * Except for _lite() readers, where it is inoperative, which 1222 * means that it is a good thing that it is redundant. 1223 */ 1224 smp_mb(); /* E */ /* Pairs with B and C. */ 1225 1226 WRITE_ONCE(ssp->srcu_ctrp, 1227 &ssp->sda->srcu_ctrs[!(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0])]); 1228 1229 /* 1230 * Ensure that if the updater misses an __srcu_read_unlock() 1231 * increment, that task's __srcu_read_lock() following its next 1232 * __srcu_read_lock() or __srcu_read_unlock() will see the above 1233 * counter update. Note that both this memory barrier and the 1234 * one in srcu_readers_active_idx_check() provide the guarantee 1235 * for __srcu_read_lock(). 1236 * 1237 * Note that this is a performance optimization, in which we spend 1238 * an otherwise unnecessary smp_mb() in order to reduce the number 1239 * of full per-CPU-variable scans in srcu_readers_lock_idx() and 1240 * srcu_readers_unlock_idx(). But this performance optimization 1241 * is not so optimal for SRCU-fast, where we would be spending 1242 * not smp_mb(), but rather synchronize_rcu(). At the same time, 1243 * the overhead of the smp_mb() is in the noise, so there is no 1244 * point in omitting it in the SRCU-fast case. So the same code 1245 * is executed either way. 1246 */ 1247 smp_mb(); /* D */ /* Pairs with C. */ 1248 } 1249 1250 /* 1251 * If SRCU is likely idle, in other words, the next SRCU grace period 1252 * should be expedited, return true, otherwise return false. Except that 1253 * in the presence of _lite() readers, always return false. 1254 * 1255 * Note that it is OK for several current from-idle requests for a new 1256 * grace period from idle to specify expediting because they will all end 1257 * up requesting the same grace period anyhow. So no loss. 1258 * 1259 * Note also that if any CPU (including the current one) is still invoking 1260 * callbacks, this function will nevertheless say "idle". This is not 1261 * ideal, but the overhead of checking all CPUs' callback lists is even 1262 * less ideal, especially on large systems. Furthermore, the wakeup 1263 * can happen before the callback is fully removed, so we have no choice 1264 * but to accept this type of error. 1265 * 1266 * This function is also subject to counter-wrap errors, but let's face 1267 * it, if this function was preempted for enough time for the counters 1268 * to wrap, it really doesn't matter whether or not we expedite the grace 1269 * period. The extra overhead of a needlessly expedited grace period is 1270 * negligible when amortized over that time period, and the extra latency 1271 * of a needlessly non-expedited grace period is similarly negligible. 1272 */ 1273 static bool srcu_should_expedite(struct srcu_struct *ssp) 1274 { 1275 unsigned long curseq; 1276 unsigned long flags; 1277 struct srcu_data *sdp; 1278 unsigned long t; 1279 unsigned long tlast; 1280 1281 check_init_srcu_struct(ssp); 1282 /* If _lite() readers, don't do unsolicited expediting. */ 1283 if (this_cpu_read(ssp->sda->srcu_reader_flavor) & SRCU_READ_FLAVOR_SLOWGP) 1284 return false; 1285 /* If the local srcu_data structure has callbacks, not idle. */ 1286 sdp = raw_cpu_ptr(ssp->sda); 1287 spin_lock_irqsave_rcu_node(sdp, flags); 1288 if (rcu_segcblist_pend_cbs(&sdp->srcu_cblist)) { 1289 spin_unlock_irqrestore_rcu_node(sdp, flags); 1290 return false; /* Callbacks already present, so not idle. */ 1291 } 1292 spin_unlock_irqrestore_rcu_node(sdp, flags); 1293 1294 /* 1295 * No local callbacks, so probabilistically probe global state. 1296 * Exact information would require acquiring locks, which would 1297 * kill scalability, hence the probabilistic nature of the probe. 1298 */ 1299 1300 /* First, see if enough time has passed since the last GP. */ 1301 t = ktime_get_mono_fast_ns(); 1302 tlast = READ_ONCE(ssp->srcu_sup->srcu_last_gp_end); 1303 if (exp_holdoff == 0 || 1304 time_in_range_open(t, tlast, tlast + exp_holdoff)) 1305 return false; /* Too soon after last GP. */ 1306 1307 /* Next, check for probable idleness. */ 1308 curseq = rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq); 1309 smp_mb(); /* Order ->srcu_gp_seq with ->srcu_gp_seq_needed. */ 1310 if (ULONG_CMP_LT(curseq, READ_ONCE(ssp->srcu_sup->srcu_gp_seq_needed))) 1311 return false; /* Grace period in progress, so not idle. */ 1312 smp_mb(); /* Order ->srcu_gp_seq with prior access. */ 1313 if (curseq != rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq)) 1314 return false; /* GP # changed, so not idle. */ 1315 return true; /* With reasonable probability, idle! */ 1316 } 1317 1318 /* 1319 * SRCU callback function to leak a callback. 1320 */ 1321 static void srcu_leak_callback(struct rcu_head *rhp) 1322 { 1323 } 1324 1325 /* 1326 * Start an SRCU grace period, and also queue the callback if non-NULL. 1327 */ 1328 static unsigned long srcu_gp_start_if_needed(struct srcu_struct *ssp, 1329 struct rcu_head *rhp, bool do_norm) 1330 { 1331 unsigned long flags; 1332 int idx; 1333 bool needexp = false; 1334 bool needgp = false; 1335 unsigned long s; 1336 struct srcu_data *sdp; 1337 struct srcu_node *sdp_mynode; 1338 int ss_state; 1339 1340 check_init_srcu_struct(ssp); 1341 /* 1342 * While starting a new grace period, make sure we are in an 1343 * SRCU read-side critical section so that the grace-period 1344 * sequence number cannot wrap around in the meantime. 1345 */ 1346 idx = __srcu_read_lock_nmisafe(ssp); 1347 ss_state = smp_load_acquire(&ssp->srcu_sup->srcu_size_state); 1348 if (ss_state < SRCU_SIZE_WAIT_CALL) 1349 sdp = per_cpu_ptr(ssp->sda, get_boot_cpu_id()); 1350 else 1351 sdp = raw_cpu_ptr(ssp->sda); 1352 spin_lock_irqsave_sdp_contention(sdp, &flags); 1353 if (rhp) 1354 rcu_segcblist_enqueue(&sdp->srcu_cblist, rhp); 1355 /* 1356 * It's crucial to capture the snapshot 's' for acceleration before 1357 * reading the current gp_seq that is used for advancing. This is 1358 * essential because if the acceleration snapshot is taken after a 1359 * failed advancement attempt, there's a risk that a grace period may 1360 * conclude and a new one may start in the interim. If the snapshot is 1361 * captured after this sequence of events, the acceleration snapshot 's' 1362 * could be excessively advanced, leading to acceleration failure. 1363 * In such a scenario, an 'acceleration leak' can occur, where new 1364 * callbacks become indefinitely stuck in the RCU_NEXT_TAIL segment. 1365 * Also note that encountering advancing failures is a normal 1366 * occurrence when the grace period for RCU_WAIT_TAIL is in progress. 1367 * 1368 * To see this, consider the following events which occur if 1369 * rcu_seq_snap() were to be called after advance: 1370 * 1371 * 1) The RCU_WAIT_TAIL segment has callbacks (gp_num = X + 4) and the 1372 * RCU_NEXT_READY_TAIL also has callbacks (gp_num = X + 8). 1373 * 1374 * 2) The grace period for RCU_WAIT_TAIL is seen as started but not 1375 * completed so rcu_seq_current() returns X + SRCU_STATE_SCAN1. 1376 * 1377 * 3) This value is passed to rcu_segcblist_advance() which can't move 1378 * any segment forward and fails. 1379 * 1380 * 4) srcu_gp_start_if_needed() still proceeds with callback acceleration. 1381 * But then the call to rcu_seq_snap() observes the grace period for the 1382 * RCU_WAIT_TAIL segment as completed and the subsequent one for the 1383 * RCU_NEXT_READY_TAIL segment as started (ie: X + 4 + SRCU_STATE_SCAN1) 1384 * so it returns a snapshot of the next grace period, which is X + 12. 1385 * 1386 * 5) The value of X + 12 is passed to rcu_segcblist_accelerate() but the 1387 * freshly enqueued callback in RCU_NEXT_TAIL can't move to 1388 * RCU_NEXT_READY_TAIL which already has callbacks for a previous grace 1389 * period (gp_num = X + 8). So acceleration fails. 1390 */ 1391 s = rcu_seq_snap(&ssp->srcu_sup->srcu_gp_seq); 1392 if (rhp) { 1393 rcu_segcblist_advance(&sdp->srcu_cblist, 1394 rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq)); 1395 /* 1396 * Acceleration can never fail because the base current gp_seq 1397 * used for acceleration is <= the value of gp_seq used for 1398 * advancing. This means that RCU_NEXT_TAIL segment will 1399 * always be able to be emptied by the acceleration into the 1400 * RCU_NEXT_READY_TAIL or RCU_WAIT_TAIL segments. 1401 */ 1402 WARN_ON_ONCE(!rcu_segcblist_accelerate(&sdp->srcu_cblist, s)); 1403 } 1404 if (ULONG_CMP_LT(sdp->srcu_gp_seq_needed, s)) { 1405 sdp->srcu_gp_seq_needed = s; 1406 needgp = true; 1407 } 1408 if (!do_norm && ULONG_CMP_LT(sdp->srcu_gp_seq_needed_exp, s)) { 1409 sdp->srcu_gp_seq_needed_exp = s; 1410 needexp = true; 1411 } 1412 spin_unlock_irqrestore_rcu_node(sdp, flags); 1413 1414 /* Ensure that snp node tree is fully initialized before traversing it */ 1415 if (ss_state < SRCU_SIZE_WAIT_BARRIER) 1416 sdp_mynode = NULL; 1417 else 1418 sdp_mynode = sdp->mynode; 1419 1420 if (needgp) 1421 srcu_funnel_gp_start(ssp, sdp, s, do_norm); 1422 else if (needexp) 1423 srcu_funnel_exp_start(ssp, sdp_mynode, s); 1424 __srcu_read_unlock_nmisafe(ssp, idx); 1425 return s; 1426 } 1427 1428 /* 1429 * Enqueue an SRCU callback on the srcu_data structure associated with 1430 * the current CPU and the specified srcu_struct structure, initiating 1431 * grace-period processing if it is not already running. 1432 * 1433 * Note that all CPUs must agree that the grace period extended beyond 1434 * all pre-existing SRCU read-side critical section. On systems with 1435 * more than one CPU, this means that when "func()" is invoked, each CPU 1436 * is guaranteed to have executed a full memory barrier since the end of 1437 * its last corresponding SRCU read-side critical section whose beginning 1438 * preceded the call to call_srcu(). It also means that each CPU executing 1439 * an SRCU read-side critical section that continues beyond the start of 1440 * "func()" must have executed a memory barrier after the call_srcu() 1441 * but before the beginning of that SRCU read-side critical section. 1442 * Note that these guarantees include CPUs that are offline, idle, or 1443 * executing in user mode, as well as CPUs that are executing in the kernel. 1444 * 1445 * Furthermore, if CPU A invoked call_srcu() and CPU B invoked the 1446 * resulting SRCU callback function "func()", then both CPU A and CPU 1447 * B are guaranteed to execute a full memory barrier during the time 1448 * interval between the call to call_srcu() and the invocation of "func()". 1449 * This guarantee applies even if CPU A and CPU B are the same CPU (but 1450 * again only if the system has more than one CPU). 1451 * 1452 * Of course, these guarantees apply only for invocations of call_srcu(), 1453 * srcu_read_lock(), and srcu_read_unlock() that are all passed the same 1454 * srcu_struct structure. 1455 */ 1456 static void __call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp, 1457 rcu_callback_t func, bool do_norm) 1458 { 1459 if (debug_rcu_head_queue(rhp)) { 1460 /* Probable double call_srcu(), so leak the callback. */ 1461 WRITE_ONCE(rhp->func, srcu_leak_callback); 1462 WARN_ONCE(1, "call_srcu(): Leaked duplicate callback\n"); 1463 return; 1464 } 1465 rhp->func = func; 1466 (void)srcu_gp_start_if_needed(ssp, rhp, do_norm); 1467 } 1468 1469 /** 1470 * call_srcu() - Queue a callback for invocation after an SRCU grace period 1471 * @ssp: srcu_struct in queue the callback 1472 * @rhp: structure to be used for queueing the SRCU callback. 1473 * @func: function to be invoked after the SRCU grace period 1474 * 1475 * The callback function will be invoked some time after a full SRCU 1476 * grace period elapses, in other words after all pre-existing SRCU 1477 * read-side critical sections have completed. However, the callback 1478 * function might well execute concurrently with other SRCU read-side 1479 * critical sections that started after call_srcu() was invoked. SRCU 1480 * read-side critical sections are delimited by srcu_read_lock() and 1481 * srcu_read_unlock(), and may be nested. 1482 * 1483 * The callback will be invoked from process context, but with bh 1484 * disabled. The callback function must therefore be fast and must 1485 * not block. 1486 * 1487 * See the description of call_rcu() for more detailed information on 1488 * memory ordering guarantees. 1489 */ 1490 void call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp, 1491 rcu_callback_t func) 1492 { 1493 __call_srcu(ssp, rhp, func, true); 1494 } 1495 EXPORT_SYMBOL_GPL(call_srcu); 1496 1497 /* 1498 * Helper function for synchronize_srcu() and synchronize_srcu_expedited(). 1499 */ 1500 static void __synchronize_srcu(struct srcu_struct *ssp, bool do_norm) 1501 { 1502 struct rcu_synchronize rcu; 1503 1504 srcu_lock_sync(&ssp->dep_map); 1505 1506 RCU_LOCKDEP_WARN(lockdep_is_held(ssp) || 1507 lock_is_held(&rcu_bh_lock_map) || 1508 lock_is_held(&rcu_lock_map) || 1509 lock_is_held(&rcu_sched_lock_map), 1510 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section"); 1511 1512 if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE) 1513 return; 1514 might_sleep(); 1515 check_init_srcu_struct(ssp); 1516 init_completion(&rcu.completion); 1517 init_rcu_head_on_stack(&rcu.head); 1518 __call_srcu(ssp, &rcu.head, wakeme_after_rcu, do_norm); 1519 wait_for_completion(&rcu.completion); 1520 destroy_rcu_head_on_stack(&rcu.head); 1521 1522 /* 1523 * Make sure that later code is ordered after the SRCU grace 1524 * period. This pairs with the spin_lock_irq_rcu_node() 1525 * in srcu_invoke_callbacks(). Unlike Tree RCU, this is needed 1526 * because the current CPU might have been totally uninvolved with 1527 * (and thus unordered against) that grace period. 1528 */ 1529 smp_mb(); 1530 } 1531 1532 /** 1533 * synchronize_srcu_expedited - Brute-force SRCU grace period 1534 * @ssp: srcu_struct with which to synchronize. 1535 * 1536 * Wait for an SRCU grace period to elapse, but be more aggressive about 1537 * spinning rather than blocking when waiting. 1538 * 1539 * Note that synchronize_srcu_expedited() has the same deadlock and 1540 * memory-ordering properties as does synchronize_srcu(). 1541 */ 1542 void synchronize_srcu_expedited(struct srcu_struct *ssp) 1543 { 1544 __synchronize_srcu(ssp, rcu_gp_is_normal()); 1545 } 1546 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited); 1547 1548 /** 1549 * synchronize_srcu - wait for prior SRCU read-side critical-section completion 1550 * @ssp: srcu_struct with which to synchronize. 1551 * 1552 * Wait for the count to drain to zero of both indexes. To avoid the 1553 * possible starvation of synchronize_srcu(), it waits for the count of 1554 * the index=!(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]) to drain to zero 1555 * at first, and then flip the ->srcu_ctrp and wait for the count of the 1556 * other index. 1557 * 1558 * Can block; must be called from process context. 1559 * 1560 * Note that it is illegal to call synchronize_srcu() from the corresponding 1561 * SRCU read-side critical section; doing so will result in deadlock. 1562 * However, it is perfectly legal to call synchronize_srcu() on one 1563 * srcu_struct from some other srcu_struct's read-side critical section, 1564 * as long as the resulting graph of srcu_structs is acyclic. 1565 * 1566 * There are memory-ordering constraints implied by synchronize_srcu(). 1567 * On systems with more than one CPU, when synchronize_srcu() returns, 1568 * each CPU is guaranteed to have executed a full memory barrier since 1569 * the end of its last corresponding SRCU read-side critical section 1570 * whose beginning preceded the call to synchronize_srcu(). In addition, 1571 * each CPU having an SRCU read-side critical section that extends beyond 1572 * the return from synchronize_srcu() is guaranteed to have executed a 1573 * full memory barrier after the beginning of synchronize_srcu() and before 1574 * the beginning of that SRCU read-side critical section. Note that these 1575 * guarantees include CPUs that are offline, idle, or executing in user mode, 1576 * as well as CPUs that are executing in the kernel. 1577 * 1578 * Furthermore, if CPU A invoked synchronize_srcu(), which returned 1579 * to its caller on CPU B, then both CPU A and CPU B are guaranteed 1580 * to have executed a full memory barrier during the execution of 1581 * synchronize_srcu(). This guarantee applies even if CPU A and CPU B 1582 * are the same CPU, but again only if the system has more than one CPU. 1583 * 1584 * Of course, these memory-ordering guarantees apply only when 1585 * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are 1586 * passed the same srcu_struct structure. 1587 * 1588 * Implementation of these memory-ordering guarantees is similar to 1589 * that of synchronize_rcu(). 1590 * 1591 * If SRCU is likely idle as determined by srcu_should_expedite(), 1592 * expedite the first request. This semantic was provided by Classic SRCU, 1593 * and is relied upon by its users, so TREE SRCU must also provide it. 1594 * Note that detecting idleness is heuristic and subject to both false 1595 * positives and negatives. 1596 */ 1597 void synchronize_srcu(struct srcu_struct *ssp) 1598 { 1599 if (srcu_should_expedite(ssp) || rcu_gp_is_expedited()) 1600 synchronize_srcu_expedited(ssp); 1601 else 1602 __synchronize_srcu(ssp, true); 1603 } 1604 EXPORT_SYMBOL_GPL(synchronize_srcu); 1605 1606 /** 1607 * get_state_synchronize_srcu - Provide an end-of-grace-period cookie 1608 * @ssp: srcu_struct to provide cookie for. 1609 * 1610 * This function returns a cookie that can be passed to 1611 * poll_state_synchronize_srcu(), which will return true if a full grace 1612 * period has elapsed in the meantime. It is the caller's responsibility 1613 * to make sure that grace period happens, for example, by invoking 1614 * call_srcu() after return from get_state_synchronize_srcu(). 1615 */ 1616 unsigned long get_state_synchronize_srcu(struct srcu_struct *ssp) 1617 { 1618 // Any prior manipulation of SRCU-protected data must happen 1619 // before the load from ->srcu_gp_seq. 1620 smp_mb(); 1621 return rcu_seq_snap(&ssp->srcu_sup->srcu_gp_seq); 1622 } 1623 EXPORT_SYMBOL_GPL(get_state_synchronize_srcu); 1624 1625 /** 1626 * start_poll_synchronize_srcu - Provide cookie and start grace period 1627 * @ssp: srcu_struct to provide cookie for. 1628 * 1629 * This function returns a cookie that can be passed to 1630 * poll_state_synchronize_srcu(), which will return true if a full grace 1631 * period has elapsed in the meantime. Unlike get_state_synchronize_srcu(), 1632 * this function also ensures that any needed SRCU grace period will be 1633 * started. This convenience does come at a cost in terms of CPU overhead. 1634 */ 1635 unsigned long start_poll_synchronize_srcu(struct srcu_struct *ssp) 1636 { 1637 return srcu_gp_start_if_needed(ssp, NULL, true); 1638 } 1639 EXPORT_SYMBOL_GPL(start_poll_synchronize_srcu); 1640 1641 /** 1642 * poll_state_synchronize_srcu - Has cookie's grace period ended? 1643 * @ssp: srcu_struct to provide cookie for. 1644 * @cookie: Return value from get_state_synchronize_srcu() or start_poll_synchronize_srcu(). 1645 * 1646 * This function takes the cookie that was returned from either 1647 * get_state_synchronize_srcu() or start_poll_synchronize_srcu(), and 1648 * returns @true if an SRCU grace period elapsed since the time that the 1649 * cookie was created. 1650 * 1651 * Because cookies are finite in size, wrapping/overflow is possible. 1652 * This is more pronounced on 32-bit systems where cookies are 32 bits, 1653 * where in theory wrapping could happen in about 14 hours assuming 1654 * 25-microsecond expedited SRCU grace periods. However, a more likely 1655 * overflow lower bound is on the order of 24 days in the case of 1656 * one-millisecond SRCU grace periods. Of course, wrapping in a 64-bit 1657 * system requires geologic timespans, as in more than seven million years 1658 * even for expedited SRCU grace periods. 1659 * 1660 * Wrapping/overflow is much more of an issue for CONFIG_SMP=n systems 1661 * that also have CONFIG_PREEMPTION=n, which selects Tiny SRCU. This uses 1662 * a 16-bit cookie, which rcutorture routinely wraps in a matter of a 1663 * few minutes. If this proves to be a problem, this counter will be 1664 * expanded to the same size as for Tree SRCU. 1665 */ 1666 bool poll_state_synchronize_srcu(struct srcu_struct *ssp, unsigned long cookie) 1667 { 1668 if (cookie != SRCU_GET_STATE_COMPLETED && 1669 !rcu_seq_done_exact(&ssp->srcu_sup->srcu_gp_seq, cookie)) 1670 return false; 1671 // Ensure that the end of the SRCU grace period happens before 1672 // any subsequent code that the caller might execute. 1673 smp_mb(); // ^^^ 1674 return true; 1675 } 1676 EXPORT_SYMBOL_GPL(poll_state_synchronize_srcu); 1677 1678 /* 1679 * Callback function for srcu_barrier() use. 1680 */ 1681 static void srcu_barrier_cb(struct rcu_head *rhp) 1682 { 1683 struct srcu_data *sdp; 1684 struct srcu_struct *ssp; 1685 1686 rhp->next = rhp; // Mark the callback as having been invoked. 1687 sdp = container_of(rhp, struct srcu_data, srcu_barrier_head); 1688 ssp = sdp->ssp; 1689 if (atomic_dec_and_test(&ssp->srcu_sup->srcu_barrier_cpu_cnt)) 1690 complete(&ssp->srcu_sup->srcu_barrier_completion); 1691 } 1692 1693 /* 1694 * Enqueue an srcu_barrier() callback on the specified srcu_data 1695 * structure's ->cblist. but only if that ->cblist already has at least one 1696 * callback enqueued. Note that if a CPU already has callbacks enqueue, 1697 * it must have already registered the need for a future grace period, 1698 * so all we need do is enqueue a callback that will use the same grace 1699 * period as the last callback already in the queue. 1700 */ 1701 static void srcu_barrier_one_cpu(struct srcu_struct *ssp, struct srcu_data *sdp) 1702 { 1703 spin_lock_irq_rcu_node(sdp); 1704 atomic_inc(&ssp->srcu_sup->srcu_barrier_cpu_cnt); 1705 sdp->srcu_barrier_head.func = srcu_barrier_cb; 1706 debug_rcu_head_queue(&sdp->srcu_barrier_head); 1707 if (!rcu_segcblist_entrain(&sdp->srcu_cblist, 1708 &sdp->srcu_barrier_head)) { 1709 debug_rcu_head_unqueue(&sdp->srcu_barrier_head); 1710 atomic_dec(&ssp->srcu_sup->srcu_barrier_cpu_cnt); 1711 } 1712 spin_unlock_irq_rcu_node(sdp); 1713 } 1714 1715 /** 1716 * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete. 1717 * @ssp: srcu_struct on which to wait for in-flight callbacks. 1718 */ 1719 void srcu_barrier(struct srcu_struct *ssp) 1720 { 1721 int cpu; 1722 int idx; 1723 unsigned long s = rcu_seq_snap(&ssp->srcu_sup->srcu_barrier_seq); 1724 1725 check_init_srcu_struct(ssp); 1726 mutex_lock(&ssp->srcu_sup->srcu_barrier_mutex); 1727 if (rcu_seq_done(&ssp->srcu_sup->srcu_barrier_seq, s)) { 1728 smp_mb(); /* Force ordering following return. */ 1729 mutex_unlock(&ssp->srcu_sup->srcu_barrier_mutex); 1730 return; /* Someone else did our work for us. */ 1731 } 1732 rcu_seq_start(&ssp->srcu_sup->srcu_barrier_seq); 1733 init_completion(&ssp->srcu_sup->srcu_barrier_completion); 1734 1735 /* Initial count prevents reaching zero until all CBs are posted. */ 1736 atomic_set(&ssp->srcu_sup->srcu_barrier_cpu_cnt, 1); 1737 1738 idx = __srcu_read_lock_nmisafe(ssp); 1739 if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER) 1740 srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda, get_boot_cpu_id())); 1741 else 1742 for_each_possible_cpu(cpu) 1743 srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda, cpu)); 1744 __srcu_read_unlock_nmisafe(ssp, idx); 1745 1746 /* Remove the initial count, at which point reaching zero can happen. */ 1747 if (atomic_dec_and_test(&ssp->srcu_sup->srcu_barrier_cpu_cnt)) 1748 complete(&ssp->srcu_sup->srcu_barrier_completion); 1749 wait_for_completion(&ssp->srcu_sup->srcu_barrier_completion); 1750 1751 rcu_seq_end(&ssp->srcu_sup->srcu_barrier_seq); 1752 mutex_unlock(&ssp->srcu_sup->srcu_barrier_mutex); 1753 } 1754 EXPORT_SYMBOL_GPL(srcu_barrier); 1755 1756 /* Callback for srcu_expedite_current() usage. */ 1757 static void srcu_expedite_current_cb(struct rcu_head *rhp) 1758 { 1759 unsigned long flags; 1760 bool needcb = false; 1761 struct srcu_data *sdp = container_of(rhp, struct srcu_data, srcu_ec_head); 1762 1763 spin_lock_irqsave_sdp_contention(sdp, &flags); 1764 if (sdp->srcu_ec_state == SRCU_EC_IDLE) { 1765 WARN_ON_ONCE(1); 1766 } else if (sdp->srcu_ec_state == SRCU_EC_PENDING) { 1767 sdp->srcu_ec_state = SRCU_EC_IDLE; 1768 } else { 1769 WARN_ON_ONCE(sdp->srcu_ec_state != SRCU_EC_REPOST); 1770 sdp->srcu_ec_state = SRCU_EC_PENDING; 1771 needcb = true; 1772 } 1773 spin_unlock_irqrestore_rcu_node(sdp, flags); 1774 // If needed, requeue ourselves as an expedited SRCU callback. 1775 if (needcb) 1776 __call_srcu(sdp->ssp, &sdp->srcu_ec_head, srcu_expedite_current_cb, false); 1777 } 1778 1779 /** 1780 * srcu_expedite_current - Expedite the current SRCU grace period 1781 * @ssp: srcu_struct to expedite. 1782 * 1783 * Cause the current SRCU grace period to become expedited. The grace 1784 * period following the current one might also be expedited. If there is 1785 * no current grace period, one might be created. If the current grace 1786 * period is currently sleeping, that sleep will complete before expediting 1787 * will take effect. 1788 */ 1789 void srcu_expedite_current(struct srcu_struct *ssp) 1790 { 1791 unsigned long flags; 1792 bool needcb = false; 1793 struct srcu_data *sdp; 1794 1795 migrate_disable(); 1796 sdp = this_cpu_ptr(ssp->sda); 1797 spin_lock_irqsave_sdp_contention(sdp, &flags); 1798 if (sdp->srcu_ec_state == SRCU_EC_IDLE) { 1799 sdp->srcu_ec_state = SRCU_EC_PENDING; 1800 needcb = true; 1801 } else if (sdp->srcu_ec_state == SRCU_EC_PENDING) { 1802 sdp->srcu_ec_state = SRCU_EC_REPOST; 1803 } else { 1804 WARN_ON_ONCE(sdp->srcu_ec_state != SRCU_EC_REPOST); 1805 } 1806 spin_unlock_irqrestore_rcu_node(sdp, flags); 1807 // If needed, queue an expedited SRCU callback. 1808 if (needcb) 1809 __call_srcu(ssp, &sdp->srcu_ec_head, srcu_expedite_current_cb, false); 1810 migrate_enable(); 1811 } 1812 EXPORT_SYMBOL_GPL(srcu_expedite_current); 1813 1814 /** 1815 * srcu_batches_completed - return batches completed. 1816 * @ssp: srcu_struct on which to report batch completion. 1817 * 1818 * Report the number of batches, correlated with, but not necessarily 1819 * precisely the same as, the number of grace periods that have elapsed. 1820 */ 1821 unsigned long srcu_batches_completed(struct srcu_struct *ssp) 1822 { 1823 return READ_ONCE(ssp->srcu_sup->srcu_gp_seq); 1824 } 1825 EXPORT_SYMBOL_GPL(srcu_batches_completed); 1826 1827 /* 1828 * Core SRCU state machine. Push state bits of ->srcu_gp_seq 1829 * to SRCU_STATE_SCAN2, and invoke srcu_gp_end() when scan has 1830 * completed in that state. 1831 */ 1832 static void srcu_advance_state(struct srcu_struct *ssp) 1833 { 1834 int idx; 1835 1836 mutex_lock(&ssp->srcu_sup->srcu_gp_mutex); 1837 1838 /* 1839 * Because readers might be delayed for an extended period after 1840 * fetching ->srcu_ctrp for their index, at any point in time there 1841 * might well be readers using both idx=0 and idx=1. We therefore 1842 * need to wait for readers to clear from both index values before 1843 * invoking a callback. 1844 * 1845 * The load-acquire ensures that we see the accesses performed 1846 * by the prior grace period. 1847 */ 1848 idx = rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq)); /* ^^^ */ 1849 if (idx == SRCU_STATE_IDLE) { 1850 spin_lock_irq_rcu_node(ssp->srcu_sup); 1851 if (ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed)) { 1852 WARN_ON_ONCE(rcu_seq_state(ssp->srcu_sup->srcu_gp_seq)); 1853 spin_unlock_irq_rcu_node(ssp->srcu_sup); 1854 mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex); 1855 return; 1856 } 1857 idx = rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq)); 1858 if (idx == SRCU_STATE_IDLE) 1859 srcu_gp_start(ssp); 1860 spin_unlock_irq_rcu_node(ssp->srcu_sup); 1861 if (idx != SRCU_STATE_IDLE) { 1862 mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex); 1863 return; /* Someone else started the grace period. */ 1864 } 1865 } 1866 1867 if (rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq)) == SRCU_STATE_SCAN1) { 1868 idx = !(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]); 1869 if (!try_check_zero(ssp, idx, 1)) { 1870 mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex); 1871 return; /* readers present, retry later. */ 1872 } 1873 srcu_flip(ssp); 1874 spin_lock_irq_rcu_node(ssp->srcu_sup); 1875 rcu_seq_set_state(&ssp->srcu_sup->srcu_gp_seq, SRCU_STATE_SCAN2); 1876 ssp->srcu_sup->srcu_n_exp_nodelay = 0; 1877 spin_unlock_irq_rcu_node(ssp->srcu_sup); 1878 } 1879 1880 if (rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq)) == SRCU_STATE_SCAN2) { 1881 1882 /* 1883 * SRCU read-side critical sections are normally short, 1884 * so check at least twice in quick succession after a flip. 1885 */ 1886 idx = !(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]); 1887 if (!try_check_zero(ssp, idx, 2)) { 1888 mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex); 1889 return; /* readers present, retry later. */ 1890 } 1891 ssp->srcu_sup->srcu_n_exp_nodelay = 0; 1892 srcu_gp_end(ssp); /* Releases ->srcu_gp_mutex. */ 1893 } 1894 } 1895 1896 /* 1897 * Invoke a limited number of SRCU callbacks that have passed through 1898 * their grace period. If there are more to do, SRCU will reschedule 1899 * the workqueue. Note that needed memory barriers have been executed 1900 * in this task's context by srcu_readers_active_idx_check(). 1901 */ 1902 static void srcu_invoke_callbacks(struct work_struct *work) 1903 { 1904 long len; 1905 bool more; 1906 struct rcu_cblist ready_cbs; 1907 struct rcu_head *rhp; 1908 struct srcu_data *sdp; 1909 struct srcu_struct *ssp; 1910 1911 sdp = container_of(work, struct srcu_data, work); 1912 1913 ssp = sdp->ssp; 1914 rcu_cblist_init(&ready_cbs); 1915 spin_lock_irq_rcu_node(sdp); 1916 WARN_ON_ONCE(!rcu_segcblist_segempty(&sdp->srcu_cblist, RCU_NEXT_TAIL)); 1917 rcu_segcblist_advance(&sdp->srcu_cblist, 1918 rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq)); 1919 /* 1920 * Although this function is theoretically re-entrant, concurrent 1921 * callbacks invocation is disallowed to avoid executing an SRCU barrier 1922 * too early. 1923 */ 1924 if (sdp->srcu_cblist_invoking || 1925 !rcu_segcblist_ready_cbs(&sdp->srcu_cblist)) { 1926 spin_unlock_irq_rcu_node(sdp); 1927 return; /* Someone else on the job or nothing to do. */ 1928 } 1929 1930 /* We are on the job! Extract and invoke ready callbacks. */ 1931 sdp->srcu_cblist_invoking = true; 1932 rcu_segcblist_extract_done_cbs(&sdp->srcu_cblist, &ready_cbs); 1933 len = ready_cbs.len; 1934 spin_unlock_irq_rcu_node(sdp); 1935 rhp = rcu_cblist_dequeue(&ready_cbs); 1936 for (; rhp != NULL; rhp = rcu_cblist_dequeue(&ready_cbs)) { 1937 debug_rcu_head_unqueue(rhp); 1938 debug_rcu_head_callback(rhp); 1939 local_bh_disable(); 1940 rhp->func(rhp); 1941 local_bh_enable(); 1942 } 1943 WARN_ON_ONCE(ready_cbs.len); 1944 1945 /* 1946 * Update counts, accelerate new callbacks, and if needed, 1947 * schedule another round of callback invocation. 1948 */ 1949 spin_lock_irq_rcu_node(sdp); 1950 rcu_segcblist_add_len(&sdp->srcu_cblist, -len); 1951 sdp->srcu_cblist_invoking = false; 1952 more = rcu_segcblist_ready_cbs(&sdp->srcu_cblist); 1953 spin_unlock_irq_rcu_node(sdp); 1954 /* An SRCU barrier or callbacks from previous nesting work pending */ 1955 if (more) 1956 srcu_schedule_cbs_sdp(sdp, 0); 1957 } 1958 1959 /* 1960 * Finished one round of SRCU grace period. Start another if there are 1961 * more SRCU callbacks queued, otherwise put SRCU into not-running state. 1962 */ 1963 static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay) 1964 { 1965 bool pushgp = true; 1966 1967 spin_lock_irq_rcu_node(ssp->srcu_sup); 1968 if (ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed)) { 1969 if (!WARN_ON_ONCE(rcu_seq_state(ssp->srcu_sup->srcu_gp_seq))) { 1970 /* All requests fulfilled, time to go idle. */ 1971 pushgp = false; 1972 } 1973 } else if (!rcu_seq_state(ssp->srcu_sup->srcu_gp_seq)) { 1974 /* Outstanding request and no GP. Start one. */ 1975 srcu_gp_start(ssp); 1976 } 1977 spin_unlock_irq_rcu_node(ssp->srcu_sup); 1978 1979 if (pushgp) 1980 queue_delayed_work(rcu_gp_wq, &ssp->srcu_sup->work, delay); 1981 } 1982 1983 /* 1984 * This is the work-queue function that handles SRCU grace periods. 1985 */ 1986 static void process_srcu(struct work_struct *work) 1987 { 1988 unsigned long curdelay; 1989 unsigned long j; 1990 struct srcu_struct *ssp; 1991 struct srcu_usage *sup; 1992 1993 sup = container_of(work, struct srcu_usage, work.work); 1994 ssp = sup->srcu_ssp; 1995 1996 srcu_advance_state(ssp); 1997 spin_lock_irq_rcu_node(ssp->srcu_sup); 1998 curdelay = srcu_get_delay(ssp); 1999 spin_unlock_irq_rcu_node(ssp->srcu_sup); 2000 if (curdelay) { 2001 WRITE_ONCE(sup->reschedule_count, 0); 2002 } else { 2003 j = jiffies; 2004 if (READ_ONCE(sup->reschedule_jiffies) == j) { 2005 ASSERT_EXCLUSIVE_WRITER(sup->reschedule_count); 2006 WRITE_ONCE(sup->reschedule_count, READ_ONCE(sup->reschedule_count) + 1); 2007 if (READ_ONCE(sup->reschedule_count) > srcu_max_nodelay) 2008 curdelay = 1; 2009 } else { 2010 WRITE_ONCE(sup->reschedule_count, 1); 2011 WRITE_ONCE(sup->reschedule_jiffies, j); 2012 } 2013 } 2014 srcu_reschedule(ssp, curdelay); 2015 } 2016 2017 void srcutorture_get_gp_data(struct srcu_struct *ssp, int *flags, 2018 unsigned long *gp_seq) 2019 { 2020 *flags = 0; 2021 *gp_seq = rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq); 2022 } 2023 EXPORT_SYMBOL_GPL(srcutorture_get_gp_data); 2024 2025 static const char * const srcu_size_state_name[] = { 2026 "SRCU_SIZE_SMALL", 2027 "SRCU_SIZE_ALLOC", 2028 "SRCU_SIZE_WAIT_BARRIER", 2029 "SRCU_SIZE_WAIT_CALL", 2030 "SRCU_SIZE_WAIT_CBS1", 2031 "SRCU_SIZE_WAIT_CBS2", 2032 "SRCU_SIZE_WAIT_CBS3", 2033 "SRCU_SIZE_WAIT_CBS4", 2034 "SRCU_SIZE_BIG", 2035 "SRCU_SIZE_???", 2036 }; 2037 2038 void srcu_torture_stats_print(struct srcu_struct *ssp, char *tt, char *tf) 2039 { 2040 int cpu; 2041 int idx; 2042 unsigned long s0 = 0, s1 = 0; 2043 int ss_state = READ_ONCE(ssp->srcu_sup->srcu_size_state); 2044 int ss_state_idx = ss_state; 2045 2046 idx = ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]; 2047 if (ss_state < 0 || ss_state >= ARRAY_SIZE(srcu_size_state_name)) 2048 ss_state_idx = ARRAY_SIZE(srcu_size_state_name) - 1; 2049 pr_alert("%s%s Tree SRCU g%ld state %d (%s)", 2050 tt, tf, rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq), ss_state, 2051 srcu_size_state_name[ss_state_idx]); 2052 if (!ssp->sda) { 2053 // Called after cleanup_srcu_struct(), perhaps. 2054 pr_cont(" No per-CPU srcu_data structures (->sda == NULL).\n"); 2055 } else { 2056 pr_cont(" per-CPU(idx=%d):", idx); 2057 for_each_possible_cpu(cpu) { 2058 unsigned long l0, l1; 2059 unsigned long u0, u1; 2060 long c0, c1; 2061 struct srcu_data *sdp; 2062 2063 sdp = per_cpu_ptr(ssp->sda, cpu); 2064 u0 = data_race(atomic_long_read(&sdp->srcu_ctrs[!idx].srcu_unlocks)); 2065 u1 = data_race(atomic_long_read(&sdp->srcu_ctrs[idx].srcu_unlocks)); 2066 2067 /* 2068 * Make sure that a lock is always counted if the corresponding 2069 * unlock is counted. 2070 */ 2071 smp_rmb(); 2072 2073 l0 = data_race(atomic_long_read(&sdp->srcu_ctrs[!idx].srcu_locks)); 2074 l1 = data_race(atomic_long_read(&sdp->srcu_ctrs[idx].srcu_locks)); 2075 2076 c0 = l0 - u0; 2077 c1 = l1 - u1; 2078 pr_cont(" %d(%ld,%ld %c)", 2079 cpu, c0, c1, 2080 "C."[rcu_segcblist_empty(&sdp->srcu_cblist)]); 2081 s0 += c0; 2082 s1 += c1; 2083 } 2084 pr_cont(" T(%ld,%ld)\n", s0, s1); 2085 } 2086 if (SRCU_SIZING_IS_TORTURE()) 2087 srcu_transition_to_big(ssp); 2088 } 2089 EXPORT_SYMBOL_GPL(srcu_torture_stats_print); 2090 2091 static int __init srcu_bootup_announce(void) 2092 { 2093 pr_info("Hierarchical SRCU implementation.\n"); 2094 if (exp_holdoff != DEFAULT_SRCU_EXP_HOLDOFF) 2095 pr_info("\tNon-default auto-expedite holdoff of %lu ns.\n", exp_holdoff); 2096 if (srcu_retry_check_delay != SRCU_DEFAULT_RETRY_CHECK_DELAY) 2097 pr_info("\tNon-default retry check delay of %lu us.\n", srcu_retry_check_delay); 2098 if (srcu_max_nodelay != SRCU_DEFAULT_MAX_NODELAY) 2099 pr_info("\tNon-default max no-delay of %lu.\n", srcu_max_nodelay); 2100 pr_info("\tMax phase no-delay instances is %lu.\n", srcu_max_nodelay_phase); 2101 return 0; 2102 } 2103 early_initcall(srcu_bootup_announce); 2104 2105 void __init srcu_init(void) 2106 { 2107 struct srcu_usage *sup; 2108 2109 /* Decide on srcu_struct-size strategy. */ 2110 if (SRCU_SIZING_IS(SRCU_SIZING_AUTO)) { 2111 if (nr_cpu_ids >= big_cpu_lim) { 2112 convert_to_big = SRCU_SIZING_INIT; // Don't bother waiting for contention. 2113 pr_info("%s: Setting srcu_struct sizes to big.\n", __func__); 2114 } else { 2115 convert_to_big = SRCU_SIZING_NONE | SRCU_SIZING_CONTEND; 2116 pr_info("%s: Setting srcu_struct sizes based on contention.\n", __func__); 2117 } 2118 } 2119 2120 /* 2121 * Once that is set, call_srcu() can follow the normal path and 2122 * queue delayed work. This must follow RCU workqueues creation 2123 * and timers initialization. 2124 */ 2125 srcu_init_done = true; 2126 while (!list_empty(&srcu_boot_list)) { 2127 sup = list_first_entry(&srcu_boot_list, struct srcu_usage, 2128 work.work.entry); 2129 list_del_init(&sup->work.work.entry); 2130 if (SRCU_SIZING_IS(SRCU_SIZING_INIT) && 2131 sup->srcu_size_state == SRCU_SIZE_SMALL) 2132 sup->srcu_size_state = SRCU_SIZE_ALLOC; 2133 queue_work(rcu_gp_wq, &sup->work.work); 2134 } 2135 } 2136 2137 #ifdef CONFIG_MODULES 2138 2139 /* Initialize any global-scope srcu_struct structures used by this module. */ 2140 static int srcu_module_coming(struct module *mod) 2141 { 2142 int i; 2143 struct srcu_struct *ssp; 2144 struct srcu_struct **sspp = mod->srcu_struct_ptrs; 2145 2146 for (i = 0; i < mod->num_srcu_structs; i++) { 2147 ssp = *(sspp++); 2148 ssp->sda = alloc_percpu(struct srcu_data); 2149 if (WARN_ON_ONCE(!ssp->sda)) 2150 return -ENOMEM; 2151 ssp->srcu_ctrp = &ssp->sda->srcu_ctrs[0]; 2152 } 2153 return 0; 2154 } 2155 2156 /* Clean up any global-scope srcu_struct structures used by this module. */ 2157 static void srcu_module_going(struct module *mod) 2158 { 2159 int i; 2160 struct srcu_struct *ssp; 2161 struct srcu_struct **sspp = mod->srcu_struct_ptrs; 2162 2163 for (i = 0; i < mod->num_srcu_structs; i++) { 2164 ssp = *(sspp++); 2165 if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq_needed)) && 2166 !WARN_ON_ONCE(!ssp->srcu_sup->sda_is_static)) 2167 cleanup_srcu_struct(ssp); 2168 if (!WARN_ON(srcu_readers_active(ssp))) 2169 free_percpu(ssp->sda); 2170 } 2171 } 2172 2173 /* Handle one module, either coming or going. */ 2174 static int srcu_module_notify(struct notifier_block *self, 2175 unsigned long val, void *data) 2176 { 2177 struct module *mod = data; 2178 int ret = 0; 2179 2180 switch (val) { 2181 case MODULE_STATE_COMING: 2182 ret = srcu_module_coming(mod); 2183 break; 2184 case MODULE_STATE_GOING: 2185 srcu_module_going(mod); 2186 break; 2187 default: 2188 break; 2189 } 2190 return ret; 2191 } 2192 2193 static struct notifier_block srcu_module_nb = { 2194 .notifier_call = srcu_module_notify, 2195 .priority = 0, 2196 }; 2197 2198 static __init int init_srcu_module_notifier(void) 2199 { 2200 int ret; 2201 2202 ret = register_module_notifier(&srcu_module_nb); 2203 if (ret) 2204 pr_warn("Failed to register srcu module notifier\n"); 2205 return ret; 2206 } 2207 late_initcall(init_srcu_module_notifier); 2208 2209 #endif /* #ifdef CONFIG_MODULES */ 2210