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 static void __scs_account(void *s, int account)
17 struct page *scs_page = vmalloc_to_page(s);
19 mod_node_page_state(page_pgdat(scs_page), NR_KERNEL_SCS_KB,
20 account * (SCS_SIZE / SZ_1K));
23 /* Matches NR_CACHED_STACKS for VMAP_STACK */
24 #define NR_CACHED_SCS 2
25 static DEFINE_PER_CPU(void *, scs_cache[NR_CACHED_SCS]);
27 static void *__scs_alloc(int node)
32 for (i = 0; i < NR_CACHED_SCS; i++) {
33 s = this_cpu_xchg(scs_cache[i], NULL);
35 s = kasan_unpoison_vmalloc(s, SCS_SIZE,
36 KASAN_VMALLOC_PROT_NORMAL);
37 memset(s, 0, SCS_SIZE);
42 s = __vmalloc_node_range(SCS_SIZE, 1, VMALLOC_START, VMALLOC_END,
43 GFP_SCS, PAGE_KERNEL, 0, node,
44 __builtin_return_address(0));
47 return kasan_reset_tag(s);
50 void *scs_alloc(int node)
54 s = __scs_alloc(node);
58 *__scs_magic(s) = SCS_END_MAGIC;
61 * Poison the allocation to catch unintentional accesses to
62 * the shadow stack when KASAN is enabled.
64 kasan_poison_vmalloc(s, SCS_SIZE);
69 void scs_free(void *s)
76 * We cannot sleep as this can be called in interrupt context,
77 * so use this_cpu_cmpxchg to update the cache, and vfree_atomic
81 for (i = 0; i < NR_CACHED_SCS; i++)
82 if (this_cpu_cmpxchg(scs_cache[i], 0, s) == NULL)
85 kasan_unpoison_vmalloc(s, SCS_SIZE, KASAN_VMALLOC_PROT_NORMAL);
89 static int scs_cleanup(unsigned int cpu)
92 void **cache = per_cpu_ptr(scs_cache, cpu);
94 for (i = 0; i < NR_CACHED_SCS; i++) {
102 void __init scs_init(void)
104 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "scs:scs_cache", NULL,
108 int scs_prepare(struct task_struct *tsk, int node)
110 void *s = scs_alloc(node);
115 task_scs(tsk) = task_scs_sp(tsk) = s;
119 static void scs_check_usage(struct task_struct *tsk)
121 static unsigned long highest;
123 unsigned long *p, prev, curr = highest, used = 0;
125 if (!IS_ENABLED(CONFIG_DEBUG_STACK_USAGE))
128 for (p = task_scs(tsk); p < __scs_magic(tsk); ++p) {
129 if (!READ_ONCE_NOCHECK(*p))
134 while (used > curr) {
135 prev = cmpxchg_relaxed(&highest, curr, used);
138 pr_info("%s (%d): highest shadow stack usage: %lu bytes\n",
139 tsk->comm, task_pid_nr(tsk), used);
147 void scs_release(struct task_struct *tsk)
149 void *s = task_scs(tsk);
154 WARN(task_scs_end_corrupted(tsk),
155 "corrupted shadow stack detected when freeing task\n");
156 scs_check_usage(tsk);