xref: /linux-6.15/include/linux/kernel.h (revision 50f9481e)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_KERNEL_H
3 #define _LINUX_KERNEL_H
4 
5 #include <linux/stdarg.h>
6 #include <linux/align.h>
7 #include <linux/limits.h>
8 #include <linux/linkage.h>
9 #include <linux/stddef.h>
10 #include <linux/types.h>
11 #include <linux/compiler.h>
12 #include <linux/bitops.h>
13 #include <linux/kstrtox.h>
14 #include <linux/log2.h>
15 #include <linux/math.h>
16 #include <linux/minmax.h>
17 #include <linux/typecheck.h>
18 #include <linux/panic.h>
19 #include <linux/printk.h>
20 #include <linux/build_bug.h>
21 #include <linux/static_call_types.h>
22 #include <asm/byteorder.h>
23 
24 #include <uapi/linux/kernel.h>
25 
26 #define STACK_MAGIC	0xdeadbeef
27 
28 /**
29  * REPEAT_BYTE - repeat the value @x multiple times as an unsigned long value
30  * @x: value to repeat
31  *
32  * NOTE: @x is not checked for > 0xff; larger values produce odd results.
33  */
34 #define REPEAT_BYTE(x)	((~0ul / 0xff) * (x))
35 
36 /* generic data direction definitions */
37 #define READ			0
38 #define WRITE			1
39 
40 /**
41  * ARRAY_SIZE - get the number of elements in array @arr
42  * @arr: array to be sized
43  */
44 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
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 #define typeof_member(T, m)	typeof(((T*)0)->m)
56 
57 #define _RET_IP_		(unsigned long)__builtin_return_address(0)
58 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
59 
60 /**
61  * upper_32_bits - return bits 32-63 of a number
62  * @n: the number we're accessing
63  *
64  * A basic shift-right of a 64- or 32-bit quantity.  Use this to suppress
65  * the "right shift count >= width of type" warning when that quantity is
66  * 32-bits.
67  */
68 #define upper_32_bits(n) ((u32)(((n) >> 16) >> 16))
69 
70 /**
71  * lower_32_bits - return bits 0-31 of a number
72  * @n: the number we're accessing
73  */
74 #define lower_32_bits(n) ((u32)((n) & 0xffffffff))
75 
76 /**
77  * upper_16_bits - return bits 16-31 of a number
78  * @n: the number we're accessing
79  */
80 #define upper_16_bits(n) ((u16)((n) >> 16))
81 
82 /**
83  * lower_16_bits - return bits 0-15 of a number
84  * @n: the number we're accessing
85  */
86 #define lower_16_bits(n) ((u16)((n) & 0xffff))
87 
88 struct completion;
89 struct user;
90 
91 #ifdef CONFIG_PREEMPT_VOLUNTARY
92 
93 extern int __cond_resched(void);
94 # define might_resched() __cond_resched()
95 
96 #elif defined(CONFIG_PREEMPT_DYNAMIC)
97 
98 extern int __cond_resched(void);
99 
100 DECLARE_STATIC_CALL(might_resched, __cond_resched);
101 
102 static __always_inline void might_resched(void)
103 {
104 	static_call_mod(might_resched)();
105 }
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_sleep(const char *file, int line, int preempt_offset);
115 extern void __might_sleep(const char *file, int line, int preempt_offset);
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__, 0); 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_sleep(const char *file, int line,
172 				   int preempt_offset) { }
173   static inline void __might_sleep(const char *file, int line,
174 				   int preempt_offset) { }
175 # define might_sleep() do { might_resched(); } while (0)
176 # define cant_sleep() do { } while (0)
177 # define cant_migrate()		do { } while (0)
178 # define sched_annotate_sleep() do { } while (0)
179 # define non_block_start() do { } while (0)
180 # define non_block_end() do { } while (0)
181 #endif
182 
183 #define might_sleep_if(cond) do { if (cond) might_sleep(); } while (0)
184 
185 #if defined(CONFIG_MMU) && \
186 	(defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP))
187 #define might_fault() __might_fault(__FILE__, __LINE__)
188 void __might_fault(const char *file, int line);
189 #else
190 static inline void might_fault(void) { }
191 #endif
192 
193 void do_exit(long error_code) __noreturn;
194 void complete_and_exit(struct completion *, long) __noreturn;
195 
196 extern int num_to_str(char *buf, int size,
197 		      unsigned long long num, unsigned int width);
198 
199 /* lib/printf utilities */
200 
201 extern __printf(2, 3) int sprintf(char *buf, const char * fmt, ...);
202 extern __printf(2, 0) int vsprintf(char *buf, const char *, va_list);
203 extern __printf(3, 4)
204 int snprintf(char *buf, size_t size, const char *fmt, ...);
205 extern __printf(3, 0)
206 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args);
207 extern __printf(3, 4)
208 int scnprintf(char *buf, size_t size, const char *fmt, ...);
209 extern __printf(3, 0)
210 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args);
211 extern __printf(2, 3) __malloc
212 char *kasprintf(gfp_t gfp, const char *fmt, ...);
213 extern __printf(2, 0) __malloc
214 char *kvasprintf(gfp_t gfp, const char *fmt, va_list args);
215 extern __printf(2, 0)
216 const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list args);
217 
218 extern __scanf(2, 3)
219 int sscanf(const char *, const char *, ...);
220 extern __scanf(2, 0)
221 int vsscanf(const char *, const char *, va_list);
222 
223 extern int no_hash_pointers_enable(char *str);
224 
225 extern int get_option(char **str, int *pint);
226 extern char *get_options(const char *str, int nints, int *ints);
227 extern unsigned long long memparse(const char *ptr, char **retptr);
228 extern bool parse_option_str(const char *str, const char *option);
229 extern char *next_arg(char *args, char **param, char **val);
230 
231 extern int core_kernel_text(unsigned long addr);
232 extern int init_kernel_text(unsigned long addr);
233 extern int core_kernel_data(unsigned long addr);
234 extern int __kernel_text_address(unsigned long addr);
235 extern int kernel_text_address(unsigned long addr);
236 extern int func_ptr_is_kernel_text(void *ptr);
237 
238 extern void bust_spinlocks(int yes);
239 
240 extern int root_mountflags;
241 
242 extern bool early_boot_irqs_disabled;
243 
244 /*
245  * Values used for system_state. Ordering of the states must not be changed
246  * as code checks for <, <=, >, >= STATE.
247  */
248 extern enum system_states {
249 	SYSTEM_BOOTING,
250 	SYSTEM_SCHEDULING,
251 	SYSTEM_FREEING_INITMEM,
252 	SYSTEM_RUNNING,
253 	SYSTEM_HALT,
254 	SYSTEM_POWER_OFF,
255 	SYSTEM_RESTART,
256 	SYSTEM_SUSPEND,
257 } system_state;
258 
259 extern const char hex_asc[];
260 #define hex_asc_lo(x)	hex_asc[((x) & 0x0f)]
261 #define hex_asc_hi(x)	hex_asc[((x) & 0xf0) >> 4]
262 
263 static inline char *hex_byte_pack(char *buf, u8 byte)
264 {
265 	*buf++ = hex_asc_hi(byte);
266 	*buf++ = hex_asc_lo(byte);
267 	return buf;
268 }
269 
270 extern const char hex_asc_upper[];
271 #define hex_asc_upper_lo(x)	hex_asc_upper[((x) & 0x0f)]
272 #define hex_asc_upper_hi(x)	hex_asc_upper[((x) & 0xf0) >> 4]
273 
274 static inline char *hex_byte_pack_upper(char *buf, u8 byte)
275 {
276 	*buf++ = hex_asc_upper_hi(byte);
277 	*buf++ = hex_asc_upper_lo(byte);
278 	return buf;
279 }
280 
281 extern int hex_to_bin(char ch);
282 extern int __must_check hex2bin(u8 *dst, const char *src, size_t count);
283 extern char *bin2hex(char *dst, const void *src, size_t count);
284 
285 bool mac_pton(const char *s, u8 *mac);
286 
287 /*
288  * General tracing related utility functions - trace_printk(),
289  * tracing_on/tracing_off and tracing_start()/tracing_stop
290  *
291  * Use tracing_on/tracing_off when you want to quickly turn on or off
292  * tracing. It simply enables or disables the recording of the trace events.
293  * This also corresponds to the user space /sys/kernel/debug/tracing/tracing_on
294  * file, which gives a means for the kernel and userspace to interact.
295  * Place a tracing_off() in the kernel where you want tracing to end.
296  * From user space, examine the trace, and then echo 1 > tracing_on
297  * to continue tracing.
298  *
299  * tracing_stop/tracing_start has slightly more overhead. It is used
300  * by things like suspend to ram where disabling the recording of the
301  * trace is not enough, but tracing must actually stop because things
302  * like calling smp_processor_id() may crash the system.
303  *
304  * Most likely, you want to use tracing_on/tracing_off.
305  */
306 
307 enum ftrace_dump_mode {
308 	DUMP_NONE,
309 	DUMP_ALL,
310 	DUMP_ORIG,
311 };
312 
313 #ifdef CONFIG_TRACING
314 void tracing_on(void);
315 void tracing_off(void);
316 int tracing_is_on(void);
317 void tracing_snapshot(void);
318 void tracing_snapshot_alloc(void);
319 
320 extern void tracing_start(void);
321 extern void tracing_stop(void);
322 
323 static inline __printf(1, 2)
324 void ____trace_printk_check_format(const char *fmt, ...)
325 {
326 }
327 #define __trace_printk_check_format(fmt, args...)			\
328 do {									\
329 	if (0)								\
330 		____trace_printk_check_format(fmt, ##args);		\
331 } while (0)
332 
333 /**
334  * trace_printk - printf formatting in the ftrace buffer
335  * @fmt: the printf format for printing
336  *
337  * Note: __trace_printk is an internal function for trace_printk() and
338  *       the @ip is passed in via the trace_printk() macro.
339  *
340  * This function allows a kernel developer to debug fast path sections
341  * that printk is not appropriate for. By scattering in various
342  * printk like tracing in the code, a developer can quickly see
343  * where problems are occurring.
344  *
345  * This is intended as a debugging tool for the developer only.
346  * Please refrain from leaving trace_printks scattered around in
347  * your code. (Extra memory is used for special buffers that are
348  * allocated when trace_printk() is used.)
349  *
350  * A little optimization trick is done here. If there's only one
351  * argument, there's no need to scan the string for printf formats.
352  * The trace_puts() will suffice. But how can we take advantage of
353  * using trace_puts() when trace_printk() has only one argument?
354  * By stringifying the args and checking the size we can tell
355  * whether or not there are args. __stringify((__VA_ARGS__)) will
356  * turn into "()\0" with a size of 3 when there are no args, anything
357  * else will be bigger. All we need to do is define a string to this,
358  * and then take its size and compare to 3. If it's bigger, use
359  * do_trace_printk() otherwise, optimize it to trace_puts(). Then just
360  * let gcc optimize the rest.
361  */
362 
363 #define trace_printk(fmt, ...)				\
364 do {							\
365 	char _______STR[] = __stringify((__VA_ARGS__));	\
366 	if (sizeof(_______STR) > 3)			\
367 		do_trace_printk(fmt, ##__VA_ARGS__);	\
368 	else						\
369 		trace_puts(fmt);			\
370 } while (0)
371 
372 #define do_trace_printk(fmt, args...)					\
373 do {									\
374 	static const char *trace_printk_fmt __used			\
375 		__section("__trace_printk_fmt") =			\
376 		__builtin_constant_p(fmt) ? fmt : NULL;			\
377 									\
378 	__trace_printk_check_format(fmt, ##args);			\
379 									\
380 	if (__builtin_constant_p(fmt))					\
381 		__trace_bprintk(_THIS_IP_, trace_printk_fmt, ##args);	\
382 	else								\
383 		__trace_printk(_THIS_IP_, fmt, ##args);			\
384 } while (0)
385 
386 extern __printf(2, 3)
387 int __trace_bprintk(unsigned long ip, const char *fmt, ...);
388 
389 extern __printf(2, 3)
390 int __trace_printk(unsigned long ip, const char *fmt, ...);
391 
392 /**
393  * trace_puts - write a string into the ftrace buffer
394  * @str: the string to record
395  *
396  * Note: __trace_bputs is an internal function for trace_puts and
397  *       the @ip is passed in via the trace_puts macro.
398  *
399  * This is similar to trace_printk() but is made for those really fast
400  * paths that a developer wants the least amount of "Heisenbug" effects,
401  * where the processing of the print format is still too much.
402  *
403  * This function allows a kernel developer to debug fast path sections
404  * that printk is not appropriate for. By scattering in various
405  * printk like tracing in the code, a developer can quickly see
406  * where problems are occurring.
407  *
408  * This is intended as a debugging tool for the developer only.
409  * Please refrain from leaving trace_puts scattered around in
410  * your code. (Extra memory is used for special buffers that are
411  * allocated when trace_puts() is used.)
412  *
413  * Returns: 0 if nothing was written, positive # if string was.
414  *  (1 when __trace_bputs is used, strlen(str) when __trace_puts is used)
415  */
416 
417 #define trace_puts(str) ({						\
418 	static const char *trace_printk_fmt __used			\
419 		__section("__trace_printk_fmt") =			\
420 		__builtin_constant_p(str) ? str : NULL;			\
421 									\
422 	if (__builtin_constant_p(str))					\
423 		__trace_bputs(_THIS_IP_, trace_printk_fmt);		\
424 	else								\
425 		__trace_puts(_THIS_IP_, str, strlen(str));		\
426 })
427 extern int __trace_bputs(unsigned long ip, const char *str);
428 extern int __trace_puts(unsigned long ip, const char *str, int size);
429 
430 extern void trace_dump_stack(int skip);
431 
432 /*
433  * The double __builtin_constant_p is because gcc will give us an error
434  * if we try to allocate the static variable to fmt if it is not a
435  * constant. Even with the outer if statement.
436  */
437 #define ftrace_vprintk(fmt, vargs)					\
438 do {									\
439 	if (__builtin_constant_p(fmt)) {				\
440 		static const char *trace_printk_fmt __used		\
441 		  __section("__trace_printk_fmt") =			\
442 			__builtin_constant_p(fmt) ? fmt : NULL;		\
443 									\
444 		__ftrace_vbprintk(_THIS_IP_, trace_printk_fmt, vargs);	\
445 	} else								\
446 		__ftrace_vprintk(_THIS_IP_, fmt, vargs);		\
447 } while (0)
448 
449 extern __printf(2, 0) int
450 __ftrace_vbprintk(unsigned long ip, const char *fmt, va_list ap);
451 
452 extern __printf(2, 0) int
453 __ftrace_vprintk(unsigned long ip, const char *fmt, va_list ap);
454 
455 extern void ftrace_dump(enum ftrace_dump_mode oops_dump_mode);
456 #else
457 static inline void tracing_start(void) { }
458 static inline void tracing_stop(void) { }
459 static inline void trace_dump_stack(int skip) { }
460 
461 static inline void tracing_on(void) { }
462 static inline void tracing_off(void) { }
463 static inline int tracing_is_on(void) { return 0; }
464 static inline void tracing_snapshot(void) { }
465 static inline void tracing_snapshot_alloc(void) { }
466 
467 static inline __printf(1, 2)
468 int trace_printk(const char *fmt, ...)
469 {
470 	return 0;
471 }
472 static __printf(1, 0) inline int
473 ftrace_vprintk(const char *fmt, va_list ap)
474 {
475 	return 0;
476 }
477 static inline void ftrace_dump(enum ftrace_dump_mode oops_dump_mode) { }
478 #endif /* CONFIG_TRACING */
479 
480 /* This counts to 12. Any more, it will return 13th argument. */
481 #define __COUNT_ARGS(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _n, X...) _n
482 #define COUNT_ARGS(X...) __COUNT_ARGS(, ##X, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
483 
484 #define __CONCAT(a, b) a ## b
485 #define CONCATENATE(a, b) __CONCAT(a, b)
486 
487 /**
488  * container_of - cast a member of a structure out to the containing structure
489  * @ptr:	the pointer to the member.
490  * @type:	the type of the container struct this is embedded in.
491  * @member:	the name of the member within the struct.
492  *
493  */
494 #define container_of(ptr, type, member) ({				\
495 	void *__mptr = (void *)(ptr);					\
496 	BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) &&	\
497 			 !__same_type(*(ptr), void),			\
498 			 "pointer type mismatch in container_of()");	\
499 	((type *)(__mptr - offsetof(type, member))); })
500 
501 /**
502  * container_of_safe - cast a member of a structure out to the containing structure
503  * @ptr:	the pointer to the member.
504  * @type:	the type of the container struct this is embedded in.
505  * @member:	the name of the member within the struct.
506  *
507  * If IS_ERR_OR_NULL(ptr), ptr is returned unchanged.
508  */
509 #define container_of_safe(ptr, type, member) ({				\
510 	void *__mptr = (void *)(ptr);					\
511 	BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) &&	\
512 			 !__same_type(*(ptr), void),			\
513 			 "pointer type mismatch in container_of()");	\
514 	IS_ERR_OR_NULL(__mptr) ? ERR_CAST(__mptr) :			\
515 		((type *)(__mptr - offsetof(type, member))); })
516 
517 /* Rebuild everything on CONFIG_FTRACE_MCOUNT_RECORD */
518 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
519 # define REBUILD_DUE_TO_FTRACE_MCOUNT_RECORD
520 #endif
521 
522 /* Permissions on a sysfs file: you didn't miss the 0 prefix did you? */
523 #define VERIFY_OCTAL_PERMISSIONS(perms)						\
524 	(BUILD_BUG_ON_ZERO((perms) < 0) +					\
525 	 BUILD_BUG_ON_ZERO((perms) > 0777) +					\
526 	 /* USER_READABLE >= GROUP_READABLE >= OTHER_READABLE */		\
527 	 BUILD_BUG_ON_ZERO((((perms) >> 6) & 4) < (((perms) >> 3) & 4)) +	\
528 	 BUILD_BUG_ON_ZERO((((perms) >> 3) & 4) < ((perms) & 4)) +		\
529 	 /* USER_WRITABLE >= GROUP_WRITABLE */					\
530 	 BUILD_BUG_ON_ZERO((((perms) >> 6) & 2) < (((perms) >> 3) & 2)) +	\
531 	 /* OTHER_WRITABLE?  Generally considered a bad idea. */		\
532 	 BUILD_BUG_ON_ZERO((perms) & 2) +					\
533 	 (perms))
534 #endif
535