xref: /linux-6.15/kernel/context_tracking.c (revision 3864caaf)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Context tracking: Probe on high level context boundaries such as kernel
4  * and userspace. This includes syscalls and exceptions entry/exit.
5  *
6  * This is used by RCU to remove its dependency on the timer tick while a CPU
7  * runs in userspace.
8  *
9  *  Started by Frederic Weisbecker:
10  *
11  * Copyright (C) 2012 Red Hat, Inc., Frederic Weisbecker <[email protected]>
12  *
13  * Many thanks to Gilad Ben-Yossef, Paul McKenney, Ingo Molnar, Andrew Morton,
14  * Steven Rostedt, Peter Zijlstra for suggestions and improvements.
15  *
16  */
17 
18 #include <linux/context_tracking.h>
19 #include <linux/rcupdate.h>
20 #include <linux/sched.h>
21 #include <linux/hardirq.h>
22 #include <linux/export.h>
23 #include <linux/kprobes.h>
24 
25 
26 #ifdef CONFIG_CONTEXT_TRACKING_IDLE
27 noinstr void ct_idle_enter(void)
28 {
29 	rcu_idle_enter();
30 }
31 EXPORT_SYMBOL_GPL(ct_idle_enter);
32 
33 void ct_idle_exit(void)
34 {
35 	rcu_idle_exit();
36 }
37 EXPORT_SYMBOL_GPL(ct_idle_exit);
38 
39 /**
40  * ct_irq_enter - inform RCU that current CPU is entering irq away from idle
41  *
42  * Enter an interrupt handler, which might possibly result in exiting
43  * idle mode, in other words, entering the mode in which read-side critical
44  * sections can occur.  The caller must have disabled interrupts.
45  *
46  * Note that the Linux kernel is fully capable of entering an interrupt
47  * handler that it never exits, for example when doing upcalls to user mode!
48  * This code assumes that the idle loop never does upcalls to user mode.
49  * If your architecture's idle loop does do upcalls to user mode (or does
50  * anything else that results in unbalanced calls to the irq_enter() and
51  * irq_exit() functions), RCU will give you what you deserve, good and hard.
52  * But very infrequently and irreproducibly.
53  *
54  * Use things like work queues to work around this limitation.
55  *
56  * You have been warned.
57  *
58  * If you add or remove a call to ct_irq_enter(), be sure to test with
59  * CONFIG_RCU_EQS_DEBUG=y.
60  */
61 noinstr void ct_irq_enter(void)
62 {
63 	lockdep_assert_irqs_disabled();
64 	ct_nmi_enter();
65 }
66 
67 /**
68  * ct_irq_exit - inform RCU that current CPU is exiting irq towards idle
69  *
70  * Exit from an interrupt handler, which might possibly result in entering
71  * idle mode, in other words, leaving the mode in which read-side critical
72  * sections can occur.  The caller must have disabled interrupts.
73  *
74  * This code assumes that the idle loop never does anything that might
75  * result in unbalanced calls to irq_enter() and irq_exit().  If your
76  * architecture's idle loop violates this assumption, RCU will give you what
77  * you deserve, good and hard.  But very infrequently and irreproducibly.
78  *
79  * Use things like work queues to work around this limitation.
80  *
81  * You have been warned.
82  *
83  * If you add or remove a call to ct_irq_exit(), be sure to test with
84  * CONFIG_RCU_EQS_DEBUG=y.
85  */
86 noinstr void ct_irq_exit(void)
87 {
88 	lockdep_assert_irqs_disabled();
89 	ct_nmi_exit();
90 }
91 
92 /*
93  * Wrapper for ct_irq_enter() where interrupts are enabled.
94  *
95  * If you add or remove a call to ct_irq_enter_irqson(), be sure to test
96  * with CONFIG_RCU_EQS_DEBUG=y.
97  */
98 void ct_irq_enter_irqson(void)
99 {
100 	unsigned long flags;
101 
102 	local_irq_save(flags);
103 	ct_irq_enter();
104 	local_irq_restore(flags);
105 }
106 
107 /*
108  * Wrapper for ct_irq_exit() where interrupts are enabled.
109  *
110  * If you add or remove a call to ct_irq_exit_irqson(), be sure to test
111  * with CONFIG_RCU_EQS_DEBUG=y.
112  */
113 void ct_irq_exit_irqson(void)
114 {
115 	unsigned long flags;
116 
117 	local_irq_save(flags);
118 	ct_irq_exit();
119 	local_irq_restore(flags);
120 }
121 
122 noinstr void ct_nmi_enter(void)
123 {
124 	rcu_nmi_enter();
125 }
126 
127 noinstr void ct_nmi_exit(void)
128 {
129 	rcu_nmi_exit();
130 }
131 #endif /* #ifdef CONFIG_CONTEXT_TRACKING_IDLE */
132 
133 #ifdef CONFIG_CONTEXT_TRACKING_USER
134 
135 #define CREATE_TRACE_POINTS
136 #include <trace/events/context_tracking.h>
137 
138 DEFINE_STATIC_KEY_FALSE(context_tracking_key);
139 EXPORT_SYMBOL_GPL(context_tracking_key);
140 
141 DEFINE_PER_CPU(struct context_tracking, context_tracking);
142 EXPORT_SYMBOL_GPL(context_tracking);
143 
144 static noinstr bool context_tracking_recursion_enter(void)
145 {
146 	int recursion;
147 
148 	recursion = __this_cpu_inc_return(context_tracking.recursion);
149 	if (recursion == 1)
150 		return true;
151 
152 	WARN_ONCE((recursion < 1), "Invalid context tracking recursion value %d\n", recursion);
153 	__this_cpu_dec(context_tracking.recursion);
154 
155 	return false;
156 }
157 
158 static __always_inline void context_tracking_recursion_exit(void)
159 {
160 	__this_cpu_dec(context_tracking.recursion);
161 }
162 
163 /**
164  * __ct_user_enter - Inform the context tracking that the CPU is going
165  *		     to enter user or guest space mode.
166  *
167  * This function must be called right before we switch from the kernel
168  * to user or guest space, when it's guaranteed the remaining kernel
169  * instructions to execute won't use any RCU read side critical section
170  * because this function sets RCU in extended quiescent state.
171  */
172 void noinstr __ct_user_enter(enum ctx_state state)
173 {
174 	/* Kernel threads aren't supposed to go to userspace */
175 	WARN_ON_ONCE(!current->mm);
176 
177 	if (!context_tracking_recursion_enter())
178 		return;
179 
180 	if ( __this_cpu_read(context_tracking.state) != state) {
181 		if (__this_cpu_read(context_tracking.active)) {
182 			/*
183 			 * At this stage, only low level arch entry code remains and
184 			 * then we'll run in userspace. We can assume there won't be
185 			 * any RCU read-side critical section until the next call to
186 			 * user_exit() or ct_irq_enter(). Let's remove RCU's dependency
187 			 * on the tick.
188 			 */
189 			if (state == CONTEXT_USER) {
190 				instrumentation_begin();
191 				trace_user_enter(0);
192 				vtime_user_enter(current);
193 				instrumentation_end();
194 			}
195 			rcu_user_enter();
196 		}
197 		/*
198 		 * Even if context tracking is disabled on this CPU, because it's outside
199 		 * the full dynticks mask for example, we still have to keep track of the
200 		 * context transitions and states to prevent inconsistency on those of
201 		 * other CPUs.
202 		 * If a task triggers an exception in userspace, sleep on the exception
203 		 * handler and then migrate to another CPU, that new CPU must know where
204 		 * the exception returns by the time we call exception_exit().
205 		 * This information can only be provided by the previous CPU when it called
206 		 * exception_enter().
207 		 * OTOH we can spare the calls to vtime and RCU when context_tracking.active
208 		 * is false because we know that CPU is not tickless.
209 		 */
210 		__this_cpu_write(context_tracking.state, state);
211 	}
212 	context_tracking_recursion_exit();
213 }
214 EXPORT_SYMBOL_GPL(__ct_user_enter);
215 
216 /*
217  * OBSOLETE:
218  * This function should be noinstr but the below local_irq_restore() is
219  * unsafe because it involves illegal RCU uses through tracing and lockdep.
220  * This is unlikely to be fixed as this function is obsolete. The preferred
221  * way is to call __context_tracking_enter() through user_enter_irqoff()
222  * or context_tracking_guest_enter(). It should be the arch entry code
223  * responsibility to call into context tracking with IRQs disabled.
224  */
225 void ct_user_enter(enum ctx_state state)
226 {
227 	unsigned long flags;
228 
229 	/*
230 	 * Some contexts may involve an exception occuring in an irq,
231 	 * leading to that nesting:
232 	 * ct_irq_enter() rcu_user_exit() rcu_user_exit() ct_irq_exit()
233 	 * This would mess up the dyntick_nesting count though. And rcu_irq_*()
234 	 * helpers are enough to protect RCU uses inside the exception. So
235 	 * just return immediately if we detect we are in an IRQ.
236 	 */
237 	if (in_interrupt())
238 		return;
239 
240 	local_irq_save(flags);
241 	__ct_user_enter(state);
242 	local_irq_restore(flags);
243 }
244 NOKPROBE_SYMBOL(ct_user_enter);
245 EXPORT_SYMBOL_GPL(ct_user_enter);
246 
247 /**
248  * user_enter_callable() - Unfortunate ASM callable version of user_enter() for
249  *			   archs that didn't manage to check the context tracking
250  *			   static key from low level code.
251  *
252  * This OBSOLETE function should be noinstr but it unsafely calls
253  * local_irq_restore(), involving illegal RCU uses through tracing and lockdep.
254  * This is unlikely to be fixed as this function is obsolete. The preferred
255  * way is to call user_enter_irqoff(). It should be the arch entry code
256  * responsibility to call into context tracking with IRQs disabled.
257  */
258 void user_enter_callable(void)
259 {
260 	user_enter();
261 }
262 NOKPROBE_SYMBOL(user_enter_callable);
263 
264 /**
265  * __ct_user_exit - Inform the context tracking that the CPU is
266  *		    exiting user or guest mode and entering the kernel.
267  *
268  * This function must be called after we entered the kernel from user or
269  * guest space before any use of RCU read side critical section. This
270  * potentially include any high level kernel code like syscalls, exceptions,
271  * signal handling, etc...
272  *
273  * This call supports re-entrancy. This way it can be called from any exception
274  * handler without needing to know if we came from userspace or not.
275  */
276 void noinstr __ct_user_exit(enum ctx_state state)
277 {
278 	if (!context_tracking_recursion_enter())
279 		return;
280 
281 	if (__this_cpu_read(context_tracking.state) == state) {
282 		if (__this_cpu_read(context_tracking.active)) {
283 			/*
284 			 * We are going to run code that may use RCU. Inform
285 			 * RCU core about that (ie: we may need the tick again).
286 			 */
287 			rcu_user_exit();
288 			if (state == CONTEXT_USER) {
289 				instrumentation_begin();
290 				vtime_user_exit(current);
291 				trace_user_exit(0);
292 				instrumentation_end();
293 			}
294 		}
295 		__this_cpu_write(context_tracking.state, CONTEXT_KERNEL);
296 	}
297 	context_tracking_recursion_exit();
298 }
299 EXPORT_SYMBOL_GPL(__ct_user_exit);
300 
301 /*
302  * OBSOLETE:
303  * This function should be noinstr but the below local_irq_save() is
304  * unsafe because it involves illegal RCU uses through tracing and lockdep.
305  * This is unlikely to be fixed as this function is obsolete. The preferred
306  * way is to call __context_tracking_exit() through user_exit_irqoff()
307  * or context_tracking_guest_exit(). It should be the arch entry code
308  * responsibility to call into context tracking with IRQs disabled.
309  */
310 void ct_user_exit(enum ctx_state state)
311 {
312 	unsigned long flags;
313 
314 	if (in_interrupt())
315 		return;
316 
317 	local_irq_save(flags);
318 	__ct_user_exit(state);
319 	local_irq_restore(flags);
320 }
321 NOKPROBE_SYMBOL(ct_user_exit);
322 EXPORT_SYMBOL_GPL(ct_user_exit);
323 
324 /**
325  * user_exit_callable() - Unfortunate ASM callable version of user_exit() for
326  *			  archs that didn't manage to check the context tracking
327  *			  static key from low level code.
328  *
329  * This OBSOLETE function should be noinstr but it unsafely calls local_irq_save(),
330  * involving illegal RCU uses through tracing and lockdep. This is unlikely
331  * to be fixed as this function is obsolete. The preferred way is to call
332  * user_exit_irqoff(). It should be the arch entry code responsibility to
333  * call into context tracking with IRQs disabled.
334  */
335 void user_exit_callable(void)
336 {
337 	user_exit();
338 }
339 NOKPROBE_SYMBOL(user_exit_callable);
340 
341 void __init ct_cpu_track_user(int cpu)
342 {
343 	static __initdata bool initialized = false;
344 
345 	if (!per_cpu(context_tracking.active, cpu)) {
346 		per_cpu(context_tracking.active, cpu) = true;
347 		static_branch_inc(&context_tracking_key);
348 	}
349 
350 	if (initialized)
351 		return;
352 
353 #ifdef CONFIG_HAVE_TIF_NOHZ
354 	/*
355 	 * Set TIF_NOHZ to init/0 and let it propagate to all tasks through fork
356 	 * This assumes that init is the only task at this early boot stage.
357 	 */
358 	set_tsk_thread_flag(&init_task, TIF_NOHZ);
359 #endif
360 	WARN_ON_ONCE(!tasklist_empty());
361 
362 	initialized = true;
363 }
364 
365 #ifdef CONFIG_CONTEXT_TRACKING_USER_FORCE
366 void __init context_tracking_init(void)
367 {
368 	int cpu;
369 
370 	for_each_possible_cpu(cpu)
371 		ct_cpu_track_user(cpu);
372 }
373 #endif
374 
375 #endif /* #ifdef CONFIG_CONTEXT_TRACKING_USER */
376