xref: /linux/arch/loongarch/include/asm/kfence.h (revision be239684b18e1cdcafcf8c7face4a2f562c745ad)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * KFENCE support for LoongArch.
4  *
5  * Author: Enze Li <lienze@kylinos.cn>
6  * Copyright (C) 2022-2023 KylinSoft Corporation.
7  */
8 
9 #ifndef _ASM_LOONGARCH_KFENCE_H
10 #define _ASM_LOONGARCH_KFENCE_H
11 
12 #include <linux/kfence.h>
13 #include <asm/pgtable.h>
14 #include <asm/tlb.h>
15 
16 static inline bool arch_kfence_init_pool(void)
17 {
18 	int err;
19 	char *kfence_pool = __kfence_pool;
20 	struct vm_struct *area;
21 
22 	area = __get_vm_area_caller(KFENCE_POOL_SIZE, VM_IOREMAP,
23 				    KFENCE_AREA_START, KFENCE_AREA_END,
24 				    __builtin_return_address(0));
25 	if (!area)
26 		return false;
27 
28 	__kfence_pool = (char *)area->addr;
29 	err = ioremap_page_range((unsigned long)__kfence_pool,
30 				 (unsigned long)__kfence_pool + KFENCE_POOL_SIZE,
31 				 virt_to_phys((void *)kfence_pool), PAGE_KERNEL);
32 	if (err) {
33 		free_vm_area(area);
34 		__kfence_pool = kfence_pool;
35 		return false;
36 	}
37 
38 	return true;
39 }
40 
41 /* Protect the given page and flush TLB. */
42 static inline bool kfence_protect_page(unsigned long addr, bool protect)
43 {
44 	pte_t *pte = virt_to_kpte(addr);
45 
46 	if (WARN_ON(!pte) || pte_none(*pte))
47 		return false;
48 
49 	if (protect)
50 		set_pte(pte, __pte(pte_val(*pte) & ~(_PAGE_VALID | _PAGE_PRESENT)));
51 	else
52 		set_pte(pte, __pte(pte_val(*pte) | (_PAGE_VALID | _PAGE_PRESENT)));
53 
54 	preempt_disable();
55 	local_flush_tlb_one(addr);
56 	preempt_enable();
57 
58 	return true;
59 }
60 
61 #endif /* _ASM_LOONGARCH_KFENCE_H */
62