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