xref: /linux-6.15/include/linux/kernel.h (revision 66a5c40f)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * NOTE:
4  *
5  * This header has combined a lot of unrelated to each other stuff.
6  * The process of splitting its content is in progress while keeping
7  * backward compatibility. That's why it's highly recommended NOT to
8  * include this header inside another header file, especially under
9  * generic or architectural include/ directory.
10  */
11 #ifndef _LINUX_KERNEL_H
12 #define _LINUX_KERNEL_H
13 
14 #include <linux/stdarg.h>
15 #include <linux/align.h>
16 #include <linux/array_size.h>
17 #include <linux/limits.h>
18 #include <linux/linkage.h>
19 #include <linux/stddef.h>
20 #include <linux/types.h>
21 #include <linux/compiler.h>
22 #include <linux/container_of.h>
23 #include <linux/bitops.h>
24 #include <linux/hex.h>
25 #include <linux/kstrtox.h>
26 #include <linux/log2.h>
27 #include <linux/math.h>
28 #include <linux/minmax.h>
29 #include <linux/typecheck.h>
30 #include <linux/panic.h>
31 #include <linux/printk.h>
32 #include <linux/build_bug.h>
33 #include <linux/sprintf.h>
34 #include <linux/static_call_types.h>
35 #include <linux/instruction_pointer.h>
36 #include <asm/byteorder.h>
37 
38 #include <uapi/linux/kernel.h>
39 
40 #define STACK_MAGIC	0xdeadbeef
41 
42 /* generic data direction definitions */
43 #define READ			0
44 #define WRITE			1
45 
46 #define PTR_IF(cond, ptr)	((cond) ? (ptr) : NULL)
47 
48 #define u64_to_user_ptr(x) (		\
49 {					\
50 	typecheck(u64, (x));		\
51 	(void __user *)(uintptr_t)(x);	\
52 }					\
53 )
54 
55 /**
56  * upper_32_bits - return bits 32-63 of a number
57  * @n: the number we're accessing
58  *
59  * A basic shift-right of a 64- or 32-bit quantity.  Use this to suppress
60  * the "right shift count >= width of type" warning when that quantity is
61  * 32-bits.
62  */
63 #define upper_32_bits(n) ((u32)(((n) >> 16) >> 16))
64 
65 /**
66  * lower_32_bits - return bits 0-31 of a number
67  * @n: the number we're accessing
68  */
69 #define lower_32_bits(n) ((u32)((n) & 0xffffffff))
70 
71 /**
72  * upper_16_bits - return bits 16-31 of a number
73  * @n: the number we're accessing
74  */
75 #define upper_16_bits(n) ((u16)((n) >> 16))
76 
77 /**
78  * lower_16_bits - return bits 0-15 of a number
79  * @n: the number we're accessing
80  */
81 #define lower_16_bits(n) ((u16)((n) & 0xffff))
82 
83 struct completion;
84 struct user;
85 
86 #ifdef CONFIG_PREEMPT_VOLUNTARY_BUILD
87 
88 extern int __cond_resched(void);
89 # define might_resched() __cond_resched()
90 
91 #elif defined(CONFIG_PREEMPT_DYNAMIC) && defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
92 
93 extern int __cond_resched(void);
94 
95 DECLARE_STATIC_CALL(might_resched, __cond_resched);
96 
97 static __always_inline void might_resched(void)
98 {
99 	static_call_mod(might_resched)();
100 }
101 
102 #elif defined(CONFIG_PREEMPT_DYNAMIC) && defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
103 
104 extern int dynamic_might_resched(void);
105 # define might_resched() dynamic_might_resched()
106 
107 #else
108 
109 # define might_resched() do { } while (0)
110 
111 #endif /* CONFIG_PREEMPT_* */
112 
113 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
114 extern void __might_resched(const char *file, int line, unsigned int offsets);
115 extern void __might_sleep(const char *file, int line);
116 extern void __cant_sleep(const char *file, int line, int preempt_offset);
117 extern void __cant_migrate(const char *file, int line);
118 
119 /**
120  * might_sleep - annotation for functions that can sleep
121  *
122  * this macro will print a stack trace if it is executed in an atomic
123  * context (spinlock, irq-handler, ...). Additional sections where blocking is
124  * not allowed can be annotated with non_block_start() and non_block_end()
125  * pairs.
126  *
127  * This is a useful debugging help to be able to catch problems early and not
128  * be bitten later when the calling function happens to sleep when it is not
129  * supposed to.
130  */
131 # define might_sleep() \
132 	do { __might_sleep(__FILE__, __LINE__); might_resched(); } while (0)
133 /**
134  * cant_sleep - annotation for functions that cannot sleep
135  *
136  * this macro will print a stack trace if it is executed with preemption enabled
137  */
138 # define cant_sleep() \
139 	do { __cant_sleep(__FILE__, __LINE__, 0); } while (0)
140 # define sched_annotate_sleep()	(current->task_state_change = 0)
141 
142 /**
143  * cant_migrate - annotation for functions that cannot migrate
144  *
145  * Will print a stack trace if executed in code which is migratable
146  */
147 # define cant_migrate()							\
148 	do {								\
149 		if (IS_ENABLED(CONFIG_SMP))				\
150 			__cant_migrate(__FILE__, __LINE__);		\
151 	} while (0)
152 
153 /**
154  * non_block_start - annotate the start of section where sleeping is prohibited
155  *
156  * This is on behalf of the oom reaper, specifically when it is calling the mmu
157  * notifiers. The problem is that if the notifier were to block on, for example,
158  * mutex_lock() and if the process which holds that mutex were to perform a
159  * sleeping memory allocation, the oom reaper is now blocked on completion of
160  * that memory allocation. Other blocking calls like wait_event() pose similar
161  * issues.
162  */
163 # define non_block_start() (current->non_block_count++)
164 /**
165  * non_block_end - annotate the end of section where sleeping is prohibited
166  *
167  * Closes a section opened by non_block_start().
168  */
169 # define non_block_end() WARN_ON(current->non_block_count-- == 0)
170 #else
171   static inline void __might_resched(const char *file, int line,
172 				     unsigned int offsets) { }
173 static inline void __might_sleep(const char *file, int line) { }
174 # define might_sleep() do { might_resched(); } while (0)
175 # define cant_sleep() do { } while (0)
176 # define cant_migrate()		do { } while (0)
177 # define sched_annotate_sleep() do { } while (0)
178 # define non_block_start() do { } while (0)
179 # define non_block_end() do { } while (0)
180 #endif
181 
182 #define might_sleep_if(cond) do { if (cond) might_sleep(); } while (0)
183 
184 #if defined(CONFIG_MMU) && \
185 	(defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP))
186 #define might_fault() __might_fault(__FILE__, __LINE__)
187 void __might_fault(const char *file, int line);
188 #else
189 static inline void might_fault(void) { }
190 #endif
191 
192 void do_exit(long error_code) __noreturn;
193 
194 extern int get_option(char **str, int *pint);
195 extern char *get_options(const char *str, int nints, int *ints);
196 extern unsigned long long memparse(const char *ptr, char **retptr);
197 extern bool parse_option_str(const char *str, const char *option);
198 extern char *next_arg(char *args, char **param, char **val);
199 
200 extern int core_kernel_text(unsigned long addr);
201 extern int __kernel_text_address(unsigned long addr);
202 extern int kernel_text_address(unsigned long addr);
203 extern int func_ptr_is_kernel_text(void *ptr);
204 
205 extern void bust_spinlocks(int yes);
206 
207 extern int root_mountflags;
208 
209 extern bool early_boot_irqs_disabled;
210 
211 /*
212  * Values used for system_state. Ordering of the states must not be changed
213  * as code checks for <, <=, >, >= STATE.
214  */
215 extern enum system_states {
216 	SYSTEM_BOOTING,
217 	SYSTEM_SCHEDULING,
218 	SYSTEM_FREEING_INITMEM,
219 	SYSTEM_RUNNING,
220 	SYSTEM_HALT,
221 	SYSTEM_POWER_OFF,
222 	SYSTEM_RESTART,
223 	SYSTEM_SUSPEND,
224 } system_state;
225 
226 /*
227  * General tracing related utility functions - trace_printk(),
228  * tracing_on/tracing_off and tracing_start()/tracing_stop
229  *
230  * Use tracing_on/tracing_off when you want to quickly turn on or off
231  * tracing. It simply enables or disables the recording of the trace events.
232  * This also corresponds to the user space /sys/kernel/tracing/tracing_on
233  * file, which gives a means for the kernel and userspace to interact.
234  * Place a tracing_off() in the kernel where you want tracing to end.
235  * From user space, examine the trace, and then echo 1 > tracing_on
236  * to continue tracing.
237  *
238  * tracing_stop/tracing_start has slightly more overhead. It is used
239  * by things like suspend to ram where disabling the recording of the
240  * trace is not enough, but tracing must actually stop because things
241  * like calling smp_processor_id() may crash the system.
242  *
243  * Most likely, you want to use tracing_on/tracing_off.
244  */
245 
246 enum ftrace_dump_mode {
247 	DUMP_NONE,
248 	DUMP_ALL,
249 	DUMP_ORIG,
250 };
251 
252 #ifdef CONFIG_TRACING
253 void tracing_on(void);
254 void tracing_off(void);
255 int tracing_is_on(void);
256 void tracing_snapshot(void);
257 void tracing_snapshot_alloc(void);
258 
259 extern void tracing_start(void);
260 extern void tracing_stop(void);
261 
262 static inline __printf(1, 2)
263 void ____trace_printk_check_format(const char *fmt, ...)
264 {
265 }
266 #define __trace_printk_check_format(fmt, args...)			\
267 do {									\
268 	if (0)								\
269 		____trace_printk_check_format(fmt, ##args);		\
270 } while (0)
271 
272 /**
273  * trace_printk - printf formatting in the ftrace buffer
274  * @fmt: the printf format for printing
275  *
276  * Note: __trace_printk is an internal function for trace_printk() and
277  *       the @ip is passed in via the trace_printk() macro.
278  *
279  * This function allows a kernel developer to debug fast path sections
280  * that printk is not appropriate for. By scattering in various
281  * printk like tracing in the code, a developer can quickly see
282  * where problems are occurring.
283  *
284  * This is intended as a debugging tool for the developer only.
285  * Please refrain from leaving trace_printks scattered around in
286  * your code. (Extra memory is used for special buffers that are
287  * allocated when trace_printk() is used.)
288  *
289  * A little optimization trick is done here. If there's only one
290  * argument, there's no need to scan the string for printf formats.
291  * The trace_puts() will suffice. But how can we take advantage of
292  * using trace_puts() when trace_printk() has only one argument?
293  * By stringifying the args and checking the size we can tell
294  * whether or not there are args. __stringify((__VA_ARGS__)) will
295  * turn into "()\0" with a size of 3 when there are no args, anything
296  * else will be bigger. All we need to do is define a string to this,
297  * and then take its size and compare to 3. If it's bigger, use
298  * do_trace_printk() otherwise, optimize it to trace_puts(). Then just
299  * let gcc optimize the rest.
300  */
301 
302 #define trace_printk(fmt, ...)				\
303 do {							\
304 	char _______STR[] = __stringify((__VA_ARGS__));	\
305 	if (sizeof(_______STR) > 3)			\
306 		do_trace_printk(fmt, ##__VA_ARGS__);	\
307 	else						\
308 		trace_puts(fmt);			\
309 } while (0)
310 
311 #define do_trace_printk(fmt, args...)					\
312 do {									\
313 	static const char *trace_printk_fmt __used			\
314 		__section("__trace_printk_fmt") =			\
315 		__builtin_constant_p(fmt) ? fmt : NULL;			\
316 									\
317 	__trace_printk_check_format(fmt, ##args);			\
318 									\
319 	if (__builtin_constant_p(fmt))					\
320 		__trace_bprintk(_THIS_IP_, trace_printk_fmt, ##args);	\
321 	else								\
322 		__trace_printk(_THIS_IP_, fmt, ##args);			\
323 } while (0)
324 
325 extern __printf(2, 3)
326 int __trace_bprintk(unsigned long ip, const char *fmt, ...);
327 
328 extern __printf(2, 3)
329 int __trace_printk(unsigned long ip, const char *fmt, ...);
330 
331 /**
332  * trace_puts - write a string into the ftrace buffer
333  * @str: the string to record
334  *
335  * Note: __trace_bputs is an internal function for trace_puts and
336  *       the @ip is passed in via the trace_puts macro.
337  *
338  * This is similar to trace_printk() but is made for those really fast
339  * paths that a developer wants the least amount of "Heisenbug" effects,
340  * where the processing of the print format is still too much.
341  *
342  * This function allows a kernel developer to debug fast path sections
343  * that printk is not appropriate for. By scattering in various
344  * printk like tracing in the code, a developer can quickly see
345  * where problems are occurring.
346  *
347  * This is intended as a debugging tool for the developer only.
348  * Please refrain from leaving trace_puts scattered around in
349  * your code. (Extra memory is used for special buffers that are
350  * allocated when trace_puts() is used.)
351  *
352  * Returns: 0 if nothing was written, positive # if string was.
353  *  (1 when __trace_bputs is used, strlen(str) when __trace_puts is used)
354  */
355 
356 #define trace_puts(str) ({						\
357 	static const char *trace_printk_fmt __used			\
358 		__section("__trace_printk_fmt") =			\
359 		__builtin_constant_p(str) ? str : NULL;			\
360 									\
361 	if (__builtin_constant_p(str))					\
362 		__trace_bputs(_THIS_IP_, trace_printk_fmt);		\
363 	else								\
364 		__trace_puts(_THIS_IP_, str, strlen(str));		\
365 })
366 extern int __trace_bputs(unsigned long ip, const char *str);
367 extern int __trace_puts(unsigned long ip, const char *str, int size);
368 
369 extern void trace_dump_stack(int skip);
370 
371 /*
372  * The double __builtin_constant_p is because gcc will give us an error
373  * if we try to allocate the static variable to fmt if it is not a
374  * constant. Even with the outer if statement.
375  */
376 #define ftrace_vprintk(fmt, vargs)					\
377 do {									\
378 	if (__builtin_constant_p(fmt)) {				\
379 		static const char *trace_printk_fmt __used		\
380 		  __section("__trace_printk_fmt") =			\
381 			__builtin_constant_p(fmt) ? fmt : NULL;		\
382 									\
383 		__ftrace_vbprintk(_THIS_IP_, trace_printk_fmt, vargs);	\
384 	} else								\
385 		__ftrace_vprintk(_THIS_IP_, fmt, vargs);		\
386 } while (0)
387 
388 extern __printf(2, 0) int
389 __ftrace_vbprintk(unsigned long ip, const char *fmt, va_list ap);
390 
391 extern __printf(2, 0) int
392 __ftrace_vprintk(unsigned long ip, const char *fmt, va_list ap);
393 
394 extern void ftrace_dump(enum ftrace_dump_mode oops_dump_mode);
395 #else
396 static inline void tracing_start(void) { }
397 static inline void tracing_stop(void) { }
398 static inline void trace_dump_stack(int skip) { }
399 
400 static inline void tracing_on(void) { }
401 static inline void tracing_off(void) { }
402 static inline int tracing_is_on(void) { return 0; }
403 static inline void tracing_snapshot(void) { }
404 static inline void tracing_snapshot_alloc(void) { }
405 
406 static inline __printf(1, 2)
407 int trace_printk(const char *fmt, ...)
408 {
409 	return 0;
410 }
411 static __printf(1, 0) inline int
412 ftrace_vprintk(const char *fmt, va_list ap)
413 {
414 	return 0;
415 }
416 static inline void ftrace_dump(enum ftrace_dump_mode oops_dump_mode) { }
417 #endif /* CONFIG_TRACING */
418 
419 /* Rebuild everything on CONFIG_FTRACE_MCOUNT_RECORD */
420 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
421 # define REBUILD_DUE_TO_FTRACE_MCOUNT_RECORD
422 #endif
423 
424 /* Permissions on a sysfs file: you didn't miss the 0 prefix did you? */
425 #define VERIFY_OCTAL_PERMISSIONS(perms)						\
426 	(BUILD_BUG_ON_ZERO((perms) < 0) +					\
427 	 BUILD_BUG_ON_ZERO((perms) > 0777) +					\
428 	 /* USER_READABLE >= GROUP_READABLE >= OTHER_READABLE */		\
429 	 BUILD_BUG_ON_ZERO((((perms) >> 6) & 4) < (((perms) >> 3) & 4)) +	\
430 	 BUILD_BUG_ON_ZERO((((perms) >> 3) & 4) < ((perms) & 4)) +		\
431 	 /* USER_WRITABLE >= GROUP_WRITABLE */					\
432 	 BUILD_BUG_ON_ZERO((((perms) >> 6) & 2) < (((perms) >> 3) & 2)) +	\
433 	 /* OTHER_WRITABLE?  Generally considered a bad idea. */		\
434 	 BUILD_BUG_ON_ZERO((perms) & 2) +					\
435 	 (perms))
436 #endif
437