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