rcu_dereference.rst 17 KB

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