ayyappa ch
ayyappa ch

Reputation: 95

rcu_dereference() vs rcu_dereference_protected()?

Can any one explain what is the difference between rcu_dereference() and rcu_dereference_protected()?

rcu_dereference() contains barrier code and rcu_dereference_protected() do not contain.

When to use rcu_dereference() and when to use rcu_dereference_protected()?

Upvotes: 1

Views: 3574

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65976

In short:

  • rcu_dereference() should be used at read-side, protected by rcu_read_lock() or similar.
  • rcu_dereference_protected() should be used at write-side (update-side) by the single writer, or protected by the lock which prevents several writers from concurrent modification of the dereferenced pointer. In such cases pointer cannot be modified outside of the current thread, so neither compiler- nor cpu-barriers are needed.

If doubt, using rcu_dereference is always safe, and its perfomance penalties (compared to rcu_dereference_protected) are low.

Exact description for rcu_dereference_protected in the kernel 4.6:

/**
 * rcu_dereference_protected() - fetch RCU pointer when updates prevented
 * @p: The pointer to read, prior to dereferencing
 * @c: The conditions under which the dereference will take place
 *
 * Return the value of the specified RCU-protected pointer, but omit
 * both the smp_read_barrier_depends() and the READ_ONCE().  This
 * is useful in cases where update-side locks prevent the value of the
 * pointer from changing.  Please note that this primitive does -not-
 * prevent the compiler from repeating this reference or combining it
 * with other references, so it should not be used without protection
 * of appropriate locks.
 *
 * This function is only for update-side use.  Using this function
 * when protected only by rcu_read_lock() will result in infrequent
 * but very ugly failures.
 */

Upvotes: 8

Related Questions