1 // SPDX-License-Identifier: GPL-2.0
3 * Shadow Call Stack support.
5 * Copyright (C) 2019 Google LLC
8 #include <linux/cpuhotplug.h>
9 #include <linux/kasan.h>
11 #include <linux/scs.h>
12 #include <linux/vmalloc.h>
13 #include <linux/vmstat.h>
15 #ifdef CONFIG_DYNAMIC_SCS
16 DEFINE_STATIC_KEY_FALSE(dynamic_scs_enabled);
19 static void __scs_account(void *s, int account)
21 struct page *scs_page = vmalloc_to_page(s);
23 mod_node_page_state(page_pgdat(scs_page), NR_KERNEL_SCS_KB,
24 account * (SCS_SIZE / SZ_1K));
27 /* Matches NR_CACHED_STACKS for VMAP_STACK */
28 #define NR_CACHED_SCS 2
29 static DEFINE_PER_CPU(void *, scs_cache[NR_CACHED_SCS]);
31 static void *__scs_alloc(int node)
36 for (i = 0; i < NR_CACHED_SCS; i++) {
37 s = this_cpu_xchg(scs_cache[i], NULL);
39 s = kasan_unpoison_vmalloc(s, SCS_SIZE,
40 KASAN_VMALLOC_PROT_NORMAL);
41 memset(s, 0, SCS_SIZE);
46 s = __vmalloc_node_range(SCS_SIZE, 1, VMALLOC_START, VMALLOC_END,
47 GFP_SCS, PAGE_KERNEL, 0, node,
48 __builtin_return_address(0));
51 return kasan_reset_tag(s);
54 void *scs_alloc(int node)
58 s = __scs_alloc(node);
62 *__scs_magic(s) = SCS_END_MAGIC;
65 * Poison the allocation to catch unintentional accesses to
66 * the shadow stack when KASAN is enabled.
68 kasan_poison_vmalloc(s, SCS_SIZE);
73 void scs_free(void *s)
80 * We cannot sleep as this can be called in interrupt context,
81 * so use this_cpu_cmpxchg to update the cache, and vfree_atomic
85 for (i = 0; i < NR_CACHED_SCS; i++)
86 if (this_cpu_cmpxchg(scs_cache[i], 0, s) == NULL)
89 kasan_unpoison_vmalloc(s, SCS_SIZE, KASAN_VMALLOC_PROT_NORMAL);
93 static int scs_cleanup(unsigned int cpu)
96 void **cache = per_cpu_ptr(scs_cache, cpu);
98 for (i = 0; i < NR_CACHED_SCS; i++) {
106 void __init scs_init(void)
108 if (!scs_is_enabled())
110 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "scs:scs_cache", NULL,
114 int scs_prepare(struct task_struct *tsk, int node)
118 if (!scs_is_enabled())
125 task_scs(tsk) = task_scs_sp(tsk) = s;
129 static void scs_check_usage(struct task_struct *tsk)
131 static unsigned long highest;
133 unsigned long *p, prev, curr = highest, used = 0;
135 if (!IS_ENABLED(CONFIG_DEBUG_STACK_USAGE))
138 for (p = task_scs(tsk); p < __scs_magic(tsk); ++p) {
139 if (!READ_ONCE_NOCHECK(*p))
144 while (used > curr) {
145 prev = cmpxchg_relaxed(&highest, curr, used);
148 pr_info("%s (%d): highest shadow stack usage: %lu bytes\n",
149 tsk->comm, task_pid_nr(tsk), used);
157 void scs_release(struct task_struct *tsk)
159 void *s = task_scs(tsk);
161 if (!scs_is_enabled() || !s)
164 WARN(task_scs_end_corrupted(tsk),
165 "corrupted shadow stack detected when freeing task\n");
166 scs_check_usage(tsk);