xref: /linux/arch/arm64/include/asm/pkeys.h (revision 5ea5880764cbb164afb17a62e76ca75dc371409d)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (C) 2023 Arm Ltd.
4  *
5  * Based on arch/x86/include/asm/pkeys.h
6  */
7 
8 #ifndef _ASM_ARM64_PKEYS_H
9 #define _ASM_ARM64_PKEYS_H
10 
11 #define ARCH_VM_PKEY_FLAGS (VM_PKEY_BIT0 | VM_PKEY_BIT1 | VM_PKEY_BIT2)
12 
13 #define arch_max_pkey() 8
14 
15 int arch_set_user_pkey_access(int pkey, unsigned long init_val);
16 
17 static inline bool arch_pkeys_enabled(void)
18 {
19 	return system_supports_poe();
20 }
21 
22 static inline int vma_pkey(struct vm_area_struct *vma)
23 {
24 	return (vma->vm_flags & ARCH_VM_PKEY_FLAGS) >> VM_PKEY_SHIFT;
25 }
26 
27 static inline int arch_override_mprotect_pkey(struct vm_area_struct *vma,
28 		int prot, int pkey)
29 {
30 	if (pkey != -1)
31 		return pkey;
32 
33 	return vma_pkey(vma);
34 }
35 
36 static inline int execute_only_pkey(struct mm_struct *mm)
37 {
38 	// Execute-only mappings are handled by EPAN/FEAT_PAN3.
39 	return -1;
40 }
41 
42 #define mm_pkey_allocation_map(mm)	(mm)->context.pkey_allocation_map
43 #define mm_set_pkey_allocated(mm, pkey) do {		\
44 	mm_pkey_allocation_map(mm) |= (1U << pkey);	\
45 } while (0)
46 #define mm_set_pkey_free(mm, pkey) do {			\
47 	mm_pkey_allocation_map(mm) &= ~(1U << pkey);	\
48 } while (0)
49 
50 static inline bool mm_pkey_is_allocated(struct mm_struct *mm, int pkey)
51 {
52 	/*
53 	 * "Allocated" pkeys are those that have been returned
54 	 * from pkey_alloc() or pkey 0 which is allocated
55 	 * implicitly when the mm is created.
56 	 */
57 	if (pkey < 0 || pkey >= arch_max_pkey())
58 		return false;
59 
60 	return mm_pkey_allocation_map(mm) & (1U << pkey);
61 }
62 
63 /*
64  * Returns a positive, 3-bit key on success, or -1 on failure.
65  */
66 static inline int mm_pkey_alloc(struct mm_struct *mm)
67 {
68 	/*
69 	 * Note: this is the one and only place we make sure
70 	 * that the pkey is valid as far as the hardware is
71 	 * concerned.  The rest of the kernel trusts that
72 	 * only good, valid pkeys come out of here.
73 	 */
74 	u8 all_pkeys_mask = GENMASK(arch_max_pkey() - 1, 0);
75 	int ret;
76 
77 	if (!arch_pkeys_enabled())
78 		return -1;
79 
80 	/*
81 	 * Are we out of pkeys?  We must handle this specially
82 	 * because ffz() behavior is undefined if there are no
83 	 * zeros.
84 	 */
85 	if (mm_pkey_allocation_map(mm) == all_pkeys_mask)
86 		return -1;
87 
88 	ret = ffz(mm_pkey_allocation_map(mm));
89 
90 	mm_set_pkey_allocated(mm, ret);
91 
92 	return ret;
93 }
94 
95 static inline int mm_pkey_free(struct mm_struct *mm, int pkey)
96 {
97 	if (!mm_pkey_is_allocated(mm, pkey))
98 		return -EINVAL;
99 
100 	mm_set_pkey_free(mm, pkey);
101 
102 	return 0;
103 }
104 
105 #endif /* _ASM_ARM64_PKEYS_H */
106