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