Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

19.2 RCU Initialization

Within the Linux kernel, rcu_init() acts as the core initialization function for the RCU subsystem and plays a critical role during the kernel boot sequence. Linux provides two distinct RCU algorithmic implementations tailored for different execution environments.

  • The first variant is Tiny RCU, which is optimized for small uniprocessor systems. It is defined within the source file git/kernel/rcu/tiny.c (historically tiny.c). Its implementation is minimalist and completely bypasses multi-core synchronization overheads.

  • The second variant is Tree RCU, which is engineered for symmetric multiprocessing (SMP) environments with a strong emphasis on high scalability. It is implemented within git/kernel/rcu/tree.c (historically tree.c).

The kernel build system compiles exactly one of these variants based on compilation flags. If CONFIG_TINY_RCU=y is set, the rcu_init() routine inside tiny.c is compiled; if CONFIG_TREE_RCU=y is active, the system compiles the version inside tree.c. The function definition for the multi-core Tree RCU initialization is implemented as follows:

void __init rcu_init(void)
{
	int cpu; 
	rcu_early_boot_tests();
	kfree_rcu_batch_init();
	rcu_bootup_announce();
	rcu_init_geometry();
	rcu_init_one();
	if (dump_tree)
		rcu_dump_rcu_node_tree();
	if (use_softirq)
		open_softirq(RCU_SOFTIRQ, rcu_core_si);
	pm_notifier(rcu_pm_notify, 0);
	for_each_online_cpu(cpu) {
		rcutree_prepare_cpu(cpu);
		rcu_cpu_starting(cpu);
		rcutree_online_cpu(cpu);
	}
	rcu_gp_wq = alloc_workqueue("rcu_gp", WQ_MEM_RECLAIM, 0);
	WARN_ON(!rcu_gp_wq);
	rcu_par_gp_wq = alloc_workqueue("rcu_par_gp", WQ_MEM_RECLAIM, 0);
	WARN_ON(!rcu_par_gp_wq);
	srcu_init();
	if (qovld < 0)
		qovld_calc = DEFAULT_RCU_QOVLD_MULT * qhimark;
	else
		qovld_calc = qovld;
}

This code block can be broken down into the following core functional modules:

1. Pre-boot and Foundational Preparation

If the kernel configuration enables CONFIG_PROVE_RCU or associated verification options, rcu_early_boot_tests() executes early smoke tests to ensure that the core RCU logic is functional before official system operation. rcu_early_boot_tests() triggers early_boot_test_call_rcu() to validate core handlers including call_rcu(), call_srcu(), and kfree_rcu(). These assertions verify whether the RCU subsystem initialization has completed successfully, the callback linked lists function correctly, the Grace Period (GP) state machine advances, Tree SRCU operates normally, SRCU callbacks trigger reliably, and the automatic memory deallocation flows operate as intended. The test wrappers call_rcu() and call_srcu() append their temporary tracking structure nodes onto the main RCU callback linked list, stall until the corresponding grace period terminates, and subsequently evaluate the framework by calling the verification handler test_callback().

Because physical memory reclamation cannot be executed instantly and must stall to wait for a comprehensive grace period to elapse, kfree_rcu() does not force each object to independently wait out its own grace period. To optimize performance, each CPU utilizes its own localized kfree_rcu_cpu structure to batch-cache these requests, flushing and releasing an entire batch via a single callback once a sufficient threshold is reached. The function kfree_rcu_batch_init() initializes this lockless, batch-processing reclamation subsystem (the per-CPU batched deferred release mechanism). This serves as a high-efficiency memory reclamation execution path, establishing a dedicated per-CPU batched flushing framework specifically for kfree_rcu().

