xref: /linux/include/linux/preempt.h (revision c8990f3179e5636832fc22e6a262de5d50c797e3)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __LINUX_PREEMPT_H
3 #define __LINUX_PREEMPT_H
4 
5 /*
6  * include/linux/preempt.h - macros for accessing and manipulating
7  * preempt_count (used for kernel preemption, interrupt count, etc.)
8  */
9 
10 #include <linux/linkage.h>
11 #include <linux/cleanup.h>
12 #include <linux/types.h>
13 
14 /*
15  * We put the hardirq and softirq counter into the preemption
16  * counter. The bitmask has the following meaning:
17  *
18  * - bits 0-7 are the preemption count (max preemption depth: 256)
19  * - bits 8-15 are the softirq count (max # of softirqs: 256)
20  * - bits 16-23 are the hardirq disable count (max # of hardirq disable: 256)
21  * - bits 24-27 are the hardirq count (max # of hardirqs: 16)
22  * - bit 28 is the NMI flag (no nesting count, tracked separately)
23  *
24  * The hardirq count could in theory be the same as the number of
25  * interrupts in the system, but we run all interrupt handlers with
26  * interrupts disabled, so we cannot have nesting interrupts. Though
27  * there are a few palaeontologic drivers which reenable interrupts in
28  * the handler, so we need more than one bit here.
29  *
30  * NMI nesting depth is tracked in a separate per-CPU variable
31  * (nmi_nesting) to save bits in preempt_count.
32  *
33  *         PREEMPT_MASK:	0x000000ff
34  *         SOFTIRQ_MASK:	0x0000ff00
35  * HARDIRQ_DISABLE_MASK:	0x00ff0000
36  *         HARDIRQ_MASK:	0x0f000000
37  *
38  * When HAS_SEPARATE_PREEMPT_RESCHED_BITS=y, PREEMPT_NEED_RESCHED is put in a
39  * separate word and that allows 64bit load-store architectures to 'set'
40  * PREEMPT_NEED_RESCHED without messing up the otherwise symmetric
41  * modifications used on preempt_count and still load the whole thing
42  * (single-copy) atomically, without having to resort to full atomic
43  * operations.
44  *
45  * Because of the above, NMI_MASK bits are different depending on
46  * HAS_SEPARATE_PREEMPT_RESCHED_BITS:
47  *
48  * - HAS_SEPARATE_PREEMPT_RESCHED_BITS=n:
49  *
50  *             NMI_MASK:	0x10000000
51  * PREEMPT_NEED_RESCHED:	0x80000000
52  *
53  * - HAS_SEPARATE_PREEMPT_RESCHED_BITS=y:
54  *             NMI_MASK:	0xf0000000
55  * (PREEMPT_NEED_RESCHED is in a different word)
56  */
57 #define PREEMPT_BITS	8
58 #define SOFTIRQ_BITS	8
59 #define HARDIRQ_DISABLE_BITS	8
60 #define HARDIRQ_BITS	4
61 #define NMI_BITS	(1 + 3*IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS))
62 
63 #define PREEMPT_SHIFT	0
64 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
65 #define HARDIRQ_DISABLE_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
66 #define HARDIRQ_SHIFT	(HARDIRQ_DISABLE_SHIFT + HARDIRQ_DISABLE_BITS)
67 #define NMI_SHIFT	(HARDIRQ_SHIFT + HARDIRQ_BITS)
68 
69 #define __IRQ_MASK(x)	((1UL << (x))-1)
70 
71 #define PREEMPT_MASK	(__IRQ_MASK(PREEMPT_BITS) << PREEMPT_SHIFT)
72 #define SOFTIRQ_MASK	(__IRQ_MASK(SOFTIRQ_BITS) << SOFTIRQ_SHIFT)
73 #define HARDIRQ_DISABLE_MASK	(__IRQ_MASK(HARDIRQ_DISABLE_BITS) << HARDIRQ_DISABLE_SHIFT)
74 #define HARDIRQ_MASK	(__IRQ_MASK(HARDIRQ_BITS) << HARDIRQ_SHIFT)
75 #define NMI_MASK	(__IRQ_MASK(NMI_BITS)     << NMI_SHIFT)
76 
77 #define PREEMPT_OFFSET	(1UL << PREEMPT_SHIFT)
78 #define SOFTIRQ_OFFSET	(1UL << SOFTIRQ_SHIFT)
79 #define HARDIRQ_DISABLE_OFFSET	(1UL << HARDIRQ_DISABLE_SHIFT)
80 #define HARDIRQ_OFFSET	(1UL << HARDIRQ_SHIFT)
81 #define NMI_OFFSET	(1UL << NMI_SHIFT)
82 
83 #define SOFTIRQ_DISABLE_OFFSET	(2 * SOFTIRQ_OFFSET)
84 
85 #define PREEMPT_DISABLED	(PREEMPT_DISABLE_OFFSET + PREEMPT_ENABLED)
86 
87 /*
88  * Disable preemption until the scheduler is running -- use an unconditional
89  * value so that it also works on !PREEMPT_COUNT kernels.
90  *
91  * Reset by start_kernel()->sched_init()->init_idle()->init_idle_preempt_count().
92  */
93 #define INIT_PREEMPT_COUNT	PREEMPT_OFFSET
94 
95 /*
96  * Initial preempt_count value; reflects the preempt_count schedule invariant
97  * which states that during context switches:
98  *
99  *    preempt_count() == 2*PREEMPT_DISABLE_OFFSET
100  *
101  * Note: PREEMPT_DISABLE_OFFSET is 0 for !PREEMPT_COUNT kernels.
102  * Note: See finish_task_switch().
103  */
104 #define FORK_PREEMPT_COUNT	(2*PREEMPT_DISABLE_OFFSET + PREEMPT_ENABLED)
105 
106 /* preempt_count() and related functions, depends on PREEMPT_NEED_RESCHED */
107 #include <asm/preempt.h>
108 
109 /**
110  * interrupt_context_level - return interrupt context level
111  *
112  * Returns the current interrupt context level.
113  *  0 - normal context
114  *  1 - softirq context
115  *  2 - hardirq context
116  *  3 - NMI context
117  */
interrupt_context_level(void)118 static __always_inline unsigned char interrupt_context_level(void)
119 {
120 	unsigned long pc = preempt_count();
121 	unsigned char level = 0;
122 
123 	level += !!(pc & (NMI_MASK));
124 	level += !!(pc & (NMI_MASK | HARDIRQ_MASK));
125 	level += !!(pc & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_OFFSET));
126 
127 	return level;
128 }
129 
130 /*
131  * These macro definitions avoid redundant invocations of preempt_count()
132  * because such invocations would result in redundant loads given that
133  * preempt_count() is commonly implemented with READ_ONCE().
134  */
135 
136 #define nmi_count()		(preempt_count() & NMI_MASK)
137 #define hardirq_count()		(preempt_count() & HARDIRQ_MASK)
138 #ifdef CONFIG_PREEMPT_RT
139 # define softirq_count()	(current->softirq_disable_cnt & SOFTIRQ_MASK)
140 # define irq_count()		((preempt_count() & (NMI_MASK | HARDIRQ_MASK)) | softirq_count())
141 #else
142 # define softirq_count()	(preempt_count() & SOFTIRQ_MASK)
143 # define irq_count()		(preempt_count() & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_MASK))
144 #endif
145 
146 /*
147  * Macros to retrieve the current execution context:
148  *
149  * in_nmi()		- We're in NMI context
150  * in_hardirq()		- We're in hard IRQ context
151  * in_serving_softirq()	- We're in softirq context
152  * in_task()		- We're in task context
153  */
154 #define in_nmi()		(nmi_count())
155 #define in_hardirq()		(hardirq_count())
156 #define in_serving_softirq()	(softirq_count() & SOFTIRQ_OFFSET)
157 #ifdef CONFIG_PREEMPT_RT
158 # define in_task()		(!((preempt_count() & (NMI_MASK | HARDIRQ_MASK)) | in_serving_softirq()))
159 #else
160 # define in_task()		(!(preempt_count() & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_OFFSET)))
161 #endif
162 
163 /*
164  * The following macros are deprecated and should not be used in new code:
165  * in_softirq()   - We have BH disabled, or are processing softirqs
166  * in_interrupt() - We're in NMI,IRQ,SoftIRQ context or have BH disabled
167  */
168 #define in_softirq()		(softirq_count())
169 #define in_interrupt()		(irq_count())
170 
171 /*
172  * The preempt_count offset after preempt_disable();
173  */
174 #if defined(CONFIG_PREEMPT_COUNT)
175 # define PREEMPT_DISABLE_OFFSET	PREEMPT_OFFSET
176 #else
177 # define PREEMPT_DISABLE_OFFSET	0
178 #endif
179 
180 /*
181  * The preempt_count offset after spin_lock()
182  */
183 #if !defined(CONFIG_PREEMPT_RT)
184 #define PREEMPT_LOCK_OFFSET		PREEMPT_DISABLE_OFFSET
185 #else
186 /* Locks on RT do not disable preemption */
187 #define PREEMPT_LOCK_OFFSET		0
188 #endif
189 
190 /*
191  * The preempt_count offset needed for things like:
192  *
193  *  spin_lock_bh()
194  *
195  * Which need to disable both preemption (CONFIG_PREEMPT_COUNT) and
196  * softirqs, such that unlock sequences of:
197  *
198  *  spin_unlock();
199  *  local_bh_enable();
200  *
201  * Work as expected.
202  */
203 #define SOFTIRQ_LOCK_OFFSET (SOFTIRQ_DISABLE_OFFSET + PREEMPT_LOCK_OFFSET)
204 
205 /*
206  * Are we running in atomic context?  WARNING: this macro cannot
207  * always detect atomic context; in particular, it cannot know about
208  * held spinlocks in non-preemptible kernels.  Thus it should not be
209  * used in the general case to determine whether sleeping is possible.
210  * Do not use in_atomic() in driver code.
211  */
212 #define in_atomic()	(preempt_count() != 0)
213 
214 /*
215  * Check whether we were atomic before we did preempt_disable():
216  * (used by the scheduler)
217  */
218 #define in_atomic_preempt_off() (preempt_count() != PREEMPT_DISABLE_OFFSET)
219 
220 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
221 extern void preempt_count_add(int val);
222 extern void preempt_count_sub(int val);
223 #define preempt_count_dec_and_test() \
224 	({ preempt_count_sub(1); should_resched(0); })
225 #else
226 #define preempt_count_add(val)	__preempt_count_add(val)
227 #define preempt_count_sub(val)	__preempt_count_sub(val)
228 #define preempt_count_dec_and_test() __preempt_count_dec_and_test()
229 #endif
230 
231 #define __preempt_count_inc() __preempt_count_add(1)
232 #define __preempt_count_dec() __preempt_count_sub(1)
233 
234 #define preempt_count_inc() preempt_count_add(1)
235 #define preempt_count_dec() preempt_count_sub(1)
236 
237 #ifdef CONFIG_PREEMPT_COUNT
238 
239 #define preempt_disable() \
240 do { \
241 	preempt_count_inc(); \
242 	barrier(); \
243 } while (0)
244 
245 #define sched_preempt_enable_no_resched() \
246 do { \
247 	barrier(); \
248 	preempt_count_dec(); \
249 } while (0)
250 
251 #define preempt_enable_no_resched() sched_preempt_enable_no_resched()
252 
253 #define preemptible()	(preempt_count() == 0 && !irqs_disabled())
254 
255 #ifdef CONFIG_PREEMPTION
256 #define preempt_enable() \
257 do { \
258 	barrier(); \
259 	if (unlikely(preempt_count_dec_and_test())) \
260 		__preempt_schedule(); \
261 } while (0)
262 
263 #define preempt_enable_notrace() \
264 do { \
265 	barrier(); \
266 	if (unlikely(__preempt_count_dec_and_test())) \
267 		__preempt_schedule_notrace(); \
268 } while (0)
269 
270 #define preempt_check_resched() \
271 do { \
272 	if (should_resched(0)) \
273 		__preempt_schedule(); \
274 } while (0)
275 
276 #else /* !CONFIG_PREEMPTION */
277 #define preempt_enable() \
278 do { \
279 	barrier(); \
280 	preempt_count_dec(); \
281 } while (0)
282 
283 #define preempt_enable_notrace() \
284 do { \
285 	barrier(); \
286 	__preempt_count_dec(); \
287 } while (0)
288 
289 #define preempt_check_resched() do { } while (0)
290 #endif /* CONFIG_PREEMPTION */
291 
292 #define preempt_disable_notrace() \
293 do { \
294 	__preempt_count_inc(); \
295 	barrier(); \
296 } while (0)
297 
298 #define preempt_enable_no_resched_notrace() \
299 do { \
300 	barrier(); \
301 	__preempt_count_dec(); \
302 } while (0)
303 
304 #else /* !CONFIG_PREEMPT_COUNT */
305 
306 /*
307  * Even if we don't have any preemption, we need preempt disable/enable
308  * to be barriers, so that we don't have things like get_user/put_user
309  * that can cause faults and scheduling migrate into our preempt-protected
310  * region.
311  */
312 #define preempt_disable()			barrier()
313 #define sched_preempt_enable_no_resched()	barrier()
314 #define preempt_enable_no_resched()		barrier()
315 #define preempt_enable()			barrier()
316 #define preempt_check_resched()			do { } while (0)
317 
318 #define preempt_disable_notrace()		barrier()
319 #define preempt_enable_no_resched_notrace()	barrier()
320 #define preempt_enable_notrace()		barrier()
321 #define preemptible()				0
322 
323 #endif /* CONFIG_PREEMPT_COUNT */
324 
325 #ifdef MODULE
326 /*
327  * Modules have no business playing preemption tricks.
328  */
329 #undef sched_preempt_enable_no_resched
330 #undef preempt_enable_no_resched
331 #undef preempt_enable_no_resched_notrace
332 #undef preempt_check_resched
333 #endif
334 
335 #define preempt_set_need_resched() \
336 do { \
337 	set_preempt_need_resched(); \
338 } while (0)
339 #define preempt_fold_need_resched() \
340 do { \
341 	if (tif_need_resched()) \
342 		set_preempt_need_resched(); \
343 } while (0)
344 
345 #ifdef CONFIG_PREEMPT_NOTIFIERS
346 
347 struct preempt_notifier;
348 struct task_struct;
349 
350 /**
351  * preempt_ops - notifiers called when a task is preempted and rescheduled
352  * @sched_in: we're about to be rescheduled:
353  *    notifier: struct preempt_notifier for the task being scheduled
354  *    cpu:  cpu we're scheduled on
355  * @sched_out: we've just been preempted
356  *    notifier: struct preempt_notifier for the task being preempted
357  *    next: the task that's kicking us out
358  *
359  * Please note that sched_in and out are called under different
360  * contexts.  sched_out is called with rq lock held and irq disabled
361  * while sched_in is called without rq lock and irq enabled.  This
362  * difference is intentional and depended upon by its users.
363  */
364 struct preempt_ops {
365 	void (*sched_in)(struct preempt_notifier *notifier, int cpu);
366 	void (*sched_out)(struct preempt_notifier *notifier,
367 			  struct task_struct *next);
368 };
369 
370 /**
371  * preempt_notifier - key for installing preemption notifiers
372  * @link: internal use
373  * @ops: defines the notifier functions to be called
374  *
375  * Usually used in conjunction with container_of().
376  */
377 struct preempt_notifier {
378 	struct hlist_node link;
379 	struct preempt_ops *ops;
380 };
381 
382 void preempt_notifier_inc(void);
383 void preempt_notifier_dec(void);
384 void preempt_notifier_register(struct preempt_notifier *notifier);
385 void preempt_notifier_unregister(struct preempt_notifier *notifier);
386 
preempt_notifier_init(struct preempt_notifier * notifier,struct preempt_ops * ops)387 static inline void preempt_notifier_init(struct preempt_notifier *notifier,
388 				     struct preempt_ops *ops)
389 {
390 	/* INIT_HLIST_NODE() open coded, to avoid dependency on list.h */
391 	notifier->link.next = NULL;
392 	notifier->link.pprev = NULL;
393 	notifier->ops = ops;
394 }
395 
396 #endif
397 
398 /*
399  * Migrate-Disable and why it is undesired.
400  *
401  * When a preempted task becomes eligible to run under the ideal model (IOW it
402  * becomes one of the M highest priority tasks), it might still have to wait
403  * for the preemptee's migrate_disable() section to complete. Thereby suffering
404  * a reduction in bandwidth in the exact duration of the migrate_disable()
405  * section.
406  *
407  * Per this argument, the change from preempt_disable() to migrate_disable()
408  * gets us:
409  *
410  * - a higher priority tasks gains reduced wake-up latency; with preempt_disable()
411  *   it would have had to wait for the lower priority task.
412  *
413  * - a lower priority tasks; which under preempt_disable() could've instantly
414  *   migrated away when another CPU becomes available, is now constrained
415  *   by the ability to push the higher priority task away, which might itself be
416  *   in a migrate_disable() section, reducing its available bandwidth.
417  *
418  * IOW it trades latency / moves the interference term, but it stays in the
419  * system, and as long as it remains unbounded, the system is not fully
420  * deterministic.
421  *
422  *
423  * The reason we have it anyway.
424  *
425  * PREEMPT_RT breaks a number of assumptions traditionally held. By forcing a
426  * number of primitives into becoming preemptible, they would also allow
427  * migration. This turns out to break a bunch of per-cpu usage. To this end,
428  * all these primitives employ migrate_disable() to restore this implicit
429  * assumption.
430  *
431  * This is a 'temporary' work-around at best. The correct solution is getting
432  * rid of the above assumptions and reworking the code to employ explicit
433  * per-cpu locking or short preempt-disable regions.
434  *
435  * The end goal must be to get rid of migrate_disable(), alternatively we need
436  * a schedulability theory that does not depend on arbitrary migration.
437  *
438  *
439  * Notes on the implementation.
440  *
441  * The implementation is particularly tricky since existing code patterns
442  * dictate neither migrate_disable() nor migrate_enable() is allowed to block.
443  * This means that it cannot use cpus_read_lock() to serialize against hotplug,
444  * nor can it easily migrate itself into a pending affinity mask change on
445  * migrate_enable().
446  *
447  *
448  * Note: even non-work-conserving schedulers like semi-partitioned depends on
449  *       migration, so migrate_disable() is not only a problem for
450  *       work-conserving schedulers.
451  *
452  */
453 
454 /**
455  * preempt_disable_nested - Disable preemption inside a normally preempt disabled section
456  *
457  * Use for code which requires preemption protection inside a critical
458  * section which has preemption disabled implicitly on non-PREEMPT_RT
459  * enabled kernels, by e.g.:
460  *  - holding a spinlock/rwlock
461  *  - soft interrupt context
462  *  - regular interrupt handlers
463  *
464  * On PREEMPT_RT enabled kernels spinlock/rwlock held sections, soft
465  * interrupt context and regular interrupt handlers are preemptible and
466  * only prevent migration. preempt_disable_nested() ensures that preemption
467  * is disabled for cases which require CPU local serialization even on
468  * PREEMPT_RT. For non-PREEMPT_RT kernels this is a NOP.
469  *
470  * The use cases are code sequences which are not serialized by a
471  * particular lock instance, e.g.:
472  *  - seqcount write side critical sections where the seqcount is not
473  *    associated to a particular lock and therefore the automatic
474  *    protection mechanism does not work. This prevents a live lock
475  *    against a preempting high priority reader.
476  *  - RMW per CPU variable updates like vmstat.
477  */
478 /* Macro to avoid header recursion hell vs. lockdep */
479 #define preempt_disable_nested()				\
480 do {								\
481 	if (IS_ENABLED(CONFIG_PREEMPT_RT))			\
482 		preempt_disable();				\
483 	else							\
484 		lockdep_assert_preemption_disabled();		\
485 } while (0)
486 
487 /**
488  * preempt_enable_nested - Undo the effect of preempt_disable_nested()
489  */
preempt_enable_nested(void)490 static __always_inline void preempt_enable_nested(void)
491 {
492 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
493 		preempt_enable();
494 }
495 
496 DEFINE_LOCK_GUARD_0(preempt, preempt_disable(), preempt_enable())
497 DEFINE_LOCK_GUARD_0(preempt_notrace, preempt_disable_notrace(), preempt_enable_notrace())
498 
499 #ifdef CONFIG_PREEMPT_DYNAMIC
500 
501 extern bool preempt_model_none(void);
502 extern bool preempt_model_voluntary(void);
503 extern bool preempt_model_full(void);
504 extern bool preempt_model_lazy(void);
505 
506 #else
507 
508 static inline bool preempt_model_none(void)
509 {
510 	return IS_ENABLED(CONFIG_PREEMPT_NONE);
511 }
512 static inline bool preempt_model_voluntary(void)
513 {
514 	return IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY);
515 }
516 static inline bool preempt_model_full(void)
517 {
518 	return IS_ENABLED(CONFIG_PREEMPT);
519 }
520 
521 static inline bool preempt_model_lazy(void)
522 {
523 	return IS_ENABLED(CONFIG_PREEMPT_LAZY);
524 }
525 
526 #endif
527 
preempt_model_rt(void)528 static inline bool preempt_model_rt(void)
529 {
530 	return IS_ENABLED(CONFIG_PREEMPT_RT);
531 }
532 
533 extern const char *preempt_model_str(void);
534 
535 /*
536  * Does the preemption model allow non-cooperative preemption?
537  *
538  * For !CONFIG_PREEMPT_DYNAMIC kernels this is an exact match with
539  * CONFIG_PREEMPTION; for CONFIG_PREEMPT_DYNAMIC this doesn't work as the
540  * kernel is *built* with CONFIG_PREEMPTION=y but may run with e.g. the
541  * PREEMPT_NONE model.
542  */
preempt_model_preemptible(void)543 static inline bool preempt_model_preemptible(void)
544 {
545 	return preempt_model_full() || preempt_model_lazy() || preempt_model_rt();
546 }
547 
548 #endif /* __LINUX_PREEMPT_H */
549