GNU Linux-libre 5.10.217-gnu1
[releases.git] / include / linux / rcupdate.h
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 /*
3  * Read-Copy Update mechanism for mutual exclusion
4  *
5  * Copyright IBM Corporation, 2001
6  *
7  * Author: Dipankar Sarma <dipankar@in.ibm.com>
8  *
9  * Based on the original work by Paul McKenney <paulmck@vnet.ibm.com>
10  * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
11  * Papers:
12  * http://www.rdrop.com/users/paulmck/paper/rclockpdcsproof.pdf
13  * http://lse.sourceforge.net/locking/rclock_OLS.2001.05.01c.sc.pdf (OLS2001)
14  *
15  * For detailed explanation of Read-Copy Update mechanism see -
16  *              http://lse.sourceforge.net/locking/rcupdate.html
17  *
18  */
19
20 #ifndef __LINUX_RCUPDATE_H
21 #define __LINUX_RCUPDATE_H
22
23 #include <linux/types.h>
24 #include <linux/compiler.h>
25 #include <linux/atomic.h>
26 #include <linux/irqflags.h>
27 #include <linux/preempt.h>
28 #include <linux/bottom_half.h>
29 #include <linux/lockdep.h>
30 #include <asm/processor.h>
31 #include <linux/cpumask.h>
32
33 #define ULONG_CMP_GE(a, b)      (ULONG_MAX / 2 >= (a) - (b))
34 #define ULONG_CMP_LT(a, b)      (ULONG_MAX / 2 < (a) - (b))
35 #define ulong2long(a)           (*(long *)(&(a)))
36 #define USHORT_CMP_GE(a, b)     (USHRT_MAX / 2 >= (unsigned short)((a) - (b)))
37 #define USHORT_CMP_LT(a, b)     (USHRT_MAX / 2 < (unsigned short)((a) - (b)))
38
39 /* Exported common interfaces */
40 void call_rcu(struct rcu_head *head, rcu_callback_t func);
41 void rcu_barrier_tasks(void);
42 void rcu_barrier_tasks_rude(void);
43 void synchronize_rcu(void);
44
45 #ifdef CONFIG_PREEMPT_RCU
46
47 void __rcu_read_lock(void);
48 void __rcu_read_unlock(void);
49
50 /*
51  * Defined as a macro as it is a very low level header included from
52  * areas that don't even know about current.  This gives the rcu_read_lock()
53  * nesting depth, but makes sense only if CONFIG_PREEMPT_RCU -- in other
54  * types of kernel builds, the rcu_read_lock() nesting depth is unknowable.
55  */
56 #define rcu_preempt_depth() (current->rcu_read_lock_nesting)
57
58 #else /* #ifdef CONFIG_PREEMPT_RCU */
59
60 #ifdef CONFIG_TINY_RCU
61 #define rcu_read_unlock_strict() do { } while (0)
62 #else
63 void rcu_read_unlock_strict(void);
64 #endif
65
66 static inline void __rcu_read_lock(void)
67 {
68         preempt_disable();
69 }
70
71 static inline void __rcu_read_unlock(void)
72 {
73         preempt_enable();
74         rcu_read_unlock_strict();
75 }
76
77 static inline int rcu_preempt_depth(void)
78 {
79         return 0;
80 }
81
82 #endif /* #else #ifdef CONFIG_PREEMPT_RCU */
83
84 /* Internal to kernel */
85 void rcu_init(void);
86 extern int rcu_scheduler_active __read_mostly;
87 void rcu_sched_clock_irq(int user);
88 void rcu_report_dead(unsigned int cpu);
89 void rcutree_migrate_callbacks(int cpu);
90
91 #ifdef CONFIG_TASKS_RCU_GENERIC
92 void rcu_init_tasks_generic(void);
93 #else
94 static inline void rcu_init_tasks_generic(void) { }
95 #endif
96
97 #ifdef CONFIG_RCU_STALL_COMMON
98 void rcu_sysrq_start(void);
99 void rcu_sysrq_end(void);
100 #else /* #ifdef CONFIG_RCU_STALL_COMMON */
101 static inline void rcu_sysrq_start(void) { }
102 static inline void rcu_sysrq_end(void) { }
103 #endif /* #else #ifdef CONFIG_RCU_STALL_COMMON */
104
105 #ifdef CONFIG_NO_HZ_FULL
106 void rcu_user_enter(void);
107 void rcu_user_exit(void);
108 #else
109 static inline void rcu_user_enter(void) { }
110 static inline void rcu_user_exit(void) { }
111 #endif /* CONFIG_NO_HZ_FULL */
112
113 #ifdef CONFIG_RCU_NOCB_CPU
114 void rcu_init_nohz(void);
115 void rcu_nocb_flush_deferred_wakeup(void);
116 #else /* #ifdef CONFIG_RCU_NOCB_CPU */
117 static inline void rcu_init_nohz(void) { }
118 static inline void rcu_nocb_flush_deferred_wakeup(void) { }
119 #endif /* #else #ifdef CONFIG_RCU_NOCB_CPU */
120
121 /**
122  * RCU_NONIDLE - Indicate idle-loop code that needs RCU readers
123  * @a: Code that RCU needs to pay attention to.
124  *
125  * RCU read-side critical sections are forbidden in the inner idle loop,
126  * that is, between the rcu_idle_enter() and the rcu_idle_exit() -- RCU
127  * will happily ignore any such read-side critical sections.  However,
128  * things like powertop need tracepoints in the inner idle loop.
129  *
130  * This macro provides the way out:  RCU_NONIDLE(do_something_with_RCU())
131  * will tell RCU that it needs to pay attention, invoke its argument
132  * (in this example, calling the do_something_with_RCU() function),
133  * and then tell RCU to go back to ignoring this CPU.  It is permissible
134  * to nest RCU_NONIDLE() wrappers, but not indefinitely (but the limit is
135  * on the order of a million or so, even on 32-bit systems).  It is
136  * not legal to block within RCU_NONIDLE(), nor is it permissible to
137  * transfer control either into or out of RCU_NONIDLE()'s statement.
138  */
139 #define RCU_NONIDLE(a) \
140         do { \
141                 rcu_irq_enter_irqson(); \
142                 do { a; } while (0); \
143                 rcu_irq_exit_irqson(); \
144         } while (0)
145
146 /*
147  * Note a quasi-voluntary context switch for RCU-tasks's benefit.
148  * This is a macro rather than an inline function to avoid #include hell.
149  */
150 #ifdef CONFIG_TASKS_RCU_GENERIC
151
152 # ifdef CONFIG_TASKS_RCU
153 # define rcu_tasks_classic_qs(t, preempt)                               \
154         do {                                                            \
155                 if (!(preempt) && READ_ONCE((t)->rcu_tasks_holdout))    \
156                         WRITE_ONCE((t)->rcu_tasks_holdout, false);      \
157         } while (0)
158 void call_rcu_tasks(struct rcu_head *head, rcu_callback_t func);
159 void synchronize_rcu_tasks(void);
160 # else
161 # define rcu_tasks_classic_qs(t, preempt) do { } while (0)
162 # define call_rcu_tasks call_rcu
163 # define synchronize_rcu_tasks synchronize_rcu
164 # endif
165
166 # ifdef CONFIG_TASKS_TRACE_RCU
167 # define rcu_tasks_trace_qs(t)                                          \
168         do {                                                            \
169                 if (!likely(READ_ONCE((t)->trc_reader_checked)) &&      \
170                     !unlikely(READ_ONCE((t)->trc_reader_nesting))) {    \
171                         smp_store_release(&(t)->trc_reader_checked, true); \
172                         smp_mb(); /* Readers partitioned by store. */   \
173                 }                                                       \
174         } while (0)
175 # else
176 # define rcu_tasks_trace_qs(t) do { } while (0)
177 # endif
178
179 #define rcu_tasks_qs(t, preempt)                                        \
180 do {                                                                    \
181         rcu_tasks_classic_qs((t), (preempt));                           \
182         rcu_tasks_trace_qs((t));                                        \
183 } while (0)
184
185 # ifdef CONFIG_TASKS_RUDE_RCU
186 void call_rcu_tasks_rude(struct rcu_head *head, rcu_callback_t func);
187 void synchronize_rcu_tasks_rude(void);
188 # endif
189
190 #define rcu_note_voluntary_context_switch(t) rcu_tasks_qs(t, false)
191 void exit_tasks_rcu_start(void);
192 void exit_tasks_rcu_stop(void);
193 void exit_tasks_rcu_finish(void);
194 #else /* #ifdef CONFIG_TASKS_RCU_GENERIC */
195 #define rcu_tasks_qs(t, preempt) do { } while (0)
196 #define rcu_note_voluntary_context_switch(t) do { } while (0)
197 #define call_rcu_tasks call_rcu
198 #define synchronize_rcu_tasks synchronize_rcu
199 static inline void exit_tasks_rcu_start(void) { }
200 static inline void exit_tasks_rcu_stop(void) { }
201 static inline void exit_tasks_rcu_finish(void) { }
202 #endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */
203
204 /**
205  * rcu_trace_implies_rcu_gp - does an RCU Tasks Trace grace period imply an RCU grace period?
206  *
207  * As an accident of implementation, an RCU Tasks Trace grace period also
208  * acts as an RCU grace period.  However, this could change at any time.
209  * Code relying on this accident must call this function to verify that
210  * this accident is still happening.
211  *
212  * You have been warned!
213  */
214 static inline bool rcu_trace_implies_rcu_gp(void) { return true; }
215
216 /**
217  * cond_resched_tasks_rcu_qs - Report potential quiescent states to RCU
218  *
219  * This macro resembles cond_resched(), except that it is defined to
220  * report potential quiescent states to RCU-tasks even if the cond_resched()
221  * machinery were to be shut off, as some advocate for PREEMPTION kernels.
222  */
223 #define cond_resched_tasks_rcu_qs() \
224 do { \
225         rcu_tasks_qs(current, false); \
226         cond_resched(); \
227 } while (0)
228
229 /**
230  * rcu_softirq_qs_periodic - Report RCU and RCU-Tasks quiescent states
231  * @old_ts: jiffies at start of processing.
232  *
233  * This helper is for long-running softirq handlers, such as NAPI threads in
234  * networking. The caller should initialize the variable passed in as @old_ts
235  * at the beginning of the softirq handler. When invoked frequently, this macro
236  * will invoke rcu_softirq_qs() every 100 milliseconds thereafter, which will
237  * provide both RCU and RCU-Tasks quiescent states. Note that this macro
238  * modifies its old_ts argument.
239  *
240  * Because regions of code that have disabled softirq act as RCU read-side
241  * critical sections, this macro should be invoked with softirq (and
242  * preemption) enabled.
243  *
244  * The macro is not needed when CONFIG_PREEMPT_RT is defined. RT kernels would
245  * have more chance to invoke schedule() calls and provide necessary quiescent
246  * states. As a contrast, calling cond_resched() only won't achieve the same
247  * effect because cond_resched() does not provide RCU-Tasks quiescent states.
248  */
249 #define rcu_softirq_qs_periodic(old_ts) \
250 do { \
251         if (!IS_ENABLED(CONFIG_PREEMPT_RT) && \
252             time_after(jiffies, (old_ts) + HZ / 10)) { \
253                 preempt_disable(); \
254                 rcu_softirq_qs(); \
255                 preempt_enable(); \
256                 (old_ts) = jiffies; \
257         } \
258 } while (0)
259
260 /*
261  * Infrastructure to implement the synchronize_() primitives in
262  * TREE_RCU and rcu_barrier_() primitives in TINY_RCU.
263  */
264
265 #if defined(CONFIG_TREE_RCU)
266 #include <linux/rcutree.h>
267 #elif defined(CONFIG_TINY_RCU)
268 #include <linux/rcutiny.h>
269 #else
270 #error "Unknown RCU implementation specified to kernel configuration"
271 #endif
272
273 /*
274  * The init_rcu_head_on_stack() and destroy_rcu_head_on_stack() calls
275  * are needed for dynamic initialization and destruction of rcu_head
276  * on the stack, and init_rcu_head()/destroy_rcu_head() are needed for
277  * dynamic initialization and destruction of statically allocated rcu_head
278  * structures.  However, rcu_head structures allocated dynamically in the
279  * heap don't need any initialization.
280  */
281 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
282 void init_rcu_head(struct rcu_head *head);
283 void destroy_rcu_head(struct rcu_head *head);
284 void init_rcu_head_on_stack(struct rcu_head *head);
285 void destroy_rcu_head_on_stack(struct rcu_head *head);
286 #else /* !CONFIG_DEBUG_OBJECTS_RCU_HEAD */
287 static inline void init_rcu_head(struct rcu_head *head) { }
288 static inline void destroy_rcu_head(struct rcu_head *head) { }
289 static inline void init_rcu_head_on_stack(struct rcu_head *head) { }
290 static inline void destroy_rcu_head_on_stack(struct rcu_head *head) { }
291 #endif  /* #else !CONFIG_DEBUG_OBJECTS_RCU_HEAD */
292
293 #if defined(CONFIG_HOTPLUG_CPU) && defined(CONFIG_PROVE_RCU)
294 bool rcu_lockdep_current_cpu_online(void);
295 #else /* #if defined(CONFIG_HOTPLUG_CPU) && defined(CONFIG_PROVE_RCU) */
296 static inline bool rcu_lockdep_current_cpu_online(void) { return true; }
297 #endif /* #else #if defined(CONFIG_HOTPLUG_CPU) && defined(CONFIG_PROVE_RCU) */
298
299 #ifdef CONFIG_DEBUG_LOCK_ALLOC
300
301 static inline void rcu_lock_acquire(struct lockdep_map *map)
302 {
303         lock_acquire(map, 0, 0, 2, 0, NULL, _THIS_IP_);
304 }
305
306 static inline void rcu_lock_release(struct lockdep_map *map)
307 {
308         lock_release(map, _THIS_IP_);
309 }
310
311 extern struct lockdep_map rcu_lock_map;
312 extern struct lockdep_map rcu_bh_lock_map;
313 extern struct lockdep_map rcu_sched_lock_map;
314 extern struct lockdep_map rcu_callback_map;
315 int debug_lockdep_rcu_enabled(void);
316 int rcu_read_lock_held(void);
317 int rcu_read_lock_bh_held(void);
318 int rcu_read_lock_sched_held(void);
319 int rcu_read_lock_any_held(void);
320
321 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
322
323 # define rcu_lock_acquire(a)            do { } while (0)
324 # define rcu_lock_release(a)            do { } while (0)
325
326 static inline int rcu_read_lock_held(void)
327 {
328         return 1;
329 }
330
331 static inline int rcu_read_lock_bh_held(void)
332 {
333         return 1;
334 }
335
336 static inline int rcu_read_lock_sched_held(void)
337 {
338         return !preemptible();
339 }
340
341 static inline int rcu_read_lock_any_held(void)
342 {
343         return !preemptible();
344 }
345
346 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
347
348 #ifdef CONFIG_PROVE_RCU
349
350 /**
351  * RCU_LOCKDEP_WARN - emit lockdep splat if specified condition is met
352  * @c: condition to check
353  * @s: informative message
354  *
355  * This checks debug_lockdep_rcu_enabled() before checking (c) to
356  * prevent early boot splats due to lockdep not yet being initialized,
357  * and rechecks it after checking (c) to prevent false-positive splats
358  * due to races with lockdep being disabled.  See commit 3066820034b5dd
359  * ("rcu: Reject RCU_LOCKDEP_WARN() false positives") for more detail.
360  */
361 #define RCU_LOCKDEP_WARN(c, s)                                          \
362         do {                                                            \
363                 static bool __section(".data.unlikely") __warned;       \
364                 if (debug_lockdep_rcu_enabled() && (c) &&               \
365                     debug_lockdep_rcu_enabled() && !__warned) {         \
366                         __warned = true;                                \
367                         lockdep_rcu_suspicious(__FILE__, __LINE__, s);  \
368                 }                                                       \
369         } while (0)
370
371 #if defined(CONFIG_PROVE_RCU) && !defined(CONFIG_PREEMPT_RCU)
372 static inline void rcu_preempt_sleep_check(void)
373 {
374         RCU_LOCKDEP_WARN(lock_is_held(&rcu_lock_map),
375                          "Illegal context switch in RCU read-side critical section");
376 }
377 #else /* #ifdef CONFIG_PROVE_RCU */
378 static inline void rcu_preempt_sleep_check(void) { }
379 #endif /* #else #ifdef CONFIG_PROVE_RCU */
380
381 #define rcu_sleep_check()                                               \
382         do {                                                            \
383                 rcu_preempt_sleep_check();                              \
384                 RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map),        \
385                                  "Illegal context switch in RCU-bh read-side critical section"); \
386                 RCU_LOCKDEP_WARN(lock_is_held(&rcu_sched_lock_map),     \
387                                  "Illegal context switch in RCU-sched read-side critical section"); \
388         } while (0)
389
390 #else /* #ifdef CONFIG_PROVE_RCU */
391
392 #define RCU_LOCKDEP_WARN(c, s) do { } while (0)
393 #define rcu_sleep_check() do { } while (0)
394
395 #endif /* #else #ifdef CONFIG_PROVE_RCU */
396
397 /*
398  * Helper functions for rcu_dereference_check(), rcu_dereference_protected()
399  * and rcu_assign_pointer().  Some of these could be folded into their
400  * callers, but they are left separate in order to ease introduction of
401  * multiple pointers markings to match different RCU implementations
402  * (e.g., __srcu), should this make sense in the future.
403  */
404
405 #ifdef __CHECKER__
406 #define rcu_check_sparse(p, space) \
407         ((void)(((typeof(*p) space *)p) == p))
408 #else /* #ifdef __CHECKER__ */
409 #define rcu_check_sparse(p, space)
410 #endif /* #else #ifdef __CHECKER__ */
411
412 /**
413  * unrcu_pointer - mark a pointer as not being RCU protected
414  * @p: pointer needing to lose its __rcu property
415  *
416  * Converts @p from an __rcu pointer to a __kernel pointer.
417  * This allows an __rcu pointer to be used with xchg() and friends.
418  */
419 #define unrcu_pointer(p)                                                \
420 ({                                                                      \
421         typeof(*p) *_________p1 = (typeof(*p) *__force)(p);             \
422         rcu_check_sparse(p, __rcu);                                     \
423         ((typeof(*p) __force __kernel *)(_________p1));                 \
424 })
425
426 #define __rcu_access_pointer(p, space) \
427 ({ \
428         typeof(*p) *_________p1 = (typeof(*p) *__force)READ_ONCE(p); \
429         rcu_check_sparse(p, space); \
430         ((typeof(*p) __force __kernel *)(_________p1)); \
431 })
432 #define __rcu_dereference_check(p, c, space) \
433 ({ \
434         /* Dependency order vs. p above. */ \
435         typeof(*p) *________p1 = (typeof(*p) *__force)READ_ONCE(p); \
436         RCU_LOCKDEP_WARN(!(c), "suspicious rcu_dereference_check() usage"); \
437         rcu_check_sparse(p, space); \
438         ((typeof(*p) __force __kernel *)(________p1)); \
439 })
440 #define __rcu_dereference_protected(p, c, space) \
441 ({ \
442         RCU_LOCKDEP_WARN(!(c), "suspicious rcu_dereference_protected() usage"); \
443         rcu_check_sparse(p, space); \
444         ((typeof(*p) __force __kernel *)(p)); \
445 })
446 #define rcu_dereference_raw(p) \
447 ({ \
448         /* Dependency order vs. p above. */ \
449         typeof(p) ________p1 = READ_ONCE(p); \
450         ((typeof(*p) __force __kernel *)(________p1)); \
451 })
452
453 /**
454  * RCU_INITIALIZER() - statically initialize an RCU-protected global variable
455  * @v: The value to statically initialize with.
456  */
457 #define RCU_INITIALIZER(v) (typeof(*(v)) __force __rcu *)(v)
458
459 /**
460  * rcu_assign_pointer() - assign to RCU-protected pointer
461  * @p: pointer to assign to
462  * @v: value to assign (publish)
463  *
464  * Assigns the specified value to the specified RCU-protected
465  * pointer, ensuring that any concurrent RCU readers will see
466  * any prior initialization.
467  *
468  * Inserts memory barriers on architectures that require them
469  * (which is most of them), and also prevents the compiler from
470  * reordering the code that initializes the structure after the pointer
471  * assignment.  More importantly, this call documents which pointers
472  * will be dereferenced by RCU read-side code.
473  *
474  * In some special cases, you may use RCU_INIT_POINTER() instead
475  * of rcu_assign_pointer().  RCU_INIT_POINTER() is a bit faster due
476  * to the fact that it does not constrain either the CPU or the compiler.
477  * That said, using RCU_INIT_POINTER() when you should have used
478  * rcu_assign_pointer() is a very bad thing that results in
479  * impossible-to-diagnose memory corruption.  So please be careful.
480  * See the RCU_INIT_POINTER() comment header for details.
481  *
482  * Note that rcu_assign_pointer() evaluates each of its arguments only
483  * once, appearances notwithstanding.  One of the "extra" evaluations
484  * is in typeof() and the other visible only to sparse (__CHECKER__),
485  * neither of which actually execute the argument.  As with most cpp
486  * macros, this execute-arguments-only-once property is important, so
487  * please be careful when making changes to rcu_assign_pointer() and the
488  * other macros that it invokes.
489  */
490 #define rcu_assign_pointer(p, v)                                              \
491 do {                                                                          \
492         uintptr_t _r_a_p__v = (uintptr_t)(v);                                 \
493         rcu_check_sparse(p, __rcu);                                           \
494                                                                               \
495         if (__builtin_constant_p(v) && (_r_a_p__v) == (uintptr_t)NULL)        \
496                 WRITE_ONCE((p), (typeof(p))(_r_a_p__v));                      \
497         else                                                                  \
498                 smp_store_release(&p, RCU_INITIALIZER((typeof(p))_r_a_p__v)); \
499 } while (0)
500
501 /**
502  * rcu_replace_pointer() - replace an RCU pointer, returning its old value
503  * @rcu_ptr: RCU pointer, whose old value is returned
504  * @ptr: regular pointer
505  * @c: the lockdep conditions under which the dereference will take place
506  *
507  * Perform a replacement, where @rcu_ptr is an RCU-annotated
508  * pointer and @c is the lockdep argument that is passed to the
509  * rcu_dereference_protected() call used to read that pointer.  The old
510  * value of @rcu_ptr is returned, and @rcu_ptr is set to @ptr.
511  */
512 #define rcu_replace_pointer(rcu_ptr, ptr, c)                            \
513 ({                                                                      \
514         typeof(ptr) __tmp = rcu_dereference_protected((rcu_ptr), (c));  \
515         rcu_assign_pointer((rcu_ptr), (ptr));                           \
516         __tmp;                                                          \
517 })
518
519 /**
520  * rcu_access_pointer() - fetch RCU pointer with no dereferencing
521  * @p: The pointer to read
522  *
523  * Return the value of the specified RCU-protected pointer, but omit the
524  * lockdep checks for being in an RCU read-side critical section.  This is
525  * useful when the value of this pointer is accessed, but the pointer is
526  * not dereferenced, for example, when testing an RCU-protected pointer
527  * against NULL.  Although rcu_access_pointer() may also be used in cases
528  * where update-side locks prevent the value of the pointer from changing,
529  * you should instead use rcu_dereference_protected() for this use case.
530  *
531  * It is also permissible to use rcu_access_pointer() when read-side
532  * access to the pointer was removed at least one grace period ago, as
533  * is the case in the context of the RCU callback that is freeing up
534  * the data, or after a synchronize_rcu() returns.  This can be useful
535  * when tearing down multi-linked structures after a grace period
536  * has elapsed.
537  */
538 #define rcu_access_pointer(p) __rcu_access_pointer((p), __rcu)
539
540 /**
541  * rcu_dereference_check() - rcu_dereference with debug checking
542  * @p: The pointer to read, prior to dereferencing
543  * @c: The conditions under which the dereference will take place
544  *
545  * Do an rcu_dereference(), but check that the conditions under which the
546  * dereference will take place are correct.  Typically the conditions
547  * indicate the various locking conditions that should be held at that
548  * point.  The check should return true if the conditions are satisfied.
549  * An implicit check for being in an RCU read-side critical section
550  * (rcu_read_lock()) is included.
551  *
552  * For example:
553  *
554  *      bar = rcu_dereference_check(foo->bar, lockdep_is_held(&foo->lock));
555  *
556  * could be used to indicate to lockdep that foo->bar may only be dereferenced
557  * if either rcu_read_lock() is held, or that the lock required to replace
558  * the bar struct at foo->bar is held.
559  *
560  * Note that the list of conditions may also include indications of when a lock
561  * need not be held, for example during initialisation or destruction of the
562  * target struct:
563  *
564  *      bar = rcu_dereference_check(foo->bar, lockdep_is_held(&foo->lock) ||
565  *                                            atomic_read(&foo->usage) == 0);
566  *
567  * Inserts memory barriers on architectures that require them
568  * (currently only the Alpha), prevents the compiler from refetching
569  * (and from merging fetches), and, more importantly, documents exactly
570  * which pointers are protected by RCU and checks that the pointer is
571  * annotated as __rcu.
572  */
573 #define rcu_dereference_check(p, c) \
574         __rcu_dereference_check((p), (c) || rcu_read_lock_held(), __rcu)
575
576 /**
577  * rcu_dereference_bh_check() - rcu_dereference_bh with debug checking
578  * @p: The pointer to read, prior to dereferencing
579  * @c: The conditions under which the dereference will take place
580  *
581  * This is the RCU-bh counterpart to rcu_dereference_check().
582  */
583 #define rcu_dereference_bh_check(p, c) \
584         __rcu_dereference_check((p), (c) || rcu_read_lock_bh_held(), __rcu)
585
586 /**
587  * rcu_dereference_sched_check() - rcu_dereference_sched with debug checking
588  * @p: The pointer to read, prior to dereferencing
589  * @c: The conditions under which the dereference will take place
590  *
591  * This is the RCU-sched counterpart to rcu_dereference_check().
592  */
593 #define rcu_dereference_sched_check(p, c) \
594         __rcu_dereference_check((p), (c) || rcu_read_lock_sched_held(), \
595                                 __rcu)
596
597 /*
598  * The tracing infrastructure traces RCU (we want that), but unfortunately
599  * some of the RCU checks causes tracing to lock up the system.
600  *
601  * The no-tracing version of rcu_dereference_raw() must not call
602  * rcu_read_lock_held().
603  */
604 #define rcu_dereference_raw_check(p) __rcu_dereference_check((p), 1, __rcu)
605
606 /**
607  * rcu_dereference_protected() - fetch RCU pointer when updates prevented
608  * @p: The pointer to read, prior to dereferencing
609  * @c: The conditions under which the dereference will take place
610  *
611  * Return the value of the specified RCU-protected pointer, but omit
612  * the READ_ONCE().  This is useful in cases where update-side locks
613  * prevent the value of the pointer from changing.  Please note that this
614  * primitive does *not* prevent the compiler from repeating this reference
615  * or combining it with other references, so it should not be used without
616  * protection of appropriate locks.
617  *
618  * This function is only for update-side use.  Using this function
619  * when protected only by rcu_read_lock() will result in infrequent
620  * but very ugly failures.
621  */
622 #define rcu_dereference_protected(p, c) \
623         __rcu_dereference_protected((p), (c), __rcu)
624
625
626 /**
627  * rcu_dereference() - fetch RCU-protected pointer for dereferencing
628  * @p: The pointer to read, prior to dereferencing
629  *
630  * This is a simple wrapper around rcu_dereference_check().
631  */
632 #define rcu_dereference(p) rcu_dereference_check(p, 0)
633
634 /**
635  * rcu_dereference_bh() - fetch an RCU-bh-protected pointer for dereferencing
636  * @p: The pointer to read, prior to dereferencing
637  *
638  * Makes rcu_dereference_check() do the dirty work.
639  */
640 #define rcu_dereference_bh(p) rcu_dereference_bh_check(p, 0)
641
642 /**
643  * rcu_dereference_sched() - fetch RCU-sched-protected pointer for dereferencing
644  * @p: The pointer to read, prior to dereferencing
645  *
646  * Makes rcu_dereference_check() do the dirty work.
647  */
648 #define rcu_dereference_sched(p) rcu_dereference_sched_check(p, 0)
649
650 /**
651  * rcu_pointer_handoff() - Hand off a pointer from RCU to other mechanism
652  * @p: The pointer to hand off
653  *
654  * This is simply an identity function, but it documents where a pointer
655  * is handed off from RCU to some other synchronization mechanism, for
656  * example, reference counting or locking.  In C11, it would map to
657  * kill_dependency().  It could be used as follows::
658  *
659  *      rcu_read_lock();
660  *      p = rcu_dereference(gp);
661  *      long_lived = is_long_lived(p);
662  *      if (long_lived) {
663  *              if (!atomic_inc_not_zero(p->refcnt))
664  *                      long_lived = false;
665  *              else
666  *                      p = rcu_pointer_handoff(p);
667  *      }
668  *      rcu_read_unlock();
669  */
670 #define rcu_pointer_handoff(p) (p)
671
672 /**
673  * rcu_read_lock() - mark the beginning of an RCU read-side critical section
674  *
675  * When synchronize_rcu() is invoked on one CPU while other CPUs
676  * are within RCU read-side critical sections, then the
677  * synchronize_rcu() is guaranteed to block until after all the other
678  * CPUs exit their critical sections.  Similarly, if call_rcu() is invoked
679  * on one CPU while other CPUs are within RCU read-side critical
680  * sections, invocation of the corresponding RCU callback is deferred
681  * until after the all the other CPUs exit their critical sections.
682  *
683  * Note, however, that RCU callbacks are permitted to run concurrently
684  * with new RCU read-side critical sections.  One way that this can happen
685  * is via the following sequence of events: (1) CPU 0 enters an RCU
686  * read-side critical section, (2) CPU 1 invokes call_rcu() to register
687  * an RCU callback, (3) CPU 0 exits the RCU read-side critical section,
688  * (4) CPU 2 enters a RCU read-side critical section, (5) the RCU
689  * callback is invoked.  This is legal, because the RCU read-side critical
690  * section that was running concurrently with the call_rcu() (and which
691  * therefore might be referencing something that the corresponding RCU
692  * callback would free up) has completed before the corresponding
693  * RCU callback is invoked.
694  *
695  * RCU read-side critical sections may be nested.  Any deferred actions
696  * will be deferred until the outermost RCU read-side critical section
697  * completes.
698  *
699  * You can avoid reading and understanding the next paragraph by
700  * following this rule: don't put anything in an rcu_read_lock() RCU
701  * read-side critical section that would block in a !PREEMPTION kernel.
702  * But if you want the full story, read on!
703  *
704  * In non-preemptible RCU implementations (pure TREE_RCU and TINY_RCU),
705  * it is illegal to block while in an RCU read-side critical section.
706  * In preemptible RCU implementations (PREEMPT_RCU) in CONFIG_PREEMPTION
707  * kernel builds, RCU read-side critical sections may be preempted,
708  * but explicit blocking is illegal.  Finally, in preemptible RCU
709  * implementations in real-time (with -rt patchset) kernel builds, RCU
710  * read-side critical sections may be preempted and they may also block, but
711  * only when acquiring spinlocks that are subject to priority inheritance.
712  */
713 static __always_inline void rcu_read_lock(void)
714 {
715         __rcu_read_lock();
716         __acquire(RCU);
717         rcu_lock_acquire(&rcu_lock_map);
718         RCU_LOCKDEP_WARN(!rcu_is_watching(),
719                          "rcu_read_lock() used illegally while idle");
720 }
721
722 /*
723  * So where is rcu_write_lock()?  It does not exist, as there is no
724  * way for writers to lock out RCU readers.  This is a feature, not
725  * a bug -- this property is what provides RCU's performance benefits.
726  * Of course, writers must coordinate with each other.  The normal
727  * spinlock primitives work well for this, but any other technique may be
728  * used as well.  RCU does not care how the writers keep out of each
729  * others' way, as long as they do so.
730  */
731
732 /**
733  * rcu_read_unlock() - marks the end of an RCU read-side critical section.
734  *
735  * In most situations, rcu_read_unlock() is immune from deadlock.
736  * However, in kernels built with CONFIG_RCU_BOOST, rcu_read_unlock()
737  * is responsible for deboosting, which it does via rt_mutex_unlock().
738  * Unfortunately, this function acquires the scheduler's runqueue and
739  * priority-inheritance spinlocks.  This means that deadlock could result
740  * if the caller of rcu_read_unlock() already holds one of these locks or
741  * any lock that is ever acquired while holding them.
742  *
743  * That said, RCU readers are never priority boosted unless they were
744  * preempted.  Therefore, one way to avoid deadlock is to make sure
745  * that preemption never happens within any RCU read-side critical
746  * section whose outermost rcu_read_unlock() is called with one of
747  * rt_mutex_unlock()'s locks held.  Such preemption can be avoided in
748  * a number of ways, for example, by invoking preempt_disable() before
749  * critical section's outermost rcu_read_lock().
750  *
751  * Given that the set of locks acquired by rt_mutex_unlock() might change
752  * at any time, a somewhat more future-proofed approach is to make sure
753  * that that preemption never happens within any RCU read-side critical
754  * section whose outermost rcu_read_unlock() is called with irqs disabled.
755  * This approach relies on the fact that rt_mutex_unlock() currently only
756  * acquires irq-disabled locks.
757  *
758  * The second of these two approaches is best in most situations,
759  * however, the first approach can also be useful, at least to those
760  * developers willing to keep abreast of the set of locks acquired by
761  * rt_mutex_unlock().
762  *
763  * See rcu_read_lock() for more information.
764  */
765 static inline void rcu_read_unlock(void)
766 {
767         RCU_LOCKDEP_WARN(!rcu_is_watching(),
768                          "rcu_read_unlock() used illegally while idle");
769         __release(RCU);
770         __rcu_read_unlock();
771         rcu_lock_release(&rcu_lock_map); /* Keep acq info for rls diags. */
772 }
773
774 /**
775  * rcu_read_lock_bh() - mark the beginning of an RCU-bh critical section
776  *
777  * This is equivalent of rcu_read_lock(), but also disables softirqs.
778  * Note that anything else that disables softirqs can also serve as
779  * an RCU read-side critical section.
780  *
781  * Note that rcu_read_lock_bh() and the matching rcu_read_unlock_bh()
782  * must occur in the same context, for example, it is illegal to invoke
783  * rcu_read_unlock_bh() from one task if the matching rcu_read_lock_bh()
784  * was invoked from some other task.
785  */
786 static inline void rcu_read_lock_bh(void)
787 {
788         local_bh_disable();
789         __acquire(RCU_BH);
790         rcu_lock_acquire(&rcu_bh_lock_map);
791         RCU_LOCKDEP_WARN(!rcu_is_watching(),
792                          "rcu_read_lock_bh() used illegally while idle");
793 }
794
795 /**
796  * rcu_read_unlock_bh() - marks the end of a softirq-only RCU critical section
797  *
798  * See rcu_read_lock_bh() for more information.
799  */
800 static inline void rcu_read_unlock_bh(void)
801 {
802         RCU_LOCKDEP_WARN(!rcu_is_watching(),
803                          "rcu_read_unlock_bh() used illegally while idle");
804         rcu_lock_release(&rcu_bh_lock_map);
805         __release(RCU_BH);
806         local_bh_enable();
807 }
808
809 /**
810  * rcu_read_lock_sched() - mark the beginning of a RCU-sched critical section
811  *
812  * This is equivalent of rcu_read_lock(), but disables preemption.
813  * Read-side critical sections can also be introduced by anything else
814  * that disables preemption, including local_irq_disable() and friends.
815  *
816  * Note that rcu_read_lock_sched() and the matching rcu_read_unlock_sched()
817  * must occur in the same context, for example, it is illegal to invoke
818  * rcu_read_unlock_sched() from process context if the matching
819  * rcu_read_lock_sched() was invoked from an NMI handler.
820  */
821 static inline void rcu_read_lock_sched(void)
822 {
823         preempt_disable();
824         __acquire(RCU_SCHED);
825         rcu_lock_acquire(&rcu_sched_lock_map);
826         RCU_LOCKDEP_WARN(!rcu_is_watching(),
827                          "rcu_read_lock_sched() used illegally while idle");
828 }
829
830 /* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */
831 static inline notrace void rcu_read_lock_sched_notrace(void)
832 {
833         preempt_disable_notrace();
834         __acquire(RCU_SCHED);
835 }
836
837 /**
838  * rcu_read_unlock_sched() - marks the end of a RCU-classic critical section
839  *
840  * See rcu_read_lock_sched() for more information.
841  */
842 static inline void rcu_read_unlock_sched(void)
843 {
844         RCU_LOCKDEP_WARN(!rcu_is_watching(),
845                          "rcu_read_unlock_sched() used illegally while idle");
846         rcu_lock_release(&rcu_sched_lock_map);
847         __release(RCU_SCHED);
848         preempt_enable();
849 }
850
851 /* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */
852 static inline notrace void rcu_read_unlock_sched_notrace(void)
853 {
854         __release(RCU_SCHED);
855         preempt_enable_notrace();
856 }
857
858 /**
859  * RCU_INIT_POINTER() - initialize an RCU protected pointer
860  * @p: The pointer to be initialized.
861  * @v: The value to initialized the pointer to.
862  *
863  * Initialize an RCU-protected pointer in special cases where readers
864  * do not need ordering constraints on the CPU or the compiler.  These
865  * special cases are:
866  *
867  * 1.   This use of RCU_INIT_POINTER() is NULLing out the pointer *or*
868  * 2.   The caller has taken whatever steps are required to prevent
869  *      RCU readers from concurrently accessing this pointer *or*
870  * 3.   The referenced data structure has already been exposed to
871  *      readers either at compile time or via rcu_assign_pointer() *and*
872  *
873  *      a.      You have not made *any* reader-visible changes to
874  *              this structure since then *or*
875  *      b.      It is OK for readers accessing this structure from its
876  *              new location to see the old state of the structure.  (For
877  *              example, the changes were to statistical counters or to
878  *              other state where exact synchronization is not required.)
879  *
880  * Failure to follow these rules governing use of RCU_INIT_POINTER() will
881  * result in impossible-to-diagnose memory corruption.  As in the structures
882  * will look OK in crash dumps, but any concurrent RCU readers might
883  * see pre-initialized values of the referenced data structure.  So
884  * please be very careful how you use RCU_INIT_POINTER()!!!
885  *
886  * If you are creating an RCU-protected linked structure that is accessed
887  * by a single external-to-structure RCU-protected pointer, then you may
888  * use RCU_INIT_POINTER() to initialize the internal RCU-protected
889  * pointers, but you must use rcu_assign_pointer() to initialize the
890  * external-to-structure pointer *after* you have completely initialized
891  * the reader-accessible portions of the linked structure.
892  *
893  * Note that unlike rcu_assign_pointer(), RCU_INIT_POINTER() provides no
894  * ordering guarantees for either the CPU or the compiler.
895  */
896 #define RCU_INIT_POINTER(p, v) \
897         do { \
898                 rcu_check_sparse(p, __rcu); \
899                 WRITE_ONCE(p, RCU_INITIALIZER(v)); \
900         } while (0)
901
902 /**
903  * RCU_POINTER_INITIALIZER() - statically initialize an RCU protected pointer
904  * @p: The pointer to be initialized.
905  * @v: The value to initialized the pointer to.
906  *
907  * GCC-style initialization for an RCU-protected pointer in a structure field.
908  */
909 #define RCU_POINTER_INITIALIZER(p, v) \
910                 .p = RCU_INITIALIZER(v)
911
912 /*
913  * Does the specified offset indicate that the corresponding rcu_head
914  * structure can be handled by kvfree_rcu()?
915  */
916 #define __is_kvfree_rcu_offset(offset) ((offset) < 4096)
917
918 /*
919  * Helper macro for kfree_rcu() to prevent argument-expansion eyestrain.
920  */
921 #define __kvfree_rcu(head, offset) \
922         do { \
923                 BUILD_BUG_ON(!__is_kvfree_rcu_offset(offset)); \
924                 kvfree_call_rcu(head, (rcu_callback_t)(unsigned long)(offset)); \
925         } while (0)
926
927 /**
928  * kfree_rcu() - kfree an object after a grace period.
929  * @ptr:        pointer to kfree
930  * @rhf:        the name of the struct rcu_head within the type of @ptr.
931  *
932  * Many rcu callbacks functions just call kfree() on the base structure.
933  * These functions are trivial, but their size adds up, and furthermore
934  * when they are used in a kernel module, that module must invoke the
935  * high-latency rcu_barrier() function at module-unload time.
936  *
937  * The kfree_rcu() function handles this issue.  Rather than encoding a
938  * function address in the embedded rcu_head structure, kfree_rcu() instead
939  * encodes the offset of the rcu_head structure within the base structure.
940  * Because the functions are not allowed in the low-order 4096 bytes of
941  * kernel virtual memory, offsets up to 4095 bytes can be accommodated.
942  * If the offset is larger than 4095 bytes, a compile-time error will
943  * be generated in __kvfree_rcu(). If this error is triggered, you can
944  * either fall back to use of call_rcu() or rearrange the structure to
945  * position the rcu_head structure into the first 4096 bytes.
946  *
947  * Note that the allowable offset might decrease in the future, for example,
948  * to allow something like kmem_cache_free_rcu().
949  *
950  * The BUILD_BUG_ON check must not involve any function calls, hence the
951  * checks are done in macros here.
952  */
953 #define kfree_rcu(ptr, rhf)                                             \
954 do {                                                                    \
955         typeof (ptr) ___p = (ptr);                                      \
956                                                                         \
957         if (___p)                                                       \
958                 __kvfree_rcu(&((___p)->rhf), offsetof(typeof(*(ptr)), rhf)); \
959 } while (0)
960
961 /**
962  * kvfree_rcu() - kvfree an object after a grace period.
963  *
964  * This macro consists of one or two arguments and it is
965  * based on whether an object is head-less or not. If it
966  * has a head then a semantic stays the same as it used
967  * to be before:
968  *
969  *     kvfree_rcu(ptr, rhf);
970  *
971  * where @ptr is a pointer to kvfree(), @rhf is the name
972  * of the rcu_head structure within the type of @ptr.
973  *
974  * When it comes to head-less variant, only one argument
975  * is passed and that is just a pointer which has to be
976  * freed after a grace period. Therefore the semantic is
977  *
978  *     kvfree_rcu(ptr);
979  *
980  * where @ptr is a pointer to kvfree().
981  *
982  * Please note, head-less way of freeing is permitted to
983  * use from a context that has to follow might_sleep()
984  * annotation. Otherwise, please switch and embed the
985  * rcu_head structure within the type of @ptr.
986  */
987 #define kvfree_rcu(...) KVFREE_GET_MACRO(__VA_ARGS__,           \
988         kvfree_rcu_arg_2, kvfree_rcu_arg_1)(__VA_ARGS__)
989
990 #define KVFREE_GET_MACRO(_1, _2, NAME, ...) NAME
991 #define kvfree_rcu_arg_2(ptr, rhf) kfree_rcu(ptr, rhf)
992 #define kvfree_rcu_arg_1(ptr)                                   \
993 do {                                                            \
994         typeof(ptr) ___p = (ptr);                               \
995                                                                 \
996         if (___p)                                               \
997                 kvfree_call_rcu(NULL, (rcu_callback_t) (___p)); \
998 } while (0)
999
1000 /*
1001  * Place this after a lock-acquisition primitive to guarantee that
1002  * an UNLOCK+LOCK pair acts as a full barrier.  This guarantee applies
1003  * if the UNLOCK and LOCK are executed by the same CPU or if the
1004  * UNLOCK and LOCK operate on the same lock variable.
1005  */
1006 #ifdef CONFIG_ARCH_WEAK_RELEASE_ACQUIRE
1007 #define smp_mb__after_unlock_lock()     smp_mb()  /* Full ordering for lock. */
1008 #else /* #ifdef CONFIG_ARCH_WEAK_RELEASE_ACQUIRE */
1009 #define smp_mb__after_unlock_lock()     do { } while (0)
1010 #endif /* #else #ifdef CONFIG_ARCH_WEAK_RELEASE_ACQUIRE */
1011
1012
1013 /* Has the specified rcu_head structure been handed to call_rcu()? */
1014
1015 /**
1016  * rcu_head_init - Initialize rcu_head for rcu_head_after_call_rcu()
1017  * @rhp: The rcu_head structure to initialize.
1018  *
1019  * If you intend to invoke rcu_head_after_call_rcu() to test whether a
1020  * given rcu_head structure has already been passed to call_rcu(), then
1021  * you must also invoke this rcu_head_init() function on it just after
1022  * allocating that structure.  Calls to this function must not race with
1023  * calls to call_rcu(), rcu_head_after_call_rcu(), or callback invocation.
1024  */
1025 static inline void rcu_head_init(struct rcu_head *rhp)
1026 {
1027         rhp->func = (rcu_callback_t)~0L;
1028 }
1029
1030 /**
1031  * rcu_head_after_call_rcu() - Has this rcu_head been passed to call_rcu()?
1032  * @rhp: The rcu_head structure to test.
1033  * @f: The function passed to call_rcu() along with @rhp.
1034  *
1035  * Returns @true if the @rhp has been passed to call_rcu() with @func,
1036  * and @false otherwise.  Emits a warning in any other case, including
1037  * the case where @rhp has already been invoked after a grace period.
1038  * Calls to this function must not race with callback invocation.  One way
1039  * to avoid such races is to enclose the call to rcu_head_after_call_rcu()
1040  * in an RCU read-side critical section that includes a read-side fetch
1041  * of the pointer to the structure containing @rhp.
1042  */
1043 static inline bool
1044 rcu_head_after_call_rcu(struct rcu_head *rhp, rcu_callback_t f)
1045 {
1046         rcu_callback_t func = READ_ONCE(rhp->func);
1047
1048         if (func == f)
1049                 return true;
1050         WARN_ON_ONCE(func != (rcu_callback_t)~0L);
1051         return false;
1052 }
1053
1054 /* kernel/ksysfs.c definitions */
1055 extern int rcu_expedited;
1056 extern int rcu_normal;
1057
1058 #endif /* __LINUX_RCUPDATE_H */