The kfree_rcu_cpu structure encapsulates multiple administrative fields. To clarify the operations of the initialization code, several critical tracking members—including krw_arr, monitor_work, page_cache_work, and initialized—are outlined below:

  • krw_arr:
    An array of administrative structures (typically containing 2 index slots) that segments the callback tasks into distinct batches, separating the active collecting batch from the pending waiting batch. The active batch continuously aggregates the incoming memory pointers supplied via kvfree_rcu(), while the waiting batch houses a set of pointers whose accumulated volume has breached a predefined threshold and is currently waiting for the RCU grace period to terminate. By utilizing an array topology, RCU ensures that while one batch of memory blocks is waiting out a grace period, a separate batch can simultaneously continue to collect fresh allocation release requests without inducing cross-blocking.The memory reclamation workflow follows a four-step pipeline: collection, grace period triggering, index switching, and callback release. When kvfree_rcu() is invoked, the kernel appends the target pointer into the memory container mapped to the currently active index of krw_arr. Once the collected objects breach a specific capacity or cross a time threshold, the kernel invokes call_rcu() or a dedicated RCU wait routine. At this juncture, the state of that specific krw_arr slot transitions to a waiting phase, prompting the system to hot-swap over to the alternate array element to continue collecting inbound memory release requests. When the RCU grace period formally concludes, the RCU core triggers the worker function bound to that krw_arr[i] slot (typically kfree_rcu_work), physically returning all cached memory blocks inside that batch to the parent allocator. Each individual element inside the krw_arr matrix acts as a separate administrative unit, enclosing a rcu_work structure utilized to register grace period wait hooks with the RCU core, alongside a tracking pointer referencing a bulk_data linked list that logs the batched records targeted for deletion.

  • monitor_work:
    A delayed work item tracking a timer designed to audit the maximum wait time of a pending batch. When this timer triggers, the subsystem flushes the batch and reclaims the underlying memory regardless of whether the cumulative record count has breached the standard target threshold, preventing unnecessary memory dissipation.

  • page_cache_work:
    A highly critical component within KVFREE_RCU (a specialized RCU variant tailored specifically to optimize kfree_rcu() and kvfree() workloads) managed inside the kfree_rcu_cpu structure. Its architectural existence mitigates a core technical paradox: under severe memory pressure, RCU requires memory allocations to execute its memory reclamation routines efficiently. This component is structured as a standard workqueue task whose entry target maps to the function fill_page_cache_func. Its primary responsibility is to asynchronously allocate physical page frames for the local CPU core, archiving them as a localized pool within the bkvcache linked list to back subsequent memory release transactions. Consequently, page_cache_work functions as a background pre-allocation mechanism that dynamic harvests pages in the background, guaranteeing that kvfree_rcu() permanently maintains a readily available cache of page containers when memory resources tighten.

The function kfree_rcu_batch_init() first leverages the macro helper INIT_RCU_WORK(&krcp->krw_arr[i].rcu_work, kfree_rcu_work) to initialize an individual RCU work batch (initializing the entries inside krw_arr). It configures the callback target of the krw_arr[i].rcu_work item to point to kfree_rcu_work. Upon the formal conclusion of the RCU grace period, the kernel fires this work item to execute the literal kfree() deallocation operations. Following this setup, the function initializes the monitoring timer monitor_work via the macro helper INIT_DELAYED_WORK(&krcp->monitor_work, kfree_rcu_monitor), binding it to the handler routine kfree_rcu_monitor. It subsequently sets up the asynchronous page allocation worker via the task initialization macro INIT_WORK(&krcp->page_cache_work, fill_page_cache_func), mapping page_cache_work to execute fill_page_cache_func().

The finalized technical task performed by kfree_rcu_batch_init() is to register the routine kfree_rcu_shrinker as an active system shrinker function. By registering this shrinker callback, the RCU subsystem signals its availability to the core memory management subsystem: "if system memory resources become severely constrained, notify this context, and I can accelerate the purging of the backlog items accumulated inside the lookaside buffers." When a low-memory signal triggers an eviction pass across the system, the kernel calls back into this shrinker handler to drain the RCU caches.

2. Tree RCU Hierarchical Structure Initialization

Tree RCU is a layered implementation of RCU within the Linux kernel, specifically engineered to satisfy the high-performance and scalability requirements of symmetric multiprocessing (SMP) environments. Unlike Tiny RCU, which is tailored for uniprocessor or extremely memory-constrained systems, Tree RCU coordinates CPU states using a hierarchical tree topology, thereby eliminating the severe locking bottlenecks that a global lock would otherwise impose on massive scale systems.

Tree RCU organizes all CPU cores across the system into a multi-tiered tree architecture composed of leaf-tier nodes (struct rcu_data), intermediate-tier and root-tier nodes (struct rcu_node), and a master control center tracking the global state (struct rcu_state).

  • Leaf-Tier Nodes (rcu_data): This is managed as a per-CPU private variable that stores the localized RCU state unique to each individual CPU core, executing operations such as local quiescent-state detection and callback queue management.

  • Intermediate and Root Nodes (rcu_node): These nodes form the core skeletal backbone of the tree hierarchy. They assume responsibility for harvesting quiescent-state signatures reported from the lower tiers beneath them and systematically aggregate this metadata upward until it reaches the root node. By grouping the physical CPUs into independent subsets—where each subset is protected by an isolated, localized lock—the design drastically mitigates global lock contention.

  • Global State (rcu_state): This acts as the definitive command center for the unified RCU subsystem, assuming responsibility for initiating and managing the lifecycle of grace periods, while orchestrating communication tracks across the disparate rcu_node elements.

