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 #define SCS_ORDER 0 19 #define SCS_SIZE (PAGE_SIZE << SCS_ORDER) 20 #define GFP_SCS (GFP_KERNEL | __GFP_ZERO) 21 22 /* An illegal pointer value to mark the end of the shadow stack. */ 23 #define SCS_END_MAGIC (0x5f6UL + POISON_POINTER_DELTA) 24 25 /* Allocate a static per-CPU shadow stack */ 26 #define DEFINE_SCS(name) \ 27 DEFINE_PER_CPU(unsigned long [SCS_SIZE/sizeof(long)], name) \ 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_alloc(int node); 33 void scs_free(void *s); 34 void scs_init(void); 35 int scs_prepare(struct task_struct *tsk, int node); 36 void scs_release(struct task_struct *tsk); 37 38 static inline void scs_task_reset(struct task_struct *tsk) 39 { 40 /* 41 * Reset the shadow stack to the base address in case the task 42 * is reused. 43 */ 44 task_scs_sp(tsk) = task_scs(tsk); 45 } 46 47 static inline unsigned long *__scs_magic(void *s) 48 { 49 return (unsigned long *)(s + SCS_SIZE) - 1; 50 } 51 52 static inline bool task_scs_end_corrupted(struct task_struct *tsk) 53 { 54 unsigned long *magic = __scs_magic(task_scs(tsk)); 55 unsigned long sz = task_scs_sp(tsk) - task_scs(tsk); 56 57 return sz >= SCS_SIZE - 1 || READ_ONCE_NOCHECK(*magic) != SCS_END_MAGIC; 58 } 59 60 #else /* CONFIG_SHADOW_CALL_STACK */ 61 62 static inline void *scs_alloc(int node) { return NULL; } 63 static inline void scs_free(void *s) {} 64 static inline void scs_init(void) {} 65 static inline void scs_task_reset(struct task_struct *tsk) {} 66 static inline int scs_prepare(struct task_struct *tsk, int node) { return 0; } 67 static inline void scs_release(struct task_struct *tsk) {} 68 static inline bool task_scs_end_corrupted(struct task_struct *tsk) { return false; } 69 70 #endif /* CONFIG_SHADOW_CALL_STACK */ 71 72 #endif /* _LINUX_SCS_H */ 73