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