synchronize_rcu()¶
Purpose¶
synchronize_rcu() waits for an RCU grace period to complete.
When this function returns, all RCU readers that existed before the call have exited their read-side critical sections.
This allows old RCU-protected objects to be safely reclaimed.
Prototype¶
Header¶
Usage Pattern¶
old = rcu_dereference_protected(g_obj, 1);
rcu_assign_pointer(g_obj, new);
synchronize_rcu();
kfree(old);
Concept¶
RCU updates consist of three phases:
synchronize_rcu() implements:
What Does It Wait For?¶
Assume:
are currently executing:
A writer publishes a new object:
The writer then calls:
The function waits until:
After that:
What It Does Not Wait For¶
Readers that start after publication are not part of the grace period.
Example:
The grace period only waits for:
It does not wait for:
because Reader-B can only observe the newly published object.
Blocking Behavior¶
synchronize_rcu() blocks the caller until the grace period completes.
Conceptually:
Typical Use Case¶
Simple object replacement:
struct my_object *old;
struct my_object *new;
new = kmalloc(sizeof(*new), GFP_KERNEL);
old = rcu_dereference_protected(g_obj, 1);
*new = *old;
new->value = 123;
rcu_assign_pointer(g_obj, new);
synchronize_rcu();
kfree(old);
Advantages¶
Simple¶
The update flow is easy to understand:
Safe¶
The old object is guaranteed not to be referenced by any pre-existing readers.
Disadvantages¶
Writer Blocks¶
The caller cannot continue until the grace period completes.
This may increase update latency.
Not Suitable for Frequent Updates¶
If updates occur frequently:
the blocking cost becomes significant.
In such cases:
is often preferred.
synchronize_rcu() vs call_rcu()¶
synchronize_rcu()¶
Example:
call_rcu()¶
Example:
Memory reclamation occurs later through a callback.
Common Mistake¶
Incorrect:
Readers may still reference:
leading to use-after-free bugs.
Correct: