rcu_dereference.rst 18 KB

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