xref: /linux-6.15/include/linux/scs.h (revision 51189c7a)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Shadow Call Stack support.
4  *
5  * Copyright (C) 2019 Google LLC
6  */
7 
8 #ifndef _LINUX_SCS_H
9 #define _LINUX_SCS_H
10 
11 #include <linux/gfp.h>
12 #include <linux/poison.h>
13 #include <linux/sched.h>
14 #include <linux/sizes.h>
15 
16 #ifdef CONFIG_SHADOW_CALL_STACK
17 
18 /*
19  * In testing, 1 KiB shadow stack size (i.e. 128 stack frames on a 64-bit
20  * architecture) provided ~40% safety margin on stack usage while keeping
21  * memory allocation overhead reasonable.
22  */
23 #define SCS_SIZE		SZ_1K
24 #define GFP_SCS			(GFP_KERNEL | __GFP_ZERO)
25 
26 /* An illegal pointer value to mark the end of the shadow stack. */
27 #define SCS_END_MAGIC		(0x5f6UL + POISON_POINTER_DELTA)
28 
29 #define task_scs(tsk)		(task_thread_info(tsk)->scs_base)
30 #define task_scs_sp(tsk)	(task_thread_info(tsk)->scs_sp)
31 
32 void scs_init(void);
33 int scs_prepare(struct task_struct *tsk, int node);
34 void scs_release(struct task_struct *tsk);
35 
36 static inline void scs_task_reset(struct task_struct *tsk)
37 {
38 	/*
39 	 * Reset the shadow stack to the base address in case the task
40 	 * is reused.
41 	 */
42 	task_scs_sp(tsk) = task_scs(tsk);
43 }
44 
45 static inline unsigned long *__scs_magic(void *s)
46 {
47 	return (unsigned long *)(s + SCS_SIZE) - 1;
48 }
49 
50 static inline bool scs_corrupted(struct task_struct *tsk)
51 {
52 	unsigned long *magic = __scs_magic(task_scs(tsk));
53 	unsigned long sz = task_scs_sp(tsk) - task_scs(tsk);
54 
55 	return sz >= SCS_SIZE - 1 || READ_ONCE_NOCHECK(*magic) != SCS_END_MAGIC;
56 }
57 
58 #else /* CONFIG_SHADOW_CALL_STACK */
59 
60 static inline void scs_init(void) {}
61 static inline void scs_task_reset(struct task_struct *tsk) {}
62 static inline int scs_prepare(struct task_struct *tsk, int node) { return 0; }
63 static inline bool scs_corrupted(struct task_struct *tsk) { return false; }
64 static inline void scs_release(struct task_struct *tsk) {}
65 
66 #endif /* CONFIG_SHADOW_CALL_STACK */
67 
68 #endif /* _LINUX_SCS_H */
69