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