1.. _rcu_dereference_doc:
2
3PROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference()
4===============================================================
5
6Most of the time, you can use values from rcu_dereference() or one of
7the similar primitives without worries.  Dereferencing (prefix "*"),
8field selection ("->"), assignment ("="), address-of ("&"), addition and
9subtraction of constants, and casts all work quite naturally and safely.
10
11It is nevertheless possible to get into trouble with other operations.
12Follow these rules to keep your RCU code working properly:
13
14-	You must use one of the rcu_dereference() family of primitives
15	to load an RCU-protected pointer, otherwise CONFIG_PROVE_RCU
16	will complain.  Worse yet, your code can see random memory-corruption
17	bugs due to games that compilers and DEC Alpha can play.
18	Without one of the rcu_dereference() primitives, compilers
19	can reload the value, and won't your code have fun with two
20	different values for a single pointer!  Without rcu_dereference(),
21	DEC Alpha can load a pointer, dereference that pointer, and
22	return data preceding initialization that preceded the store of
23	the pointer.
24
25	In addition, the volatile cast in rcu_dereference() prevents the
26	compiler from deducing the resulting pointer value.  Please see
27	the section entitled "EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH"
28	for an example where the compiler can in fact deduce the exact
29	value of the pointer, and thus cause misordering.
30
31-	In the special case where data is added but is never removed
32	while readers are accessing the structure, READ_ONCE() may be used
33	instead of rcu_dereference().  In this case, use of READ_ONCE()
34	takes on the role of the lockless_dereference() primitive that
35	was removed in v4.15.
36
37-	You are only permitted to use rcu_dereference on pointer values.
38	The compiler simply knows too much about integral values to
39	trust it to carry dependencies through integer operations.
40	There are a very few exceptions, namely that you can temporarily
41	cast the pointer to uintptr_t in order to:
42
43	-	Set bits and clear bits down in the must-be-zero low-order
44		bits of that pointer.  This clearly means that the pointer
45		must have alignment constraints, for example, this does
46		*not* work in general for char* pointers.
47
48	-	XOR bits to translate pointers, as is done in some
49		classic buddy-allocator algorithms.
50
51	It is important to cast the value back to pointer before
52	doing much of anything else with it.
53
54-	Avoid cancellation when using the "+" and "-" infix arithmetic
55	operators.  For example, for a given variable "x", avoid
56	"(x-(uintptr_t)x)" for char* pointers.	The compiler is within its
57	rights to substitute zero for this sort of expression, so that
58	subsequent accesses no longer depend on the rcu_dereference(),
59	again possibly resulting in bugs due to misordering.
60
61	Of course, if "p" is a pointer from rcu_dereference(), and "a"
62	and "b" are integers that happen to be equal, the expression
63	"p+a-b" is safe because its value still necessarily depends on
64	the rcu_dereference(), thus maintaining proper ordering.
65
66-	If you are using RCU to protect JITed functions, so that the
67	"()" function-invocation operator is applied to a value obtained
68	(directly or indirectly) from rcu_dereference(), you may need to
69	interact directly with the hardware to flush instruction caches.
70	This issue arises on some systems when a newly JITed function is
71	using the same memory that was used by an earlier JITed function.
72
73-	Do not use the results from relational operators ("==", "!=",
74	">", ">=", "<", or "<=") when dereferencing.  For example,
75	the following (quite strange) code is buggy::
76
77		int *p;
78		int *q;
79
80		...
81
82		p = rcu_dereference(gp)
83		q = &global_q;
84		q += p > &oom_p;
85		r1 = *q;  /* BUGGY!!! */
86
87	As before, the reason this is buggy is that relational operators
88	are often compiled using branches.  And as before, although
89	weak-memory machines such as ARM or PowerPC do order stores
90	after such branches, but can speculate loads, which can again
91	result in misordering bugs.
92
93-	Be very careful about comparing pointers obtained from
94	rcu_dereference() against non-NULL values.  As Linus Torvalds
95	explained, if the two pointers are equal, the compiler could
96	substitute the pointer you are comparing against for the pointer
97	obtained from rcu_dereference().  For example::
98
99		p = rcu_dereference(gp);
100		if (p == &default_struct)
101			do_default(p->a);
102
103	Because the compiler now knows that the value of "p" is exactly
104	the address of the variable "default_struct", it is free to
105	transform this code into the following::
106
107		p = rcu_dereference(gp);
108		if (p == &default_struct)
109			do_default(default_struct.a);
110
111	On ARM and Power hardware, the load from "default_struct.a"
112	can now be speculated, such that it might happen before the
113	rcu_dereference().  This could result in bugs due to misordering.
114
115	However, comparisons are OK in the following cases:
116
117	-	The comparison was against the NULL pointer.  If the
118		compiler knows that the pointer is NULL, you had better
119		not be dereferencing it anyway.  If the comparison is
120		non-equal, the compiler is none the wiser.  Therefore,
121		it is safe to compare pointers from rcu_dereference()
122		against NULL pointers.
123
124	-	The pointer is never dereferenced after being compared.
125		Since there are no subsequent dereferences, the compiler
126		cannot use anything it learned from the comparison
127		to reorder the non-existent subsequent dereferences.
128		This sort of comparison occurs frequently when scanning
129		RCU-protected circular linked lists.
130
131		Note that if the pointer comparison is done outside
132		of an RCU read-side critical section, and the pointer
133		is never dereferenced, rcu_access_pointer() should be
134		used in place of rcu_dereference().  In most cases,
135		it is best to avoid accidental dereferences by testing
136		the rcu_access_pointer() return value directly, without
137		assigning it to a variable.
138
139		Within an RCU read-side critical section, there is little
140		reason to use rcu_access_pointer().
141
142	-	The comparison is against a pointer that references memory
143		that was initialized "a long time ago."  The reason
144		this is safe is that even if misordering occurs, the
145		misordering will not affect the accesses that follow
146		the comparison.  So exactly how long ago is "a long
147		time ago"?  Here are some possibilities:
148
149		-	Compile time.
150
151		-	Boot time.
152
153		-	Module-init time for module code.
154
155		-	Prior to kthread creation for kthread code.
156
157		-	During some prior acquisition of the lock that
158			we now hold.
159
160		-	Before mod_timer() time for a timer handler.
161
162		There are many other possibilities involving the Linux
163		kernel's wide array of primitives that cause code to
164		be invoked at a later time.
165
166	-	The pointer being compared against also came from
167		rcu_dereference().  In this case, both pointers depend
168		on one rcu_dereference() or another, so you get proper
169		ordering either way.
170
171		That said, this situation can make certain RCU usage
172		bugs more likely to happen.  Which can be a good thing,
173		at least if they happen during testing.  An example
174		of such an RCU usage bug is shown in the section titled
175		"EXAMPLE OF AMPLIFIED RCU-USAGE BUG".
176
177	-	All of the accesses following the comparison are stores,
178		so that a control dependency preserves the needed ordering.
179		That said, it is easy to get control dependencies wrong.
180		Please see the "CONTROL DEPENDENCIES" section of
181		Documentation/memory-barriers.txt for more details.
182
183	-	The pointers are not equal *and* the compiler does
184		not have enough information to deduce the value of the
185		pointer.  Note that the volatile cast in rcu_dereference()
186		will normally prevent the compiler from knowing too much.
187
188		However, please note that if the compiler knows that the
189		pointer takes on only one of two values, a not-equal
190		comparison will provide exactly the information that the
191		compiler needs to deduce the value of the pointer.
192
193-	Disable any value-speculation optimizations that your compiler
194	might provide, especially if you are making use of feedback-based
195	optimizations that take data collected from prior runs.  Such
196	value-speculation optimizations reorder operations by design.
197
198	There is one exception to this rule:  Value-speculation
199	optimizations that leverage the branch-prediction hardware are
200	safe on strongly ordered systems (such as x86), but not on weakly
201	ordered systems (such as ARM or Power).  Choose your compiler
202	command-line options wisely!
203
204
205EXAMPLE OF AMPLIFIED RCU-USAGE BUG
206----------------------------------
207
208Because updaters can run concurrently with RCU readers, RCU readers can
209see stale and/or inconsistent values.  If RCU readers need fresh or
210consistent values, which they sometimes do, they need to take proper
211precautions.  To see this, consider the following code fragment::
212
213	struct foo {
214		int a;
215		int b;
216		int c;
217	};
218	struct foo *gp1;
219	struct foo *gp2;
220
221	void updater(void)
222	{
223		struct foo *p;
224
225		p = kmalloc(...);
226		if (p == NULL)
227			deal_with_it();
228		p->a = 42;  /* Each field in its own cache line. */
229		p->b = 43;
230		p->c = 44;
231		rcu_assign_pointer(gp1, p);
232		p->b = 143;
233		p->c = 144;
234		rcu_assign_pointer(gp2, p);
235	}
236
237	void reader(void)
238	{
239		struct foo *p;
240		struct foo *q;
241		int r1, r2;
242
243		p = rcu_dereference(gp2);
244		if (p == NULL)
245			return;
246		r1 = p->b;  /* Guaranteed to get 143. */
247		q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
248		if (p == q) {
249			/* The compiler decides that q->c is same as p->c. */
250			r2 = p->c; /* Could get 44 on weakly order system. */
251		}
252		do_something_with(r1, r2);
253	}
254
255You might be surprised that the outcome (r1 == 143 && r2 == 44) is possible,
256but you should not be.  After all, the updater might have been invoked
257a second time between the time reader() loaded into "r1" and the time
258that it loaded into "r2".  The fact that this same result can occur due
259to some reordering from the compiler and CPUs is beside the point.
260
261But suppose that the reader needs a consistent view?
262
263Then one approach is to use locking, for example, as follows::
264
265	struct foo {
266		int a;
267		int b;
268		int c;
269		spinlock_t lock;
270	};
271	struct foo *gp1;
272	struct foo *gp2;
273
274	void updater(void)
275	{
276		struct foo *p;
277
278		p = kmalloc(...);
279		if (p == NULL)
280			deal_with_it();
281		spin_lock(&p->lock);
282		p->a = 42;  /* Each field in its own cache line. */
283		p->b = 43;
284		p->c = 44;
285		spin_unlock(&p->lock);
286		rcu_assign_pointer(gp1, p);
287		spin_lock(&p->lock);
288		p->b = 143;
289		p->c = 144;
290		spin_unlock(&p->lock);
291		rcu_assign_pointer(gp2, p);
292	}
293
294	void reader(void)
295	{
296		struct foo *p;
297		struct foo *q;
298		int r1, r2;
299
300		p = rcu_dereference(gp2);
301		if (p == NULL)
302			return;
303		spin_lock(&p->lock);
304		r1 = p->b;  /* Guaranteed to get 143. */
305		q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
306		if (p == q) {
307			/* The compiler decides that q->c is same as p->c. */
308			r2 = p->c; /* Locking guarantees r2 == 144. */
309		}
310		spin_unlock(&p->lock);
311		do_something_with(r1, r2);
312	}
313
314As always, use the right tool for the job!
315
316
317EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH
318-----------------------------------------
319
320If a pointer obtained from rcu_dereference() compares not-equal to some
321other pointer, the compiler normally has no clue what the value of the
322first pointer might be.  This lack of knowledge prevents the compiler
323from carrying out optimizations that otherwise might destroy the ordering
324guarantees that RCU depends on.  And the volatile cast in rcu_dereference()
325should prevent the compiler from guessing the value.
326
327But without rcu_dereference(), the compiler knows more than you might
328expect.  Consider the following code fragment::
329
330	struct foo {
331		int a;
332		int b;
333	};
334	static struct foo variable1;
335	static struct foo variable2;
336	static struct foo *gp = &variable1;
337
338	void updater(void)
339	{
340		initialize_foo(&variable2);
341		rcu_assign_pointer(gp, &variable2);
342		/*
343		 * The above is the only store to gp in this translation unit,
344		 * and the address of gp is not exported in any way.
345		 */
346	}
347
348	int reader(void)
349	{
350		struct foo *p;
351
352		p = gp;
353		barrier();
354		if (p == &variable1)
355			return p->a; /* Must be variable1.a. */
356		else
357			return p->b; /* Must be variable2.b. */
358	}
359
360Because the compiler can see all stores to "gp", it knows that the only
361possible values of "gp" are "variable1" on the one hand and "variable2"
362on the other.  The comparison in reader() therefore tells the compiler
363the exact value of "p" even in the not-equals case.  This allows the
364compiler to make the return values independent of the load from "gp",
365in turn destroying the ordering between this load and the loads of the
366return values.  This can result in "p->b" returning pre-initialization
367garbage values.
368
369In short, rcu_dereference() is *not* optional when you are going to
370dereference the resulting pointer.
371
372
373WHICH MEMBER OF THE rcu_dereference() FAMILY SHOULD YOU USE?
374------------------------------------------------------------
375
376First, please avoid using rcu_dereference_raw() and also please avoid
377using rcu_dereference_check() and rcu_dereference_protected() with a
378second argument with a constant value of 1 (or true, for that matter).
379With that caution out of the way, here is some guidance for which
380member of the rcu_dereference() to use in various situations:
381
3821.	If the access needs to be within an RCU read-side critical
383	section, use rcu_dereference().  With the new consolidated
384	RCU flavors, an RCU read-side critical section is entered
385	using rcu_read_lock(), anything that disables bottom halves,
386	anything that disables interrupts, or anything that disables
387	preemption.
388
3892.	If the access might be within an RCU read-side critical section
390	on the one hand, or protected by (say) my_lock on the other,
391	use rcu_dereference_check(), for example::
392
393		p1 = rcu_dereference_check(p->rcu_protected_pointer,
394					   lockdep_is_held(&my_lock));
395
396
3973.	If the access might be within an RCU read-side critical section
398	on the one hand, or protected by either my_lock or your_lock on
399	the other, again use rcu_dereference_check(), for example::
400
401		p1 = rcu_dereference_check(p->rcu_protected_pointer,
402					   lockdep_is_held(&my_lock) ||
403					   lockdep_is_held(&your_lock));
404
4054.	If the access is on the update side, so that it is always protected
406	by my_lock, use rcu_dereference_protected()::
407
408		p1 = rcu_dereference_protected(p->rcu_protected_pointer,
409					       lockdep_is_held(&my_lock));
410
411	This can be extended to handle multiple locks as in #3 above,
412	and both can be extended to check other conditions as well.
413
4145.	If the protection is supplied by the caller, and is thus unknown
415	to this code, that is the rare case when rcu_dereference_raw()
416	is appropriate.  In addition, rcu_dereference_raw() might be
417	appropriate when the lockdep expression would be excessively
418	complex, except that a better approach in that case might be to
419	take a long hard look at your synchronization design.  Still,
420	there are data-locking cases where any one of a very large number
421	of locks or reference counters suffices to protect the pointer,
422	so rcu_dereference_raw() does have its place.
423
424	However, its place is probably quite a bit smaller than one
425	might expect given the number of uses in the current kernel.
426	Ditto for its synonym, rcu_dereference_check( ... , 1), and
427	its close relative, rcu_dereference_protected(... , 1).
428
429
430SPARSE CHECKING OF RCU-PROTECTED POINTERS
431-----------------------------------------
432
433The sparse static-analysis tool checks for direct access to RCU-protected
434pointers, which can result in "interesting" bugs due to compiler
435optimizations involving invented loads and perhaps also load tearing.
436For example, suppose someone mistakenly does something like this::
437
438	p = q->rcu_protected_pointer;
439	do_something_with(p->a);
440	do_something_else_with(p->b);
441
442If register pressure is high, the compiler might optimize "p" out
443of existence, transforming the code to something like this::
444
445	do_something_with(q->rcu_protected_pointer->a);
446	do_something_else_with(q->rcu_protected_pointer->b);
447
448This could fatally disappoint your code if q->rcu_protected_pointer
449changed in the meantime.  Nor is this a theoretical problem:  Exactly
450this sort of bug cost Paul E. McKenney (and several of his innocent
451colleagues) a three-day weekend back in the early 1990s.
452
453Load tearing could of course result in dereferencing a mashup of a pair
454of pointers, which also might fatally disappoint your code.
455
456These problems could have been avoided simply by making the code instead
457read as follows::
458
459	p = rcu_dereference(q->rcu_protected_pointer);
460	do_something_with(p->a);
461	do_something_else_with(p->b);
462
463Unfortunately, these sorts of bugs can be extremely hard to spot during
464review.  This is where the sparse tool comes into play, along with the
465"__rcu" marker.  If you mark a pointer declaration, whether in a structure
466or as a formal parameter, with "__rcu", which tells sparse to complain if
467this pointer is accessed directly.  It will also cause sparse to complain
468if a pointer not marked with "__rcu" is accessed using rcu_dereference()
469and friends.  For example, ->rcu_protected_pointer might be declared as
470follows::
471
472	struct foo __rcu *rcu_protected_pointer;
473
474Use of "__rcu" is opt-in.  If you choose not to use it, then you should
475ignore the sparse warnings.
476