rcu_dereference.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. PROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference()
  2. Most of the time, you can use values from rcu_dereference() or one of
  3. the similar primitives without worries. Dereferencing (prefix "*"),
  4. field selection ("->"), assignment ("="), address-of ("&"), addition and
  5. subtraction of constants, and casts all work quite naturally and safely.
  6. It is nevertheless possible to get into trouble with other operations.
  7. Follow these rules to keep your RCU code working properly:
  8. o You must use one of the rcu_dereference() family of primitives
  9. to load an RCU-protected pointer, otherwise CONFIG_PROVE_RCU
  10. will complain. Worse yet, your code can see random memory-corruption
  11. bugs due to games that compilers and DEC Alpha can play.
  12. Without one of the rcu_dereference() primitives, compilers
  13. can reload the value, and won't your code have fun with two
  14. different values for a single pointer! Without rcu_dereference(),
  15. DEC Alpha can load a pointer, dereference that pointer, and
  16. return data preceding initialization that preceded the store of
  17. the pointer.
  18. In addition, the volatile cast in rcu_dereference() prevents the
  19. compiler from deducing the resulting pointer value. Please see
  20. the section entitled "EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH"
  21. for an example where the compiler can in fact deduce the exact
  22. value of the pointer, and thus cause misordering.
  23. o You are only permitted to use rcu_dereference on pointer values.
  24. The compiler simply knows too much about integral values to
  25. trust it to carry dependencies through integer operations.
  26. There are a very few exceptions, namely that you can temporarily
  27. cast the pointer to uintptr_t in order to:
  28. o Set bits and clear bits down in the must-be-zero low-order
  29. bits of that pointer. This clearly means that the pointer
  30. must have alignment constraints, for example, this does
  31. -not- work in general for char* pointers.
  32. o XOR bits to translate pointers, as is done in some
  33. classic buddy-allocator algorithms.
  34. It is important to cast the value back to pointer before
  35. doing much of anything else with it.
  36. o Avoid cancellation when using the "+" and "-" infix arithmetic
  37. operators. For example, for a given variable "x", avoid
  38. "(x-(uintptr_t)x)" for char* pointers. The compiler is within its
  39. rights to substitute zero for this sort of expression, so that
  40. subsequent accesses no longer depend on the rcu_dereference(),
  41. again possibly resulting in bugs due to misordering.
  42. Of course, if "p" is a pointer from rcu_dereference(), and "a"
  43. and "b" are integers that happen to be equal, the expression
  44. "p+a-b" is safe because its value still necessarily depends on
  45. the rcu_dereference(), thus maintaining proper ordering.
  46. o If you are using RCU to protect JITed functions, so that the
  47. "()" function-invocation operator is applied to a value obtained
  48. (directly or indirectly) from rcu_dereference(), you may need to
  49. interact directly with the hardware to flush instruction caches.
  50. This issue arises on some systems when a newly JITed function is
  51. using the same memory that was used by an earlier JITed function.
  52. o Do not use the results from relational operators ("==", "!=",
  53. ">", ">=", "<", or "<=") when dereferencing. For example,
  54. the following (quite strange) code is buggy:
  55. int *p;
  56. int *q;
  57. ...
  58. p = rcu_dereference(gp)
  59. q = &global_q;
  60. q += p > &oom_p;
  61. r1 = *q; /* BUGGY!!! */
  62. As before, the reason this is buggy is that relational operators
  63. are often compiled using branches. And as before, although
  64. weak-memory machines such as ARM or PowerPC do order stores
  65. after such branches, but can speculate loads, which can again
  66. result in misordering bugs.
  67. o Be very careful about comparing pointers obtained from
  68. rcu_dereference() against non-NULL values. As Linus Torvalds
  69. explained, if the two pointers are equal, the compiler could
  70. substitute the pointer you are comparing against for the pointer
  71. obtained from rcu_dereference(). For example:
  72. p = rcu_dereference(gp);
  73. if (p == &default_struct)
  74. do_default(p->a);
  75. Because the compiler now knows that the value of "p" is exactly
  76. the address of the variable "default_struct", it is free to
  77. transform this code into the following:
  78. p = rcu_dereference(gp);
  79. if (p == &default_struct)
  80. do_default(default_struct.a);
  81. On ARM and Power hardware, the load from "default_struct.a"
  82. can now be speculated, such that it might happen before the
  83. rcu_dereference(). This could result in bugs due to misordering.
  84. However, comparisons are OK in the following cases:
  85. o The comparison was against the NULL pointer. If the
  86. compiler knows that the pointer is NULL, you had better
  87. not be dereferencing it anyway. If the comparison is
  88. non-equal, the compiler is none the wiser. Therefore,
  89. it is safe to compare pointers from rcu_dereference()
  90. against NULL pointers.
  91. o The pointer is never dereferenced after being compared.
  92. Since there are no subsequent dereferences, the compiler
  93. cannot use anything it learned from the comparison
  94. to reorder the non-existent subsequent dereferences.
  95. This sort of comparison occurs frequently when scanning
  96. RCU-protected circular linked lists.
  97. Note that if checks for being within an RCU read-side
  98. critical section are not required and the pointer is never
  99. dereferenced, rcu_access_pointer() should be used in place
  100. of rcu_dereference(). The rcu_access_pointer() primitive
  101. does not require an enclosing read-side critical section,
  102. and also omits the smp_read_barrier_depends() included in
  103. rcu_dereference(), which in turn should provide a small
  104. performance gain in some CPUs (e.g., the DEC Alpha).
  105. o The comparison is against a pointer that references memory
  106. that was initialized "a long time ago." The reason
  107. this is safe is that even if misordering occurs, the
  108. misordering will not affect the accesses that follow
  109. the comparison. So exactly how long ago is "a long
  110. time ago"? Here are some possibilities:
  111. o Compile time.
  112. o Boot time.
  113. o Module-init time for module code.
  114. o Prior to kthread creation for kthread code.
  115. o During some prior acquisition of the lock that
  116. we now hold.
  117. o Before mod_timer() time for a timer handler.
  118. There are many other possibilities involving the Linux
  119. kernel's wide array of primitives that cause code to
  120. be invoked at a later time.
  121. o The pointer being compared against also came from
  122. rcu_dereference(). In this case, both pointers depend
  123. on one rcu_dereference() or another, so you get proper
  124. ordering either way.
  125. That said, this situation can make certain RCU usage
  126. bugs more likely to happen. Which can be a good thing,
  127. at least if they happen during testing. An example
  128. of such an RCU usage bug is shown in the section titled
  129. "EXAMPLE OF AMPLIFIED RCU-USAGE BUG".
  130. o All of the accesses following the comparison are stores,
  131. so that a control dependency preserves the needed ordering.
  132. That said, it is easy to get control dependencies wrong.
  133. Please see the "CONTROL DEPENDENCIES" section of
  134. Documentation/memory-barriers.txt for more details.
  135. o The pointers are not equal -and- the compiler does
  136. not have enough information to deduce the value of the
  137. pointer. Note that the volatile cast in rcu_dereference()
  138. will normally prevent the compiler from knowing too much.
  139. However, please note that if the compiler knows that the
  140. pointer takes on only one of two values, a not-equal
  141. comparison will provide exactly the information that the
  142. compiler needs to deduce the value of the pointer.
  143. o Disable any value-speculation optimizations that your compiler
  144. might provide, especially if you are making use of feedback-based
  145. optimizations that take data collected from prior runs. Such
  146. value-speculation optimizations reorder operations by design.
  147. There is one exception to this rule: Value-speculation
  148. optimizations that leverage the branch-prediction hardware are
  149. safe on strongly ordered systems (such as x86), but not on weakly
  150. ordered systems (such as ARM or Power). Choose your compiler
  151. command-line options wisely!
  152. EXAMPLE OF AMPLIFIED RCU-USAGE BUG
  153. Because updaters can run concurrently with RCU readers, RCU readers can
  154. see stale and/or inconsistent values. If RCU readers need fresh or
  155. consistent values, which they sometimes do, they need to take proper
  156. precautions. To see this, consider the following code fragment:
  157. struct foo {
  158. int a;
  159. int b;
  160. int c;
  161. };
  162. struct foo *gp1;
  163. struct foo *gp2;
  164. void updater(void)
  165. {
  166. struct foo *p;
  167. p = kmalloc(...);
  168. if (p == NULL)
  169. deal_with_it();
  170. p->a = 42; /* Each field in its own cache line. */
  171. p->b = 43;
  172. p->c = 44;
  173. rcu_assign_pointer(gp1, p);
  174. p->b = 143;
  175. p->c = 144;
  176. rcu_assign_pointer(gp2, p);
  177. }
  178. void reader(void)
  179. {
  180. struct foo *p;
  181. struct foo *q;
  182. int r1, r2;
  183. p = rcu_dereference(gp2);
  184. if (p == NULL)
  185. return;
  186. r1 = p->b; /* Guaranteed to get 143. */
  187. q = rcu_dereference(gp1); /* Guaranteed non-NULL. */
  188. if (p == q) {
  189. /* The compiler decides that q->c is same as p->c. */
  190. r2 = p->c; /* Could get 44 on weakly order system. */
  191. }
  192. do_something_with(r1, r2);
  193. }
  194. You might be surprised that the outcome (r1 == 143 && r2 == 44) is possible,
  195. but you should not be. After all, the updater might have been invoked
  196. a second time between the time reader() loaded into "r1" and the time
  197. that it loaded into "r2". The fact that this same result can occur due
  198. to some reordering from the compiler and CPUs is beside the point.
  199. But suppose that the reader needs a consistent view?
  200. Then one approach is to use locking, for example, as follows:
  201. struct foo {
  202. int a;
  203. int b;
  204. int c;
  205. spinlock_t lock;
  206. };
  207. struct foo *gp1;
  208. struct foo *gp2;
  209. void updater(void)
  210. {
  211. struct foo *p;
  212. p = kmalloc(...);
  213. if (p == NULL)
  214. deal_with_it();
  215. spin_lock(&p->lock);
  216. p->a = 42; /* Each field in its own cache line. */
  217. p->b = 43;
  218. p->c = 44;
  219. spin_unlock(&p->lock);
  220. rcu_assign_pointer(gp1, p);
  221. spin_lock(&p->lock);
  222. p->b = 143;
  223. p->c = 144;
  224. spin_unlock(&p->lock);
  225. rcu_assign_pointer(gp2, p);
  226. }
  227. void reader(void)
  228. {
  229. struct foo *p;
  230. struct foo *q;
  231. int r1, r2;
  232. p = rcu_dereference(gp2);
  233. if (p == NULL)
  234. return;
  235. spin_lock(&p->lock);
  236. r1 = p->b; /* Guaranteed to get 143. */
  237. q = rcu_dereference(gp1); /* Guaranteed non-NULL. */
  238. if (p == q) {
  239. /* The compiler decides that q->c is same as p->c. */
  240. r2 = p->c; /* Locking guarantees r2 == 144. */
  241. }
  242. spin_unlock(&p->lock);
  243. do_something_with(r1, r2);
  244. }
  245. As always, use the right tool for the job!
  246. EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH
  247. If a pointer obtained from rcu_dereference() compares not-equal to some
  248. other pointer, the compiler normally has no clue what the value of the
  249. first pointer might be. This lack of knowledge prevents the compiler
  250. from carrying out optimizations that otherwise might destroy the ordering
  251. guarantees that RCU depends on. And the volatile cast in rcu_dereference()
  252. should prevent the compiler from guessing the value.
  253. But without rcu_dereference(), the compiler knows more than you might
  254. expect. Consider the following code fragment:
  255. struct foo {
  256. int a;
  257. int b;
  258. };
  259. static struct foo variable1;
  260. static struct foo variable2;
  261. static struct foo *gp = &variable1;
  262. void updater(void)
  263. {
  264. initialize_foo(&variable2);
  265. rcu_assign_pointer(gp, &variable2);
  266. /*
  267. * The above is the only store to gp in this translation unit,
  268. * and the address of gp is not exported in any way.
  269. */
  270. }
  271. int reader(void)
  272. {
  273. struct foo *p;
  274. p = gp;
  275. barrier();
  276. if (p == &variable1)
  277. return p->a; /* Must be variable1.a. */
  278. else
  279. return p->b; /* Must be variable2.b. */
  280. }
  281. Because the compiler can see all stores to "gp", it knows that the only
  282. possible values of "gp" are "variable1" on the one hand and "variable2"
  283. on the other. The comparison in reader() therefore tells the compiler
  284. the exact value of "p" even in the not-equals case. This allows the
  285. compiler to make the return values independent of the load from "gp",
  286. in turn destroying the ordering between this load and the loads of the
  287. return values. This can result in "p->b" returning pre-initialization
  288. garbage values.
  289. In short, rcu_dereference() is -not- optional when you are going to
  290. dereference the resulting pointer.