The definitive technical objective of the Tree RCU architecture is to determine precisely when it is mathematically safe to free a discarded memory block—meaning the system must verify that every single CPU core has cleanly crossed the active grace period boundary. Resolving this constraint follows a bottom-up aggregation path followed by a top-down dispatch path. Each individual CPU core independent monitors its local operational state within its private rcu_data container to detect a quiescent state. Once a quiescent state is resolved—signifying that the targeted processor core has spent a verified temporal window without executing any active read transactions within an RCU read-side critical section—this metadata is forwarded upward, propagating the signature from the leaf layer to the corresponding parent node. When every CPU core nested under a specific intermediate node successfully reports a quiescent state, that node escalates the notification to its own parent node, repeating this bottom-up walk until the signal arrives at the absolute root node. The moment the root node validates that all participating CPUs across the system have transitioned through a quiescent state, it officially marks the conclusion of the active grace period. Following this declaration, the grace period termination command streams back downward from the root node layer-by-layer, eventually notifying the individual CPU cores to execute and drain their accumulated callback backlogs (such as triggering kfree operations).

In essence, Tree RCU replaces global monolithic synchronization passes with a decentralized, hierarchical aggregation paradigm. This architectural optimization enables the Linux kernel to seamlessly scale its scheduling throughput from a handful of processor cores up to thousands of cores simultaneously, while fully preserving the microarchitectural benefit of near-zero execution overhead on the RCU read side.

Within the execution paths of rcu_init(), the routine rcu_init_geometry() computes the precise geometry of the RCU tree topology (establishing the total number of layers alongside the allocation count of nodes per layer), calculating these dimensions dynamically based on the system's NR_CPUS capabilities and internal scaling factor metrics. Following this computation, rcu_init_one() executes the physical allocation and initialization of the rcu_node tree array structures alongside the parent rcu_state container. If the kernel bootstrap options enable the parameter dump_tree, the subsystem triggers rcu_dump_rcu_node_tree() to print out the compiled hierarchical tree layout, providing developers with low-level diagnostics to audit CPU grouping configurations.

3. Event Processing Mechanism

If the boolean variable use_softirq evaluates to true (the standard operational configuration across production platforms), the subsystem invokes open_softirq() to register the RCU_SOFTIRQ vector. The RCU architecture relies heavily on software interrupts to orchestrate and process the deferred callback functions that accumulate behind an active grace period (such as triggering kfree_rcu_work to execute real-time physical memory freeing operations).

4. Activating the Current CPU

During this explicit phase of the kernel boot sequence, although only the primary Bootstrap Processor (BSP) is actively running, the initialization logic must proactively execute the programmatic setup steps typical of a CPU hot-plug transition. The loop macro for_each_online_cpu() iterates over all currently online CPU cores (which, at this checkpoint, is restricted exclusively to the BSP). The sub-routine rcutree_prepare_cpu() carves out and allocates a private rcu_data tracking descriptor for each available CPU core. Following this, rcu_cpu_starting() registers the core to signal that it is fully prepared to participate in RCU tracking audits. Finally, rcutree_online_cpu() formally promotes the operational state of the processor core to an online status, authorizing it to cast active votes within the grace period consensus tracking loops.

5. Creating Workqueues for Expedited Grace Periods and Tree SRCU

The routine leverages alloc_workqueue() to instantiate a dedicated workqueue named "rcu_gp" to handle expedited grace periods, alongside a parallel workqueue named "rcu_par_gp" to coordinate concurrent grace period processing workloads. Following this, srcu_init() initializes the Sleepable RCU (SRCU) subsystem, an independent RCU variant engineered to safely tolerate blocking sleep phases within read-side critical sections. The tracking variable qovld_calc is utilized to compute the callback overload threshold boundary. If the absolute number of pending callbacks packed within an active RCU queue breaches this computed limit, the kernel automatically scales up its execution aggression, executing highly intensive reclamation passes to clean out the backlog.

Throughout this initial RCU bootstrap phase, the kernel operates strictly under uniprocessor constraints, hardware interrupts are completely disabled, and the task scheduler has not yet assumed comprehensive control of execution threads. Consequently, the rcu_init() routine possesses unrestricted authorization to modify global tracking topologies and rewrite architectural descriptors directly without utilizing mutex synchronization locks or worrying about concurrent race conditions.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com