Skip to contentSkip to conversation

arch, mm: create a generic set_memory/change_page_attr core

RFC PATCH New Mike Rapoport (Microsoft) 1 participant 55 messages Nov 26

Subsystems (12)
lore
Share & tools
lore
#0 lore raw

v2 cover arch, mm: create a generic set_memory/change_page_attr core

= tl;dr =

This is heavily reworked v2 of

https://lore.kernel.org/all/[email protected]

I decided to convert all architectures that implement set_memory_*() in one series so that it will be clear that the consolidation does not have conceptual gaps.

While the series is large, a bulk of it is a refactoring of x86's CPA, and then several commits that create the generic code and a few commits per converted architecture.

= Motivation =

Currently there are 7 independent implementations for set_memory and set_direct_map APIs.

With increasing demand for kernel page table manipulations, for example "Direct Map Removal Support for guest_memfd" [1] and "mm: ASI direct map management" [2], it makes sense to have a generic core for kernel page table manipulation in mm/ with helpers in the architecture specific code.

A fix to a UAF bug [3] earlier this year had to touch set memory functionality in subtly different way in different architectures rather than to fix the core logic in a single place.

x86's implementation is the most versatile and most battle tested and as such it is the best base for the generic implementation: it preserves large mappings when it can, it splits when it must, it handles the direct map alias, it serializes against itself and it sanity checks the result. The others are catching up one bug at a time ;-)

With the generic CPA core in place it would be possible to:

- make sure protection updates follow all-or-nothing principle: today a request that fails half way leaves the pages it already processed changed and a caller has no real way to recover from it
- add an "atomic" mode to CPA so that it could handle debug_pagealloc and KFENCE the same way on all architectures
- enable collapse of large mappings on arm64 with BBML3 and on s390 and let them use EXECMEM_ROX_CACHE
- enable collapse of the direct map sometime in the future

= Changes =

This series converts all the architectures that implement set_memory APIs to use a generic core based on x86 implementation so that all of them have the same behaviour.

The core walks the page tables, serializes the requests, decides how large mappings are handled, and makes direct map counters in /proc/meminfo and /proc/vmstat and CPA statistics in debugfs available to all architectures.

The architectures take care of the page table format, of what they can split, of definitions of alias mappings and of the TLB flushes.

The changelogs of the conversion patches list what changes for every architecture.

I left out Documentation/mm/kernel-page-tables.rst update for now. Will post it with non-RFC version.

= Patches =

Patches 1-2 are riscv fixes for handling of p4d leaves and Svnapot.

Patches 3-5 align command line parsing in s390 decompressor with the kernel to make sure both kernel and decompressor see the same parameter values, particularly for debug_pagealloc.

Patches 6-17 are x86 fixes and cleanups.

Patches 18-28 reorganize x86 CPA implementation to make it friendlier for generalization and separate the generic part of CPA from the x86 specifics.

Patch 29 pulls CPA core to mm/pageattr.c and declares the architecture hooks in include/linux/pageattr.h.

Patches 30-32, 38, 43, 44 and 48 add bits that the architectures converted after them need.

Then there are the conversion patches:
- 33-36 for LoongArch
- 37 for ARM
- 39 for powerpc
- 40-42 for riscv
- 45-47 for s390
- 49-52 for arm64

And in the end, patch 53 enables the generic core with ARCH_HAS_SET_MEMORY and patch 54 adds kernel-doc for the API and the hooks.

= Testing =

The patches are build tested on all architectures with various relevant configuration options turned on and off.

arm64 and riscv boot in QEMU and pass module load and unload loops, BPF JIT loads, memfd_secret() and writes to tmpfs, which on arm64 trigger CPA with debug_pagealloc.

x86 is tested in KVM with the CPA self test, module load and unload loops and BPF JIT loads.

All three were tested with and without debug_pagealloc, and arm64 with rodata=on as well.

The tests ran with a concurrent loop reading the kernel page tables dump in debugfs to rule out races with ptdump.

I also verified that there is no measurable performance difference on x86.

= Prerequisites =

While working on this series I found a few more issues, though much less pressing than UAF :)

The fixes for x86 [4], riscv [5] and s390 [6] are posted separately.

This series is on top of v7.4-rc3 with the posted fixes applied and with hibernation series [7] from mm-nonmm-unstable that is waiting for the next merge window in Andrew's tree.

b4 will conflict on the hibernation series, it's easier to get this RFC from git:

https://git.kernel.org/pub/scm/linux/kernel/git/rppt/linux.git/log/?h=generic-set-memory/rfc-v2

= Merging =

As Dave suggested [8], I'd like this to go through mm with acks from the architectures.

= References =

[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]
[4] https://lore.kernel.org/all/[email protected]
[5] https://lore.kernel.org/all/[email protected]
[6] https://lore.kernel.org/all/[email protected]
[7] https://lore.kernel.org/all/[email protected]
[8] https://lore.kernel.org/all/[email protected]

---
v2 changes:
* revamp the series :)

v1: https://patch.msgid.link/[email protected]

---
Mike Rapoport (Microsoft) (54):
riscv: do not use P4D entries for the linear mapping
riscv: test for Svnapot in pte_napot()
s390/boot: parse boolean parameters like the kernel s390/boot: stop parsing the command line at "--"
s390/boot: treat dashes and underscores alike in parameter names x86/mm/pat: don't count kernel image splits as direct map splits x86/mm/pat: drop KERN_WARNING from the WARN() in __cpa_process_fault() x86/mm/pat: fail a split at an unexpected level with -EINVAL x86/mm/pat: separate CPA request flags from internal state x86/mm/pat: stop using CPA for debug_pagealloc
x86/mm/pat: drop the init_mm read lock from change_page_attr_set_clr() x86/mm/pat: introduce change_page_attr_pages()
x86/mm/pat: make the direct map counters atomic
x86/mm/pat: take pgd_lock only around the pgd_list walks x86/mm/pat: look up the effective NX/RW bits in verify_rwx() x86/mm/pat: look up a large page again only after dropping cpa_lock x86/mm/pat: drop the check of existing mappings against static protections x86/mm/pat: consolidate encoding of page table entries x86/mm/pat: use enum pgtable_level in CPA
x86/mm/pat: index the CPA statistics by page table level x86/mm/pat: introduce struct cpa_leaf
x86/mm/pat: consolidate calculation of the new protection x86/mm/pat: allocate the page tables for a split by level x86/mm/pat: detect unchanged mappings by comparing protections x86/mm/pat: add cpa_is_direct_map()
x86/mm/pat: implement set_memory_*() with a table of operations x86/mm/pat: prepare the direct map counters for the generic code x86/mm/pat: separate the generic part of CPA from the x86 hooks x86/mm/pat, mm: pull CPA core to mm/
mm/pageattr: introduce arch_cpa_can_split()
mm/pageattr: introduce cpa_flush_tlb_kernel_range()
asm-generic: add an empty pageattr.h
LoongArch: use pfn_is_nosave() to exclude firmware ranges from hibernation
LoongArch: stop pretending LoongArch supports set_direct_map APIs
LoongArch: drop the huge page handling from set_memory()
LoongArch: use the generic CPA core
ARM: mm: use the generic CPA core
mm/pageattr: let a leaf cover a contiguous block of entries
powerpc: use the generic CPA core
riscv: replace set_memory_rw_nx() with set_memory_nx() and set_memory_rw()
riscv: use the generic CPA core
riscv: count the mappings of the linear map
mm/pageattr: let an architecture allocate the page tables for a split mm/pageattr: derive direct map counter updates from the level sizes s390/boot: map the identity map with 4K pages for debug_pagealloc
s390: remove set_memory_rwnx()
s390: use the generic CPA core
mm/pageattr: let an architecture bracket the set_memory() entry points
arm64: mm: allocate page tables in the callers of split_p{mu}d()
arm64: use the generic CPA core
arm64: let the generic CPA core split large mappings
arm64: count the mappings of the linear map
arch, mm: enable the generic CPA core with ARCH_HAS_SET_MEMORY mm/pageattr: document CPA core and the architecture hooks

 arch/arm/include/asm/set_memory.h       |    6 +-
 arch/arm/mm/pageattr.c                  |   96 ++-
 arch/arm64/include/asm/mmu.h            |    3 -
 arch/arm64/include/asm/pageattr.h       |   23 +
 arch/arm64/include/asm/set_memory.h     |    2 -
 arch/arm64/mm/init.c                    |    3 -
 arch/arm64/mm/mmu.c                     |  310 +++-----
 arch/arm64/mm/pageattr.c                |  390 +++++-----
 arch/loongarch/Kconfig                  |    1 -
 arch/loongarch/include/asm/set_memory.h |   12 +-
 arch/loongarch/mm/pageattr.c            |  215 +-----
 arch/loongarch/power/hibernate.c        |    6 +-
 arch/powerpc/include/asm/set_memory.h   |   46 +-
 arch/powerpc/mm/pageattr.c              |  160 ++--
 arch/riscv/include/asm/pageattr.h       |   17 +
 arch/riscv/include/asm/pgtable.h        |   10 +-
 arch/riscv/include/asm/set_memory.h     |   10 +-
 arch/riscv/kernel/setup.c               |    6 +-
 arch/riscv/mm/init.c                    |   24 +-
 arch/riscv/mm/pageattr.c                |  459 ++++--------
 arch/s390/boot/boot.h                   |    1 +
 arch/s390/boot/ipl_parm.c               |   64 +-
 arch/s390/boot/string.c                 |    9 +
 arch/s390/boot/vmem.c                   |    3 +-
 arch/s390/include/asm/pageattr.h        |   21 +
 arch/s390/include/asm/set_memory.h      |   56 +-
 arch/s390/mm/dump_pagetables.c          |    2 -
 arch/s390/mm/init.c                     |   15 +
 arch/s390/mm/pageattr.c                 |  496 ++++++-------
 arch/s390/mm/vmem.c                     |   12 +-
 arch/x86/Kconfig                        |    8 -
 arch/x86/include/asm/pageattr.h         |   33 +
 arch/x86/include/asm/pgtable_types.h    |    6 -
 arch/x86/include/asm/set_memory.h       |    5 -
 arch/x86/mm/init_32.c                   |    5 +-
 arch/x86/mm/init_64.c                   |   15 +-
 arch/x86/mm/pat/set_memory.c            | 1220 +++++++++----------------------
 include/asm-generic/Kbuild              |    1 +
 include/asm-generic/pageattr.h          |    5 +
 include/asm-generic/set_memory.h        |   11 +
 include/linux/pageattr.h                |  459 ++++++++++++
 include/linux/pgtable.h                 |   26 +
 include/linux/vm_event_item.h           |    2 +-
 mm/Kconfig                              |    3 +
 mm/Kconfig.debug                        |    8 +
 mm/Makefile                             |    1 +
 mm/pageattr.c                           |  684 +++++++++++++++++
 mm/vmstat.c                             |    2 +-
 48 files changed, 2614 insertions(+), 2358 deletions(-)

---
base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3
change-id: 20260721-generic-set-memory-v0-1-06547a00b2ae
prerequisite-change-id: 20260916-hibernation-7603b86eb981:v2
prerequisite-patch-id: b1bb2d4e1a2f542e3e8d0741a30a780722a350b0
prerequisite-patch-id: da4fcef1a9df5f657cadfccf591d6bbb45a197f4
prerequisite-patch-id: 6eab635bf8bd5b2ad0b40464fc7f595d7929769a
prerequisite-patch-id: 74ad7bb09568c6b155058869cddbca01f37ee377
prerequisite-patch-id: 319fe0988123448585901a69c901cd6381744ae7
prerequisite-change-id: 20261112-fixes-x86-0c15b6adc212:v1
prerequisite-patch-id: 00540235ba71e3d6f77190958aed21af53e3231e
prerequisite-patch-id: 4c8347b413897acfb979f48814bd0a98887881cb
prerequisite-patch-id: 3432c685702db763dc8ace31c0ba56e9e357c97d
prerequisite-patch-id: 0b22ccc8b6b84cf68d83eb4322196cc51b22310e
prerequisite-patch-id: 0e2e3eb56ec4e967db60bc464e42cdcb4a132571
prerequisite-patch-id: f35d21bc18f51b0ca3fc3c80f3fb8901ce207f98
prerequisite-patch-id: b1825b2c583747b97cfee853f231ff91fbbb1e64
prerequisite-patch-id: c972a0aef660b2fc348ad08acfd290406b565932
prerequisite-patch-id: 95489ac4f31f34a8b874ca96c6145c6613f9b612
prerequisite-change-id: 20261112-fixes-riscv-3e48788f58fe:v2
prerequisite-patch-id: 99056c0e4f9faa899a17b9cdc913796f60d848d5
prerequisite-patch-id: cc95791ee9f36ddcf041d6c0dd9ddd655ed38718
prerequisite-change-id: 20261117-fixes-s390-82943938787a:v1
prerequisite-patch-id: f93f6904a8052e1e5e504e055e886363846b7881

--
Sincerely yours,
Mike.

#1 lore raw

RFC PATCH v2 1/54 riscv: do not use P4D entries for the linear mapping

The linear map uses P4D sized leaves with Sv57 since commit 3335068f8721 ("riscv: Use PUD/P4D/PGD pages for the linear mapping"), but riscv has no p4d_leaf() and the generic stub returns false.

As a result, kernel page table walks treat P4D leaves as tables and wrongly descend to lower levels. This affects the split in set_memory_*(), kernel_page_present(), ptdump and the hibernation page table copy.

Stop creating P4D leaves rather than teaching every walker about them, as commit 629db01c64ff ("riscv: Don't use PGD entries for the linear mapping") did for PGD leaves.

Fixes 3335068f8721 ("riscv: Use PUD/P4D/PGD pages for the linear mapping")
---
 arch/riscv/mm/init.c | 4 ----
 1 file changed, 4 deletions(-)
arch/riscv/mm/init.c +0 -4
index 070ee69eabb3..e1bcc3a16129 100644
@@ -717,10 +717,6 @@ static uintptr_t __meminit best_map_size(phys_addr_t pa, uintptr_t va, phys_addr
 	if (debug_pagealloc_enabled())
 		return PAGE_SIZE;
 
-	if (pgtable_l5_enabled() &&
-	    !(pa & (P4D_SIZE - 1)) && !(va & (P4D_SIZE - 1)) && size >= P4D_SIZE)
-		return P4D_SIZE;
-
 	if (pgtable_l4_enabled() &&
 	    !(pa & (PUD_SIZE - 1)) && !(va & (PUD_SIZE - 1)) && size >= PUD_SIZE)
 		return PUD_SIZE;
Signature · 1 line
2.53.0
#2 lore raw

RFC PATCH v2 2/54 riscv: test for Svnapot in pte_napot()

In reply to Mike Rapoport (Microsoft)

pte_napot() tests only bit 63 and relies on its callers to check that the CPU supports Svnapot.

On T-Head CPUs bit 63 is not the NAPOT bit: it is set in the non-cached I/O mappings (_PAGE_IO_THEAD).

pte_pfn() checks has_svnapot() before pte_napot(), but pte_leaf_size() does not. With CONFIG_RISCV_ISA_SVNAPOT=y on T-Head, a page of an I/O mapping looks like a NAPOT block and pte_leaf_size() derives its size from the alignment of its PFN. perf then reports a bogus page size for addresses in I/O mappings.

Check has_svnapot() in pte_napot() so that its callers don't have to, and drop the check that became redundant in pte_pfn().

Fixes e0fe5ab4192c ("riscv: Fix pte_leaf_size() for NAPOT")
---
 arch/riscv/include/asm/pgtable.h | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
arch/riscv/include/asm/pgtable.h +5 -5
index 2ebd5fa5adc5..1c1ba48315ed 100644
@@ -288,9 +288,9 @@ static __always_inline bool has_svnapot(void)
 	return riscv_has_extension_likely(RISCV_ISA_EXT_SVNAPOT);
 }
 
-static inline unsigned long pte_napot(pte_t pte)
+static inline bool pte_napot(pte_t pte)
 {
-	return pte_val(pte) & _PAGE_NAPOT;
+	return has_svnapot() && (pte_val(pte) & _PAGE_NAPOT);
 }
 
 static inline pte_t pte_mknapot(pte_t pte, unsigned int order)
@@ -306,9 +306,9 @@ static inline pte_t pte_mknapot(pte_t pte, unsigned int order)
 
 static __always_inline bool has_svnapot(void) { return false; }
 
-static inline unsigned long pte_napot(pte_t pte)
+static inline bool pte_napot(pte_t pte)
 {
-	return 0;
+	return false;
 }
 
 #endif /* CONFIG_RISCV_ISA_SVNAPOT */
@@ -318,7 +318,7 @@ static inline unsigned long pte_pfn(pte_t pte)
 {
 	unsigned long res  = __page_val_to_pfn(pte_val(pte));
 
-	if (has_svnapot() && pte_napot(pte))
+	if (pte_napot(pte))
 		res = res & (res - 1UL);
 
 	return res;
Signature · 1 line
2.53.0
#3 lore raw

RFC PATCH v2 3/54 s390/boot: parse boolean parameters like the kernel

In reply to Mike Rapoport (Microsoft)

The decompressor has a copy of kstrtobool() that takes only y/n, 1/0 and on/off. The kernel's kstrtobool() also takes true/false since 0d6ea3ac94ca ("lib/kstrtox.c: add "false"/"true" support to kstrtobool()") and enabled/disabled since ae5b3500856f ("kstrtox: add support for enabled and disabled in kstrtobool()").

The decompressor ignores these values, so "cmma=false" leaves CMMA enabled and "prot_virt=true" does not enable it.

Copy kstrtobool() from lib/kstrtox.c. This also adds the break after the on/off switch, which only replaces a fall through to the empty default case.

---
 arch/s390/boot/string.c | 9 +++++++++
 1 file changed, 9 insertions(+)
arch/s390/boot/string.c +9 -0
index e4ad196cb720..c12fee2670e3 100644
@@ -132,13 +132,21 @@ int kstrtobool(const char *s, bool *res)
 		return -EINVAL;
 
 	switch (s[0]) {
+	case 'e':
+	case 'E':
 	case 'y':
 	case 'Y':
+	case 't':
+	case 'T':
 	case '1':
 		*res = true;
 		return 0;
+	case 'd':
+	case 'D':
 	case 'n':
 	case 'N':
+	case 'f':
+	case 'F':
 	case '0':
 		*res = false;
 		return 0;
@@ -156,6 +164,7 @@ int kstrtobool(const char *s, bool *res)
 		default:
 			break;
 		}
+		break;
 	default:
 		break;
 	}
Signature · 1 line
2.53.0
#4 lore raw

RFC PATCH v2 4/54 s390/boot: stop parsing the command line at "--"

In reply to Mike Rapoport (Microsoft)

The kernel parses its parameters up to "--" and passes everything after it to init. The decompressor parses the whole command line, so an argument meant for init still takes effect in the decompressor if it has the name of a parameter the decompressor knows, like "mem=".

Stop at "--", like parse_args() does.

---
 arch/s390/boot/ipl_parm.c | 4 ++++
 1 file changed, 4 insertions(+)
arch/s390/boot/ipl_parm.c +4 -0
index 8bbd102fa50f..ed28ea2fc1d1 100644
@@ -268,6 +268,10 @@ void parse_boot_command_line(void)
 	while (*args) {
 		args = next_arg(args, &param, &val);
 
+		/* The arguments after "--" are for init */
+		if (!val && !strcmp(param, "--"))
+			break;
+
 		if (!strcmp(param, "mem") && val)
 			memory_limit = round_down(memparse(val, NULL), PAGE_SIZE);
 
Signature · 1 line
2.53.0
#5 lore raw

RFC PATCH v2 5/54 s390/boot: treat dashes and underscores alike in parameter names

In reply to Mike Rapoport (Microsoft)

Dashes and underscores are equivalent in the names of kernel parameters, and the kernel compares the names with parameq(). The decompressor uses strcmp(), so it ignores "relocate-lowcore" or "prot-virt=1".

Compare the names like parameq() does.

---
 arch/s390/boot/ipl_parm.c | 51 ++++++++++++++++++++++++++++++++---------------
 1 file changed, 35 insertions(+), 16 deletions(-)
arch/s390/boot/ipl_parm.c +35 -16
index ed28ea2fc1d1..ac4cf1ced71d 100644
@@ -255,6 +255,25 @@ static void modify_fac_list(char *str)
 	check_cleared_facilities();
 }
 
+static char dash2underscore(char c)
+{
+	if (c == '-')
+		return '_';
+	return c;
+}
+
+/* Dashes and underscores are equivalent in parameter names */
+static bool parameq(const char *a, const char *b)
+{
+	size_t i, n = strlen(a) + 1;
+
+	for (i = 0; i < n; i++) {
+		if (dash2underscore(a[i]) != dash2underscore(b[i]))
+			return false;
+	}
+	return true;
+}
+
 void parse_boot_command_line(void)
 {
 	char *param, *val;
@@ -272,15 +291,15 @@ void parse_boot_command_line(void)
 		if (!val && !strcmp(param, "--"))
 			break;
 
-		if (!strcmp(param, "mem") && val)
+		if (parameq(param, "mem") && val)
 			memory_limit = round_down(memparse(val, NULL), PAGE_SIZE);
 
-		if (!strcmp(param, "vmalloc") && val) {
+		if (parameq(param, "vmalloc") && val) {
 			vmalloc_size = round_up(memparse(val, NULL), _SEGMENT_SIZE);
 			vmalloc_size_set = 1;
 		}
 
-		if (!strcmp(param, "dfltcc") && val) {
+		if (parameq(param, "dfltcc") && val) {
 			if (!strcmp(val, "off"))
 				zlib_dfltcc_support = ZLIB_DFLTCC_DISABLED;
 			else if (!strcmp(val, "on"))
@@ -293,49 +312,49 @@ void parse_boot_command_line(void)
 				zlib_dfltcc_support = ZLIB_DFLTCC_FULL_DEBUG;
 		}
 
-		if (!strcmp(param, "facilities") && val)
+		if (parameq(param, "facilities") && val)
 			modify_fac_list(val);
 
-		if (!strcmp(param, "debug-alternative"))
+		if (parameq(param, "debug-alternative"))
 			alt_debug_setup(val);
 
-		if (!strcmp(param, "nokaslr"))
+		if (parameq(param, "nokaslr"))
 			__kaslr_enabled = 0;
 
-		if (!strcmp(param, "cmma")) {
+		if (parameq(param, "cmma")) {
 			rc = kstrtobool(val, &enabled);
 			if (!rc && !enabled)
 				cmma_flag = 0;
 		}
 
 #ifdef CONFIG_STACKPROTECTOR
-		if (!strcmp(param, "debug_stackprotector"))
+		if (parameq(param, "debug_stackprotector"))
 			stack_protector_debug = 1;
 #endif
 
 #if IS_ENABLED(CONFIG_KVM)
-		if (!strcmp(param, "prot_virt")) {
+		if (parameq(param, "prot_virt")) {
 			rc = kstrtobool(val, &enabled);
 			if (!rc && enabled)
 				prot_virt_host = 1;
 		}
 #endif
-		if (!strcmp(param, "relocate_lowcore") && test_facility(193))
+		if (parameq(param, "relocate_lowcore") && test_facility(193))
 			set_machine_feature(MFEATURE_LOWCORE);
-		if (!strcmp(param, "earlyprintk"))
+		if (parameq(param, "earlyprintk"))
 			boot_earlyprintk = true;
-		if (!strcmp(param, "debug"))
+		if (parameq(param, "debug"))
 			boot_console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
-		if (!strcmp(param, "bootdebug")) {
+		if (parameq(param, "bootdebug")) {
 			bootdebug = true;
 			if (val)
 				strscpy(bootdebug_filter, val);
 		}
-		if (!strcmp(param, "quiet"))
+		if (parameq(param, "quiet"))
 			boot_console_loglevel = CONSOLE_LOGLEVEL_QUIET;
-		if (!strcmp(param, "ignore_loglevel"))
+		if (parameq(param, "ignore_loglevel"))
 			boot_ignore_loglevel = true;
-		if (!strcmp(param, "loglevel")) {
+		if (parameq(param, "loglevel")) {
 			boot_console_loglevel = simple_strtoull(val, NULL, 10);
 			if (boot_console_loglevel < CONSOLE_LOGLEVEL_MIN)
 				boot_console_loglevel = CONSOLE_LOGLEVEL_MIN;
Signature · 1 line
2.53.0
#6 lore raw

RFC PATCH v2 6/54 x86/mm/pat: don't count kernel image splits as direct map splits

In reply to Mike Rapoport (Microsoft)

The DirectMap lines of /proc/meminfo count only the direct map. The kernel image mapping is never added to them.

CPA counts a split if virt_addr_valid() accepts the address and its pfn is mapped in the direct map. On 64-bit virt_addr_valid() accepts the kernel image mapping too, and its pfns are in the direct map, so the splits of the kernel image mapping are counted as well.

Such splits can happen when mark_rodata_ro() updates the protections of the kernel image.

Each split of the kernel image mapping moves 2M from DirectMap2M to DirectMap4k, although the direct map does not change.

Count splits and collapses only for addresses in the direct map.

Fixes 8eb5779f6b9c ("x86, mm: use pfn_range_is_mapped() with CPA")
---
 arch/x86/mm/pat/set_memory.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
arch/x86/mm/pat/set_memory.c +7 -8
index 2ff37ff1cecd..42f27d60adf3 100644
@@ -1190,12 +1190,9 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc, lpaddr += lpinc)
 		split_set_pte(cpa, pbase + i, pfn, ref_prot, lpaddr, lpinc);
 
-	if (virt_addr_valid(address)) {
-		unsigned long pfn = PFN_DOWN(__pa(address));
-
-		if (pfn_range_is_mapped(pfn, pfn + 1))
-			split_page_count(level);
-	}
+	if (within(address, PAGE_OFFSET,
+		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
+		split_page_count(level);
 
 	/*
 	 * Install the new, split up pagetable.
@@ -1314,7 +1311,8 @@ static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
 		}
 	}
 
-	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
+	if (within(addr, PAGE_OFFSET,
+		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
 		collapse_page_count(PG_LEVEL_2M);
 
 	return 1;
@@ -1361,7 +1359,8 @@ static int collapse_pud_page(pud_t *pud, unsigned long addr,
 	list_add(&page_ptdesc(pud_page(*pud))->pt_list, pgtables);
 	set_pud(pud, pfn_pud(pfn, pmd_pgprot(first)));
 
-	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
+	if (within(addr, PAGE_OFFSET,
+		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
 		collapse_page_count(PG_LEVEL_1G);
 
 	return 1;
Signature · 1 line
2.53.0
#7 lore raw

RFC PATCH v2 7/54 x86/mm/pat: drop KERN_WARNING from the WARN() in __cpa_process_fault()

In reply to Mike Rapoport (Microsoft)

WARN() prints its message at the warning level, so the KERN_WARNING in the format string is redundant.

Drop it.

---
 arch/x86/mm/pat/set_memory.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/mm/pat/set_memory.c +1 -1
index 42f27d60adf3..db41f94f2355 100644
@@ -1835,7 +1835,7 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
 		/* Faults in the highmap are OK, so do not warn: */
 		return -EFAULT;
 	} else {
-		WARN(1, KERN_WARNING "CPA: called for zero pte. "
+		WARN(1, "CPA: called for zero pte. "
 			"vaddr = %lx cpa->addr = %lx\n", vaddr,
 			cpa->addr);
 
Signature · 1 line
2.53.0
#8 lore raw

RFC PATCH v2 8/54 x86/mm/pat: fail a split at an unexpected level with -EINVAL

In reply to Mike Rapoport (Microsoft)

__split_large_page() returns 1 when it encounters an unexpected level, or when another CPU split the large page first.

split_large_page() frees the page table and returns 0 in both cases, and __change_page_attr() looks the address up and tries again. For an unexpected level it tries forever.

Getting there would be a bug, because no mappings ever use P4D leaves. Still, a level CPA cannot split should fail the request rather than loop.

Return -EINVAL for an unexpected level and pass it up to the caller.

---
 arch/x86/mm/pat/set_memory.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/x86/mm/pat/set_memory.c +6 -2
index db41f94f2355..217c739371ee 100644
@@ -1178,7 +1178,7 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 		break;
 
 	default:
-		return 1;
+		return -EINVAL;
 	}
 
 	ref_prot = pgprot_clear_protnone_bits(ref_prot);
@@ -1230,6 +1230,7 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 			    unsigned long address)
 {
 	pte_t *pte;
+	int ret;
 
 	spin_unlock(&cpa_lock);
 	if (cpa->init_mm_read_locked)
@@ -1241,8 +1242,11 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 	if (!pte)
 		return -ENOMEM;
 
-	if (__split_large_page(cpa, kpte, address, pte))
+	ret = __split_large_page(cpa, kpte, address, pte);
+	if (ret)
 		pte_free_kernel(&init_mm, pte);
+	if (ret < 0)
+		return ret;
 
 	return 0;
 }
Signature · 1 line
2.53.0
#9 lore raw

RFC PATCH v2 9/54 x86/mm/pat: separate CPA request flags from internal state

In reply to Mike Rapoport (Microsoft)

struct cpa_data has a mixture of flags stored in the flags field and in several bitfields, such as .force_split and .force_flush_all.

The use of plain flags and bitfields for caller-requested behaviour and internal state management is inconsistent: .force_split is a caller request, while the other bitfields are managed internally by CPA functions.

The same is true for CPA_ flags: CPA_FLUSHTLB is set internally when a TLB flush is required, while the other flags express the desired behaviour.

Keep caller requests in cpa_data.flags and move internal bookkeeping to cpa_data.state. Replace the bitfields with CPA_ flags.

To distinguish requests from the state prefix the request flags with CPA_REQ_ and the state flags with CPA_ST_.

Pass forced splitting as a request flag and track alias recursion in state instead of passing a separate primary argument. Preserve the existing locking, protection and flushing behaviour.

Since all the defines are updated, also change their values to ease the upcoming changes.

No functional change intended.

---
 arch/x86/mm/pat/set_memory.c | 167 ++++++++++++++++++++++---------------------
 1 file changed, 86 insertions(+), 81 deletions(-)
arch/x86/mm/pat/set_memory.c +86 -81
index 217c739371ee..87c7c7934b42 100644
@@ -48,10 +48,7 @@ struct cpa_data {
 	unsigned long	curpage;
 	unsigned long	pfn;
 	unsigned int	flags;
-	unsigned int	force_split		: 1,
-			force_static_prot	: 1,
-			force_flush_all		: 1,
-			init_mm_read_locked	: 1;
+	unsigned int	state;
 	struct page	**pages;
 };
 
@@ -70,11 +67,19 @@ static const int cpa_warn_level = CPA_PROTECT;
  */
 static DEFINE_SPINLOCK(cpa_lock);
 
-#define CPA_FLUSHTLB		0x01
-#define CPA_PAGES_ARRAY		0x04
-#define CPA_NO_CHECK_ALIAS	0x08 /* Do not search for aliases */
-#define CPA_COLLAPSE		0x10 /* try to collapse large pages */
-#define CPA_DEBUG_PAGEALLOC	0x20
+/* cpa_data::flags */
+#define CPA_REQ_NO_CHECK_ALIAS	0x01 /* Do not search for aliases */
+#define CPA_REQ_COLLAPSE	0x02 /* try to collapse large pages */
+#define CPA_REQ_SPLIT		0x04 /* split large pages */
+#define CPA_REQ_PAGES_ARRAY	0x08
+#define CPA_REQ_DEBUG_PAGEALLOC	0x10
+
+/* cpa_data::state */
+#define CPA_ST_FLUSHTLB		0x01 /* the TLB needs a flush */
+#define CPA_ST_FLUSH_ALL	0x02 /* flush the entire TLB */
+#define CPA_ST_ALIAS		0x04 /* the request is for an alias */
+#define CPA_ST_STATIC_PROT	0x08 /* enforce static protections in a split */
+#define CPA_ST_INIT_MM_LOCKED	0x10 /* init_mm's mmap lock is held */
 
 static inline pgprot_t cachemode2pgprot(enum page_cache_mode pcm)
 {
@@ -305,7 +310,7 @@ static inline unsigned long fix_addr(unsigned long addr)
 
 static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
 {
-	if (cpa->flags & CPA_PAGES_ARRAY) {
+	if (cpa->flags & CPA_REQ_PAGES_ARRAY) {
 		struct page *page = cpa->pages[idx];
 
 		if (unlikely(PageHighMem(page)))
@@ -415,7 +420,7 @@ static void cpa_collapse_large_pages(struct cpa_data *cpa)
 	int collapsed = 0;
 	int i;
 
-	if (cpa->flags & CPA_PAGES_ARRAY) {
+	if (cpa->flags & CPA_REQ_PAGES_ARRAY) {
 		for (i = 0; i < cpa->numpages; i++)
 			collapsed += collapse_large_pages(__cpa_addr(cpa, i),
 							  &pgtables);
@@ -458,7 +463,8 @@ static void cpa_flush(struct cpa_data *cpa, int cache)
 		return;
 	}
 
-	if (cpa->force_flush_all || cpa->numpages > tlb_single_page_flush_ceiling)
+	if ((cpa->state & CPA_ST_FLUSH_ALL) ||
+	    cpa->numpages > tlb_single_page_flush_ceiling)
 		flush_tlb_all();
 	else
 		on_each_cpu(__cpa_flush_tlb, cpa, 1);
@@ -1027,7 +1033,7 @@ static int __should_split_large_page(pte_t *kpte, unsigned long address,
 		 * Split the large page and tell the split code to
 		 * enforce static protections.
 		 */
-		cpa->force_static_prot = 1;
+		cpa->state |= CPA_ST_STATIC_PROT;
 		return 1;
 	}
 
@@ -1076,7 +1082,7 @@ static int __should_split_large_page(pte_t *kpte, unsigned long address,
 	/* All checks passed. Update the large page mapping. */
 	new_pte = pfn_pte(old_pfn, new_prot);
 	__set_pmd_pte(kpte, address, new_pte);
-	cpa->flags |= CPA_FLUSHTLB;
+	cpa->state |= CPA_ST_FLUSHTLB;
 	cpa_inc_lp_preserved(level);
 	return 0;
 }
@@ -1084,7 +1090,7 @@ static int __should_split_large_page(pte_t *kpte, unsigned long address,
 static int should_split_large_page(pte_t *kpte, unsigned long address,
 				   struct cpa_data *cpa)
 {
-	if (cpa->force_split)
+	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
 
 	guard(spinlock)(&pgd_lock);
@@ -1102,7 +1108,7 @@ static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
 	 * If should_split_large_page() discovered an inconsistent mapping,
 	 * remove the invalid protection in the split mapping.
 	 */
-	if (!cpa->force_static_prot)
+	if (!(cpa->state & CPA_ST_STATIC_PROT))
 		goto set;
 
 	/* Hand in lpsize = 0 to enforce the protection mechanism */
@@ -1233,10 +1239,10 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 	int ret;
 
 	spin_unlock(&cpa_lock);
-	if (cpa->init_mm_read_locked)
+	if (cpa->state & CPA_ST_INIT_MM_LOCKED)
 		mmap_read_unlock(&init_mm);
 	pte = pte_alloc_one_kernel(&init_mm);
-	if (cpa->init_mm_read_locked)
+	if (cpa->state & CPA_ST_INIT_MM_LOCKED)
 		mmap_read_lock(&init_mm);
 	spin_lock(&cpa_lock);
 	if (!pte)
@@ -1802,8 +1808,7 @@ static int populate_pgd(struct cpa_data *cpa, unsigned long addr)
 	return 0;
 }
 
-static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
-			       int primary)
+static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr)
 {
 	if (cpa->pgd) {
 		/*
@@ -1817,7 +1822,7 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
 	/*
 	 * Ignore all non primary paths.
 	 */
-	if (!primary) {
+	if (cpa->state & CPA_ST_ALIAS) {
 		cpa->numpages = 1;
 		return 0;
 	}
@@ -1847,7 +1852,7 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
 	}
 }
 
-static int __change_page_attr(struct cpa_data *cpa, int primary)
+static int __change_page_attr(struct cpa_data *cpa)
 {
 	unsigned long address;
 	int do_split, err;
@@ -1859,11 +1864,11 @@ static int __change_page_attr(struct cpa_data *cpa, int primary)
 repeat:
 	kpte = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
 	if (!kpte)
-		return __cpa_process_fault(cpa, address, primary);
+		return __cpa_process_fault(cpa, address);
 
 	old_pte = *kpte;
 	if (pte_none(old_pte))
-		return __cpa_process_fault(cpa, address, primary);
+		return __cpa_process_fault(cpa, address);
 
 	if (level == PG_LEVEL_4K) {
 		pte_t new_pte;
@@ -1896,7 +1901,7 @@ static int __change_page_attr(struct cpa_data *cpa, int primary)
 		 */
 		if (pte_val(old_pte) != pte_val(new_pte)) {
 			set_pte_atomic(kpte, new_pte);
-			cpa->flags |= CPA_FLUSHTLB;
+			cpa->state |= CPA_ST_FLUSHTLB;
 		}
 		cpa->numpages = 1;
 		return 0;
@@ -1925,7 +1930,7 @@ static int __change_page_attr(struct cpa_data *cpa, int primary)
 	return err;
 }
 
-static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary);
+static int __change_page_attr_set_clr(struct cpa_data *cpa);
 
 /*
  * Check the directmap and "high kernel map" 'aliases'.
@@ -1949,7 +1954,9 @@ static int cpa_process_alias(struct cpa_data *cpa)
 
 		alias_cpa = *cpa;
 		alias_cpa.addr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
-		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_FLUSHTLB);
+		alias_cpa.flags &= ~CPA_REQ_PAGES_ARRAY;
+		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
+		alias_cpa.state |= CPA_ST_ALIAS;
 		alias_cpa.curpage = 0;
 
 		/* Directmap always has NX set, do not modify. */
@@ -1958,11 +1965,9 @@ static int cpa_process_alias(struct cpa_data *cpa)
 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
 		}
 
-		ret = __change_page_attr_set_clr(&alias_cpa, 0);
-		if (alias_cpa.flags & CPA_FLUSHTLB) {
-			cpa->flags |= CPA_FLUSHTLB;
-			cpa->force_flush_all = 1;
-		}
+		ret = __change_page_attr_set_clr(&alias_cpa);
+		if (alias_cpa.state & CPA_ST_FLUSHTLB)
+			cpa->state |= CPA_ST_FLUSHTLB | CPA_ST_FLUSH_ALL;
 		if (ret)
 			return ret;
 	}
@@ -1978,7 +1983,9 @@ static int cpa_process_alias(struct cpa_data *cpa)
 		alias_cpa = *cpa;
 		alias_cpa.addr = (cpa->pfn << PAGE_SHIFT) +
 				 __START_KERNEL_map - phys_base;
-		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_FLUSHTLB);
+		alias_cpa.flags &= ~CPA_REQ_PAGES_ARRAY;
+		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
+		alias_cpa.state |= CPA_ST_ALIAS;
 		alias_cpa.curpage = 0;
 
 		/*
@@ -1994,18 +2001,16 @@ static int cpa_process_alias(struct cpa_data *cpa)
 		 * The high mapping range is imprecise, so ignore the
 		 * return value.
 		 */
-		__change_page_attr_set_clr(&alias_cpa, 0);
-		if (alias_cpa.flags & CPA_FLUSHTLB) {
-			cpa->flags |= CPA_FLUSHTLB;
-			cpa->force_flush_all = 1;
-		}
+		__change_page_attr_set_clr(&alias_cpa);
+		if (alias_cpa.state & CPA_ST_FLUSHTLB)
+			cpa->state |= CPA_ST_FLUSHTLB | CPA_ST_FLUSH_ALL;
 	}
 #endif
 
 	return 0;
 }
 
-static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
+static int __change_page_attr_set_clr(struct cpa_data *cpa)
 {
 	unsigned long numpages = cpa->numpages;
 	unsigned long rempages = numpages;
@@ -2016,7 +2021,7 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
 	 * No changes, easy!
 	 */
 	if (!(pgprot_val(cpa->mask_set) | pgprot_val(cpa->mask_clr)) &&
-	    !cpa->force_split)
+	    !(cpa->flags & CPA_REQ_SPLIT))
 		return ret;
 
 	/*
@@ -2039,7 +2044,7 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
 	 *
 	 * Therefore, it is safe to not take cpa_lock.
 	 */
-	if (debug_pagealloc_enabled() && (cpa->flags & CPA_DEBUG_PAGEALLOC))
+	if (debug_pagealloc_enabled() && (cpa->flags & CPA_REQ_DEBUG_PAGEALLOC))
 		lock = false;
 
 	while (rempages) {
@@ -2049,19 +2054,20 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
 		 */
 		cpa->numpages = rempages;
 		/* for array changes, we can't use large page */
-		if (cpa->flags & CPA_PAGES_ARRAY)
+		if (cpa->flags & CPA_REQ_PAGES_ARRAY)
 			cpa->numpages = 1;
 
 		if (lock) {
 			guard(spinlock)(&cpa_lock);
-			ret = __change_page_attr(cpa, primary);
+			ret = __change_page_attr(cpa);
 		} else {
-			ret = __change_page_attr(cpa, primary);
+			ret = __change_page_attr(cpa);
 		}
 		if (ret)
 			goto out;
 
-		if (primary && !(cpa->flags & CPA_NO_CHECK_ALIAS)) {
+		if (!(cpa->state & CPA_ST_ALIAS) &&
+		    !(cpa->flags & CPA_REQ_NO_CHECK_ALIAS)) {
 			ret = cpa_process_alias(cpa);
 			if (ret)
 				goto out;
@@ -2088,8 +2094,7 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
 
 static int change_page_attr_set_clr(unsigned long addr, int numpages,
 				    pgprot_t mask_set, pgprot_t mask_clr,
-				    int force_split, int in_flag,
-				    struct page **pages)
+				    int in_flag, struct page **pages)
 {
 	struct cpa_data cpa;
 	int ret, cache;
@@ -2102,13 +2107,14 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	 */
 	mask_set = canon_pgprot(mask_set);
 
-	if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) && !force_split)
+	if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) &&
+	    !(in_flag & CPA_REQ_SPLIT))
 		return 0;
 
 	/* Ensure we are PAGE_SIZE aligned */
-	if (!(in_flag & CPA_PAGES_ARRAY)) {
+	if (!(in_flag & CPA_REQ_PAGES_ARRAY)) {
 		/*
-		 * in_flag of CPA_PAGES_ARRAY implies it is aligned.
+		 * in_flag of CPA_REQ_PAGES_ARRAY implies it is aligned.
 		 * No need to check in that case
 		 */
 		if (addr & ~PAGE_MASK) {
@@ -2132,18 +2138,17 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	cpa.mask_clr = mask_clr;
 	cpa.flags = in_flag;
 	cpa.curpage = 0;
-	cpa.force_split = force_split;
 
 	/* Avoid race with concurrent CPA collapse. */
-	cpa.init_mm_read_locked = true;
+	cpa.state = CPA_ST_INIT_MM_LOCKED;
 	scoped_guard(mmap_read_lock, &init_mm)
-		ret = __change_page_attr_set_clr(&cpa, 1);
-	cpa.init_mm_read_locked = false;
+		ret = __change_page_attr_set_clr(&cpa);
+	cpa.state &= ~CPA_ST_INIT_MM_LOCKED;
 
 	/*
 	 * Check whether we really changed something:
 	 */
-	if (!(cpa.flags & CPA_FLUSHTLB))
+	if (!(cpa.state & CPA_ST_FLUSHTLB))
 		goto out;
 
 	/*
@@ -2156,14 +2161,14 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	 * On error; flush everything to be sure.
 	 */
 	if (ret)
-		cpa.force_flush_all = 1;
+		cpa.state |= CPA_ST_FLUSH_ALL;
 
 	cpa_flush(&cpa, cache);
 
 	if (ret)
 		goto out;
 
-	if (!(cpa.flags & CPA_COLLAPSE))
+	if (!(cpa.flags & CPA_REQ_COLLAPSE))
 		goto out;
 
 	/*
@@ -2184,28 +2189,28 @@ static inline int change_page_attr_set(unsigned long addr, int numpages,
 				       pgprot_t mask)
 {
 	return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
-					0, NULL);
+					NULL);
 }
 
 static inline int change_page_attr_clear(unsigned long addr, int numpages,
 					 pgprot_t mask)
 {
 	return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
-					0, NULL);
+					NULL);
 }
 
 static inline int cpa_set_pages_array(struct page **pages, int numpages,
 				       pgprot_t mask)
 {
-	return change_page_attr_set_clr(0, numpages, mask, __pgprot(0), 0,
-		CPA_PAGES_ARRAY, pages);
+	return change_page_attr_set_clr(0, numpages, mask, __pgprot(0),
+					CPA_REQ_PAGES_ARRAY, pages);
 }
 
 static inline int cpa_clear_pages_array(struct page **pages, int numpages,
 					 pgprot_t mask)
 {
-	return change_page_attr_set_clr(0, numpages, __pgprot(0), mask, 0,
-		CPA_PAGES_ARRAY, pages);
+	return change_page_attr_set_clr(0, numpages, __pgprot(0), mask,
+					CPA_REQ_PAGES_ARRAY, pages);
 }
 
 int _set_memory_uc(unsigned long addr, int numpages)
@@ -2255,7 +2260,7 @@ int _set_memory_wc(unsigned long addr, int numpages)
 		ret = change_page_attr_set_clr(addr, numpages,
 					       cachemode2pgprot(_PAGE_CACHE_MODE_WC),
 					       __pgprot(_PAGE_CACHE_MASK),
-					       0, 0, NULL);
+					       0, NULL);
 	}
 	return ret;
 }
@@ -2373,8 +2378,8 @@ int set_memory_rox(unsigned long addr, int numpages)
 	if (__supported_pte_mask & _PAGE_NX)
 		clr.pgprot |= _PAGE_NX;
 
-	return change_page_attr_set_clr(addr, numpages, __pgprot(0), clr, 0,
-					CPA_COLLAPSE, NULL);
+	return change_page_attr_set_clr(addr, numpages, __pgprot(0), clr,
+					CPA_REQ_COLLAPSE, NULL);
 }
 
 int set_memory_rw(unsigned long addr, int numpages)
@@ -2390,8 +2395,8 @@ int set_memory_np(unsigned long addr, int numpages)
 int set_memory_np_noalias(unsigned long addr, int numpages)
 {
 	return change_page_attr_set_clr(addr, numpages, __pgprot(0),
-					__pgprot(_PAGE_PRESENT), 0,
-					CPA_NO_CHECK_ALIAS, NULL);
+					__pgprot(_PAGE_PRESENT),
+					CPA_REQ_NO_CHECK_ALIAS, NULL);
 }
 
 int set_memory_p(unsigned long addr, int numpages)
@@ -2403,7 +2408,7 @@ int set_memory_4k(unsigned long addr, int numpages)
 {
 	return change_page_attr_set_clr(addr, numpages,
 					__pgprot(_PAGE_KERNEL_4K),
-					__pgprot(0), 1, 0, NULL);
+					__pgprot(0), CPA_REQ_SPLIT, NULL);
 }
 
 int set_memory_nonglobal(unsigned long addr, int numpages)
@@ -2449,7 +2454,7 @@ static int __set_memory_enc_pgtable(unsigned long addr, int numpages, bool enc)
 	if (ret)
 		goto vmm_fail;
 
-	ret = __change_page_attr_set_clr(&cpa, 1);
+	ret = __change_page_attr_set_clr(&cpa);
 
 	/*
 	 * After changing the encryption attribute, we need to flush TLBs again
@@ -2571,7 +2576,7 @@ static int _set_pages_array(struct page **pages, int numpages,
 					       cachemode2pgprot(
 						_PAGE_CACHE_MODE_WC),
 					       __pgprot(_PAGE_CACHE_MASK),
-					       0, CPA_PAGES_ARRAY, pages);
+					       CPA_REQ_PAGES_ARRAY, pages);
 	if (ret)
 		goto err_out;
 	return 0; /* Success */
@@ -2653,7 +2658,7 @@ static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags
 				.numpages = numpages,
 				.mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
 				.mask_clr = __pgprot(0),
-				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
+				.flags = CPA_REQ_NO_CHECK_ALIAS | cpa_flags };
 
 	/*
 	 * No alias checking needed for setting present flag. otherwise,
@@ -2661,7 +2666,7 @@ static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags
 	 * mappings (this adds to complexity if we want to do this from
 	 * atomic context especially). Let's keep it simple!
 	 */
-	return __change_page_attr_set_clr(&cpa, 1);
+	return __change_page_attr_set_clr(&cpa);
 }
 
 static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flags)
@@ -2671,7 +2676,7 @@ static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flag
 				.numpages = numpages,
 				.mask_set = __pgprot(0),
 				.mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
-				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
+				.flags = CPA_REQ_NO_CHECK_ALIAS | cpa_flags };
 
 	/*
 	 * No alias checking needed for setting not present flag. otherwise,
@@ -2679,7 +2684,7 @@ static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flag
 	 * mappings (this adds to complexity if we want to do this from
 	 * atomic context especially). Let's keep it simple!
 	 */
-	return __change_page_attr_set_clr(&cpa, 1);
+	return __change_page_attr_set_clr(&cpa);
 }
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr)
@@ -2708,9 +2713,9 @@ void __kernel_map_pages(struct page *page, int numpages, int enable)
 	 * and hence no memory allocations during large page split.
 	 */
 	if (enable)
-		__set_pages_p(page, numpages, CPA_DEBUG_PAGEALLOC);
+		__set_pages_p(page, numpages, CPA_REQ_DEBUG_PAGEALLOC);
 	else
-		__set_pages_np(page, numpages, CPA_DEBUG_PAGEALLOC);
+		__set_pages_np(page, numpages, CPA_REQ_DEBUG_PAGEALLOC);
 
 	/*
 	 * We should perform an IPI and flush all tlbs, but that can
@@ -2758,7 +2763,7 @@ int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
 		.numpages = numpages,
 		.mask_set = __pgprot(0),
 		.mask_clr = __pgprot(~page_flags & (_PAGE_NX|_PAGE_RW|_PAGE_DIRTY)),
-		.flags = CPA_NO_CHECK_ALIAS,
+		.flags = CPA_REQ_NO_CHECK_ALIAS,
 	};
 
 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
@@ -2771,7 +2776,7 @@ int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
 
 	cpa.mask_set = __pgprot(_PAGE_PRESENT | page_flags);
 
-	retval = __change_page_attr_set_clr(&cpa, 1);
+	retval = __change_page_attr_set_clr(&cpa);
 	__flush_tlb_all();
 
 out:
@@ -2801,12 +2806,12 @@ int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
 		.numpages	= numpages,
 		.mask_set	= __pgprot(0),
 		.mask_clr	= __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
-		.flags		= CPA_NO_CHECK_ALIAS,
+		.flags		= CPA_REQ_NO_CHECK_ALIAS,
 	};
 
 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
 
-	retval = __change_page_attr_set_clr(&cpa, 1);
+	retval = __change_page_attr_set_clr(&cpa);
 	__flush_tlb_all();
 
 	return retval;
Signature · 1 line
2.53.0
#10 lore raw

RFC PATCH v2 10/54 x86/mm/pat: stop using CPA for debug_pagealloc

In reply to Mike Rapoport (Microsoft)

With debug_pagealloc, the page allocator unmaps pages from the direct map when it frees them and maps them back when it allocates them, in whatever context it runs. It does that with CPA, in a mode of its own.

That mode is the one exception in the locking of CPA: it skips cpa_lock, and every request checks for it. The exception is easy to get wrong:
commit 5fce67641a3e ("x86/mm/pat: Don't gate cpa_lock on debug_pagealloc_enabled()") dropped it, and commit 7da514d819a0 ("x86/mm:
Fix and document DEBUG_PAGEALLOC") had to bring it back.

With debug_pagealloc enabled the direct map is mapped with 4K pages, so mapping or unmapping a page always updates a single existing PTE.

Update the PTEs with apply_to_existing_page_range(), like powerpc and riscv do, and drop the lockless mode from CPA.

Every request now takes cpa_lock, so cpa_inc_4k_install() does not need data_race() any more.

---
 arch/x86/mm/pat/set_memory.c | 77 +++++++++++++++++++-------------------------
 1 file changed, 33 insertions(+), 44 deletions(-)
arch/x86/mm/pat/set_memory.c +33 -44
index 87c7c7934b42..c3af82788879 100644
@@ -72,7 +72,6 @@ static DEFINE_SPINLOCK(cpa_lock);
 #define CPA_REQ_COLLAPSE	0x02 /* try to collapse large pages */
 #define CPA_REQ_SPLIT		0x04 /* split large pages */
 #define CPA_REQ_PAGES_ARRAY	0x08
-#define CPA_REQ_DEBUG_PAGEALLOC	0x10
 
 /* cpa_data::state */
 #define CPA_ST_FLUSHTLB		0x01 /* the TLB needs a flush */
@@ -165,7 +164,7 @@ static inline void cpa_inc_2m_checked(void)
 
 static inline void cpa_inc_4k_install(void)
 {
-	data_race(cpa_4k_install++);
+	cpa_4k_install++;
 }
 
 static inline void cpa_inc_lp_sameprot(int level)
@@ -2014,7 +2013,6 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 {
 	unsigned long numpages = cpa->numpages;
 	unsigned long rempages = numpages;
-	bool lock = true;
 	int ret = 0;
 
 	/*
@@ -2024,29 +2022,6 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 	    !(cpa->flags & CPA_REQ_SPLIT))
 		return ret;
 
-	/*
-	 * DEBUG_PAGEALLOC is special; it is called from any context the
-	 * page-allocator is, which violates the normal cpa_lock locking
-	 * rules.
-	 *
-	 * However, since it is part of the page-allocator, things are still
-	 * properly serialized by the page-allocator locking and the fact that
-	 * when a page is owned by the page-allocator, it isn't owned by
-	 * anybody else. That is, you *SHOULD NOT* be calling cpa() on memory
-	 * that isn't allocated.
-	 *
-	 * Additionally, DEBUG_PAGEALLOC ensures (per probe_page_size_mask())
-	 * that the kernel mapping is 4k pages, therefore there are no large
-	 * pages to split/collapse.
-	 *
-	 * Furthermore, the page-allocator strictly manages pages that
-	 * *exist*, avoiding pgd_lock.
-	 *
-	 * Therefore, it is safe to not take cpa_lock.
-	 */
-	if (debug_pagealloc_enabled() && (cpa->flags & CPA_REQ_DEBUG_PAGEALLOC))
-		lock = false;
-
 	while (rempages) {
 		/*
 		 * Store the remaining nr of pages for the large page
@@ -2057,12 +2032,8 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 		if (cpa->flags & CPA_REQ_PAGES_ARRAY)
 			cpa->numpages = 1;
 
-		if (lock) {
-			guard(spinlock)(&cpa_lock);
-			ret = __change_page_attr(cpa);
-		} else {
+		scoped_guard(spinlock, &cpa_lock)
 			ret = __change_page_attr(cpa);
-		}
 		if (ret)
 			goto out;
 
@@ -2651,14 +2622,14 @@ int set_pages_rw(struct page *page, int numpages)
 	return set_memory_rw(addr, numpages);
 }
 
-static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags)
+static int __set_pages_p(struct page *page, int numpages)
 {
 	struct cpa_data cpa = { .addr = (unsigned long)page_address(page),
 				.pgd = NULL,
 				.numpages = numpages,
 				.mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
 				.mask_clr = __pgprot(0),
-				.flags = CPA_REQ_NO_CHECK_ALIAS | cpa_flags };
+				.flags = CPA_REQ_NO_CHECK_ALIAS };
 
 	/*
 	 * No alias checking needed for setting present flag. otherwise,
@@ -2669,14 +2640,14 @@ static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags
 	return __change_page_attr_set_clr(&cpa);
 }
 
-static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flags)
+static int __set_pages_np(struct page *page, int numpages)
 {
 	struct cpa_data cpa = { .addr = (unsigned long)page_address(page),
 				.pgd = NULL,
 				.numpages = numpages,
 				.mask_set = __pgprot(0),
 				.mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
-				.flags = CPA_REQ_NO_CHECK_ALIAS | cpa_flags };
+				.flags = CPA_REQ_NO_CHECK_ALIAS };
 
 	/*
 	 * No alias checking needed for setting not present flag. otherwise,
@@ -2689,17 +2660,35 @@ static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flag
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr)
 {
-	return __set_pages_np(page, nr, 0);
+	return __set_pages_np(page, nr);
 }
 
 int set_direct_map_default_noflush(struct page *page, unsigned int nr)
 {
-	return __set_pages_p(page, nr, 0);
+	return __set_pages_p(page, nr);
 }
 
 #ifdef CONFIG_DEBUG_PAGEALLOC
+static int kernel_map_pte(pte_t *ptep, unsigned long addr, void *data)
+{
+	int *enable = data;
+	pte_t pte = ptep_get(ptep);
+	pgprot_t prot = pte_pgprot(pte);
+
+	if (*enable)
+		pgprot_val(prot) |= _PAGE_PRESENT | _PAGE_RW;
+	else
+		pgprot_val(prot) &= ~(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY);
+	prot = pgprot_clear_protnone_bits(prot);
+	set_pte_atomic(ptep, pfn_pte(pte_pfn(pte), prot));
+
+	return 0;
+}
+
 void __kernel_map_pages(struct page *page, int numpages, int enable)
 {
+	unsigned long addr = (unsigned long)page_address(page);
+
 	if (PageHighMem(page))
 		return;
 	if (!enable) {
@@ -2708,14 +2697,14 @@ void __kernel_map_pages(struct page *page, int numpages, int enable)
 	}
 
 	/*
-	 * The return value is ignored as the calls cannot fail.
-	 * Large pages for identity mappings are not used at boot time
-	 * and hence no memory allocations during large page split.
+	 * This runs in any context the page allocator does, without locks.
+	 * The allocator owns these pages, so nothing else changes their PTEs,
+	 * and with debug_pagealloc the direct map has only 4K pages (see
+	 * probe_page_size_mask()), so their page tables are never split or
+	 * collapsed.
 	 */
-	if (enable)
-		__set_pages_p(page, numpages, CPA_REQ_DEBUG_PAGEALLOC);
-	else
-		__set_pages_np(page, numpages, CPA_REQ_DEBUG_PAGEALLOC);
+	apply_to_existing_page_range(&init_mm, addr, numpages * PAGE_SIZE,
+				     kernel_map_pte, &enable);
 
 	/*
 	 * We should perform an IPI and flush all tlbs, but that can
Signature · 1 line
2.53.0
#11 lore raw

RFC PATCH v2 11/54 x86/mm/pat: drop the init_mm read lock from change_page_attr_set_clr()

In reply to Mike Rapoport (Microsoft)

change_page_attr_set_clr() holds the init_mm read lock so that a collapse of large pages, which holds the write lock, cannot free a page table under a CPA lookup.

Since commit 1aac65f3e651 ("x86/mm/pat: Take cpa_lock around large-page collapse") the collapse holds cpa_lock as well, and with debug_pagealloc no longer using CPA, cpa_lock is enough to synchronize all CPA operations.

The only thing mmap_read_lock() adds is keeping out a concurrent ptdump.

A ptdump racing with any CPA operation except collapse is safe: only a collapse frees page tables, and a split replaces a leaf with a complete page table. The only difference without mmap_read_lock() in CPA is that ptdump may show some entries before and some after the change.

Collapse, though, must keep the mmap_write_lock() to ensure ptdump and text poking are not accessing page tables the collapse frees.

Remove mmap_read_lock() and CPA_ST_INIT_MM_LOCKED from CPA operations to simplify its locking model.

Update the comments of cpa_lock and of the mmap_write_lock() around the collapse to clearly state what they serialize.

---
 arch/x86/mm/pat/set_memory.c | 26 +++++++++-----------------
 1 file changed, 9 insertions(+), 17 deletions(-)
arch/x86/mm/pat/set_memory.c +9 -17
index c3af82788879..e1abc0d1d143 100644
@@ -61,9 +61,10 @@ enum cpa_warn {
 static const int cpa_warn_level = CPA_PROTECT;
 
 /*
- * Serialize cpa() using cpa_lock so that we don't allow any other cpu, with
- * stale large tlb entries, to change the page attribute in parallel to some
- * other cpu splitting a large page entry along with changing the attribute.
+ * Serialize CPA using cpa_lock so that:
+ * - concurrent requests don't split or change the same large mapping at the
+ *   same time
+ * - collapses of large mappings don't free page tables under a CPA lookup
  */
 static DEFINE_SPINLOCK(cpa_lock);
 
@@ -78,7 +79,6 @@ static DEFINE_SPINLOCK(cpa_lock);
 #define CPA_ST_FLUSH_ALL	0x02 /* flush the entire TLB */
 #define CPA_ST_ALIAS		0x04 /* the request is for an alias */
 #define CPA_ST_STATIC_PROT	0x08 /* enforce static protections in a split */
-#define CPA_ST_INIT_MM_LOCKED	0x10 /* init_mm's mmap lock is held */
 
 static inline pgprot_t cachemode2pgprot(enum page_cache_mode pcm)
 {
@@ -1238,11 +1238,7 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 	int ret;
 
 	spin_unlock(&cpa_lock);
-	if (cpa->state & CPA_ST_INIT_MM_LOCKED)
-		mmap_read_unlock(&init_mm);
 	pte = pte_alloc_one_kernel(&init_mm);
-	if (cpa->state & CPA_ST_INIT_MM_LOCKED)
-		mmap_read_lock(&init_mm);
 	spin_lock(&cpa_lock);
 	if (!pte)
 		return -ENOMEM;
@@ -2110,11 +2106,7 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	cpa.flags = in_flag;
 	cpa.curpage = 0;
 
-	/* Avoid race with concurrent CPA collapse. */
-	cpa.state = CPA_ST_INIT_MM_LOCKED;
-	scoped_guard(mmap_read_lock, &init_mm)
-		ret = __change_page_attr_set_clr(&cpa);
-	cpa.state &= ~CPA_ST_INIT_MM_LOCKED;
+	ret = __change_page_attr_set_clr(&cpa);
 
 	/*
 	 * Check whether we really changed something:
@@ -2143,10 +2135,10 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 		goto out;
 
 	/*
-	 * Take the mmap write lock on init_mm to:
-	 * - Avoid a use-after-free if raced by ptdump (which takes its own
-	 *   write lock on init_mm).
-	 * - Serialise concurrent CPA walkers.
+	 * Take the mmap write lock on init_mm to avoid a use-after-free if
+	 * there is a race with
+	 * - ptdump (which takes its own write lock on init_mm)
+	 * - text poking (which takes the read lock around vmalloc_to_page())
 	 */
 	scoped_guard(mmap_write_lock, &init_mm) {
 		guard(spinlock)(&cpa_lock);
Signature · 1 line
2.53.0
#12 lore raw

RFC PATCH v2 12/54 x86/mm/pat: introduce change_page_attr_pages()

In reply to Mike Rapoport (Microsoft)

CPA takes either a range of addresses or, with CPA_REQ_PAGES_ARRAY, an array of pages.

CPA_REQ_PAGES_ARRAY is used by set_pages_array_*() APIs to change the cache mode of the direct map of the pages.

Changing the cache mode of the direct map is very x86 specific and no other architecture does it.

With the upcoming move of the CPA core to the generic code, it is best to keep arrays of pages in x86, so that generic core deals only with ranges and is simpler to reason about.

Besides, its current implementation is suboptimal. CPA walks an array page at a time and splits every large page it touches, even when the pages are contiguous. For instance, TTM passes arrays that may contain high order pages.

Introduce change_page_attr_pages() that changes the pages that are contiguous in the direct map as a single range, so a range that covers a large page keeps it, and drop CPA_REQ_PAGES_ARRAY.

Purge the vmap aliases once before the ranges and flush the TLB and the caches once after them, as before.

change_page_attr_pages() flushes once for the entire pages array, so the flush can no longer take a struct cpa_data. Introduce struct cpa_flush_req that describes either a range or an array of pages, and use it for both change_page_attr_set_clr() and change_page_attr_pages().

A highmem page has no address in the direct map. CPA looked up address 0 for it, which on 32-bit ends in the "CPA: called for zero pte" warning and -EFAULT since commit 16ebf031e8ab ("x86/mm/cpa: Add __cpa_addr() helper"). Skip highmem pages.

---
 arch/x86/mm/pat/set_memory.c | 191 ++++++++++++++++++++++++++++---------------
 1 file changed, 124 insertions(+), 67 deletions(-)
arch/x86/mm/pat/set_memory.c +124 -67
index e1abc0d1d143..5e3c1152d202 100644
@@ -49,7 +49,6 @@ struct cpa_data {
 	unsigned long	pfn;
 	unsigned int	flags;
 	unsigned int	state;
-	struct page	**pages;
 };
 
 enum cpa_warn {
@@ -72,7 +71,6 @@ static DEFINE_SPINLOCK(cpa_lock);
 #define CPA_REQ_NO_CHECK_ALIAS	0x01 /* Do not search for aliases */
 #define CPA_REQ_COLLAPSE	0x02 /* try to collapse large pages */
 #define CPA_REQ_SPLIT		0x04 /* split large pages */
-#define CPA_REQ_PAGES_ARRAY	0x08
 
 /* cpa_data::state */
 #define CPA_ST_FLUSHTLB		0x01 /* the TLB needs a flush */
@@ -309,15 +307,6 @@ static inline unsigned long fix_addr(unsigned long addr)
 
 static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
 {
-	if (cpa->flags & CPA_REQ_PAGES_ARRAY) {
-		struct page *page = cpa->pages[idx];
-
-		if (unlikely(PageHighMem(page)))
-			return 0;
-
-		return (unsigned long)page_address(page);
-	}
-
 	return cpa->addr + idx * PAGE_SIZE;
 }
 
@@ -400,13 +389,33 @@ static void cpa_flush_all(unsigned long cache)
 	on_each_cpu(__cpa_flush_all, (void *) cache, 1);
 }
 
+/* The pages to flush: @numpages pages from @addr, or those in @pages */
+struct cpa_flush_req {
+	unsigned long	addr;
+	struct page	**pages;
+	unsigned long	numpages;
+	unsigned int	state;
+};
+
+/*
+ * A highmem page in @pages is not changed, but flushing it is harmless:
+ * page_address() returns NULL or its kmap address.
+ */
+static unsigned long cpa_flush_addr(struct cpa_flush_req *req, unsigned int i)
+{
+	if (req->pages)
+		return (unsigned long)page_address(req->pages[i]);
+
+	return req->addr + i * PAGE_SIZE;
+}
+
 static void __cpa_flush_tlb(void *data)
 {
-	struct cpa_data *cpa = data;
+	struct cpa_flush_req *req = data;
 	unsigned int i;
 
-	for (i = 0; i < cpa->numpages; i++)
-		flush_tlb_one_kernel(fix_addr(__cpa_addr(cpa, i)));
+	for (i = 0; i < req->numpages; i++)
+		flush_tlb_one_kernel(fix_addr(cpa_flush_addr(req, i)));
 }
 
 static int collapse_large_pages(unsigned long addr, struct list_head *pgtables);
@@ -417,20 +426,13 @@ static void cpa_collapse_large_pages(struct cpa_data *cpa)
 	struct ptdesc *ptdesc, *tmp;
 	LIST_HEAD(pgtables);
 	int collapsed = 0;
-	int i;
 
-	if (cpa->flags & CPA_REQ_PAGES_ARRAY) {
-		for (i = 0; i < cpa->numpages; i++)
-			collapsed += collapse_large_pages(__cpa_addr(cpa, i),
-							  &pgtables);
-	} else {
-		addr = __cpa_addr(cpa, 0);
-		start = addr & PMD_MASK;
-		end = addr + PAGE_SIZE * cpa->numpages;
+	addr = __cpa_addr(cpa, 0);
+	start = addr & PMD_MASK;
+	end = addr + PAGE_SIZE * cpa->numpages;
 
-		for (addr = start; within(addr, start, end); addr += PMD_SIZE)
-			collapsed += collapse_large_pages(addr, &pgtables);
-	}
+	for (addr = start; within(addr, start, end); addr += PMD_SIZE)
+		collapsed += collapse_large_pages(addr, &pgtables);
 
 	if (!collapsed)
 		return;
@@ -451,7 +453,7 @@ static void cpa_collapse_large_pages(struct cpa_data *cpa)
 	}
 }
 
-static void cpa_flush(struct cpa_data *cpa, int cache)
+static void __cpa_flush(struct cpa_flush_req *req, int cache)
 {
 	unsigned int i;
 
@@ -462,18 +464,18 @@ static void cpa_flush(struct cpa_data *cpa, int cache)
 		return;
 	}
 
-	if ((cpa->state & CPA_ST_FLUSH_ALL) ||
-	    cpa->numpages > tlb_single_page_flush_ceiling)
+	if ((req->state & CPA_ST_FLUSH_ALL) ||
+	    req->numpages > tlb_single_page_flush_ceiling)
 		flush_tlb_all();
 	else
-		on_each_cpu(__cpa_flush_tlb, cpa, 1);
+		on_each_cpu(__cpa_flush_tlb, req, 1);
 
 	if (!cache)
 		return;
 
 	mb();
-	for (i = 0; i < cpa->numpages; i++) {
-		unsigned long addr = __cpa_addr(cpa, i);
+	for (i = 0; i < req->numpages; i++) {
+		unsigned long addr = cpa_flush_addr(req, i);
 		unsigned int level;
 
 		pte_t *pte = lookup_address(addr, &level);
@@ -487,6 +489,17 @@ static void cpa_flush(struct cpa_data *cpa, int cache)
 	mb();
 }
 
+static void cpa_flush(struct cpa_data *cpa, int cache)
+{
+	struct cpa_flush_req req = {
+		.addr = cpa->addr,
+		.numpages = cpa->numpages,
+		.state = cpa->state,
+	};
+
+	__cpa_flush(&req, cache);
+}
+
 static bool overlaps(unsigned long r1_start, unsigned long r1_end,
 		     unsigned long r2_start, unsigned long r2_end)
 {
@@ -1949,7 +1962,6 @@ static int cpa_process_alias(struct cpa_data *cpa)
 
 		alias_cpa = *cpa;
 		alias_cpa.addr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
-		alias_cpa.flags &= ~CPA_REQ_PAGES_ARRAY;
 		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
 		alias_cpa.state |= CPA_ST_ALIAS;
 		alias_cpa.curpage = 0;
@@ -1978,7 +1990,6 @@ static int cpa_process_alias(struct cpa_data *cpa)
 		alias_cpa = *cpa;
 		alias_cpa.addr = (cpa->pfn << PAGE_SHIFT) +
 				 __START_KERNEL_map - phys_base;
-		alias_cpa.flags &= ~CPA_REQ_PAGES_ARRAY;
 		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
 		alias_cpa.state |= CPA_ST_ALIAS;
 		alias_cpa.curpage = 0;
@@ -2024,9 +2035,6 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 		 * preservation check.
 		 */
 		cpa->numpages = rempages;
-		/* for array changes, we can't use large page */
-		if (cpa->flags & CPA_REQ_PAGES_ARRAY)
-			cpa->numpages = 1;
 
 		scoped_guard(spinlock, &cpa_lock)
 			ret = __change_page_attr(cpa);
@@ -2061,7 +2069,7 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 
 static int change_page_attr_set_clr(unsigned long addr, int numpages,
 				    pgprot_t mask_set, pgprot_t mask_clr,
-				    int in_flag, struct page **pages)
+				    int in_flag)
 {
 	struct cpa_data cpa;
 	int ret, cache;
@@ -2079,18 +2087,12 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 		return 0;
 
 	/* Ensure we are PAGE_SIZE aligned */
-	if (!(in_flag & CPA_REQ_PAGES_ARRAY)) {
+	if (addr & ~PAGE_MASK) {
+		addr &= PAGE_MASK;
 		/*
-		 * in_flag of CPA_REQ_PAGES_ARRAY implies it is aligned.
-		 * No need to check in that case
+		 * People should not be passing in unaligned addresses:
 		 */
-		if (addr & ~PAGE_MASK) {
-			addr &= PAGE_MASK;
-			/*
-			 * People should not be passing in unaligned addresses:
-			 */
-			WARN_ON_ONCE(1);
-		}
+		WARN_ON_ONCE(1);
 	}
 
 	/* Must avoid aliasing mappings in the highmem code */
@@ -2099,7 +2101,6 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	vm_unmap_aliases();
 
 	cpa.addr = addr;
-	cpa.pages = pages;
 	cpa.numpages = numpages;
 	cpa.mask_set = mask_set;
 	cpa.mask_clr = mask_clr;
@@ -2151,29 +2152,88 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 static inline int change_page_attr_set(unsigned long addr, int numpages,
 				       pgprot_t mask)
 {
-	return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
-					NULL);
+	return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0);
 }
 
 static inline int change_page_attr_clear(unsigned long addr, int numpages,
 					 pgprot_t mask)
 {
-	return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
-					NULL);
+	return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0);
+}
+
+/* The number of pages from @pages[0] that are contiguous in the direct map */
+static int nr_contig_pages(struct page **pages, int numpages)
+{
+	void *addr = page_address(pages[0]);
+	int n;
+
+	for (n = 1; n < numpages; n++) {
+		if (page_address(pages[n]) != addr + n * PAGE_SIZE)
+			break;
+	}
+
+	return n;
+}
+
+/*
+ * Change the pages in ranges that are contiguous in the direct map, so that
+ * a range that covers a large page keeps it. Purge the vmap aliases once
+ * before the ranges and flush once after them.
+ */
+static int change_page_attr_pages(struct page **pages, int numpages,
+				  pgprot_t mask_set, pgprot_t mask_clr)
+{
+	struct cpa_flush_req req = { .pages = pages, .numpages = numpages };
+	struct cpa_data cpa = {
+		.mask_set = canon_pgprot(mask_set),
+		.mask_clr = mask_clr,
+	};
+	int i, n, ret = 0;
+
+	if (!pgprot_val(cpa.mask_set) && !pgprot_val(cpa.mask_clr))
+		return 0;
+
+	kmap_flush_unused();
+	vm_unmap_aliases();
+
+	for (i = 0; i < numpages; i += n) {
+		n = 1;
+		if (PageHighMem(pages[i]))
+			continue;
+
+		n = nr_contig_pages(pages + i, numpages - i);
+		cpa.addr = (unsigned long)page_address(pages[i]);
+		cpa.numpages = n;
+		cpa.curpage = 0;
+		cpa.state = 0;
+		ret = __change_page_attr_set_clr(&cpa);
+		req.state |= cpa.state;
+		if (ret)
+			break;
+	}
+
+	if (!(req.state & CPA_ST_FLUSHTLB))
+		return ret;
+
+	/* On error, flush everything to be sure */
+	if (ret)
+		req.state |= CPA_ST_FLUSH_ALL;
+
+	__cpa_flush(&req, !!pgprot2cachemode(cpa.mask_set));
+
+	return ret;
 }
 
 static inline int cpa_set_pages_array(struct page **pages, int numpages,
 				       pgprot_t mask)
 {
-	return change_page_attr_set_clr(0, numpages, mask, __pgprot(0),
-					CPA_REQ_PAGES_ARRAY, pages);
+	return change_page_attr_pages(pages, numpages, mask, __pgprot(0));
 }
 
 static inline int cpa_clear_pages_array(struct page **pages, int numpages,
 					 pgprot_t mask)
 {
-	return change_page_attr_set_clr(0, numpages, __pgprot(0), mask,
-					CPA_REQ_PAGES_ARRAY, pages);
+	return change_page_attr_pages(pages, numpages, __pgprot(0), mask);
 }
 
 int _set_memory_uc(unsigned long addr, int numpages)
@@ -2222,8 +2282,7 @@ int _set_memory_wc(unsigned long addr, int numpages)
 	if (!ret) {
 		ret = change_page_attr_set_clr(addr, numpages,
 					       cachemode2pgprot(_PAGE_CACHE_MODE_WC),
-					       __pgprot(_PAGE_CACHE_MASK),
-					       0, NULL);
+					       __pgprot(_PAGE_CACHE_MASK), 0);
 	}
 	return ret;
 }
@@ -2342,7 +2401,7 @@ int set_memory_rox(unsigned long addr, int numpages)
 		clr.pgprot |= _PAGE_NX;
 
 	return change_page_attr_set_clr(addr, numpages, __pgprot(0), clr,
-					CPA_REQ_COLLAPSE, NULL);
+					CPA_REQ_COLLAPSE);
 }
 
 int set_memory_rw(unsigned long addr, int numpages)
@@ -2359,7 +2418,7 @@ int set_memory_np_noalias(unsigned long addr, int numpages)
 {
 	return change_page_attr_set_clr(addr, numpages, __pgprot(0),
 					__pgprot(_PAGE_PRESENT),
-					CPA_REQ_NO_CHECK_ALIAS, NULL);
+					CPA_REQ_NO_CHECK_ALIAS);
 }
 
 int set_memory_p(unsigned long addr, int numpages)
@@ -2371,7 +2430,7 @@ int set_memory_4k(unsigned long addr, int numpages)
 {
 	return change_page_attr_set_clr(addr, numpages,
 					__pgprot(_PAGE_KERNEL_4K),
-					__pgprot(0), CPA_REQ_SPLIT, NULL);
+					__pgprot(0), CPA_REQ_SPLIT);
 }
 
 int set_memory_nonglobal(unsigned long addr, int numpages)
@@ -2535,11 +2594,9 @@ static int _set_pages_array(struct page **pages, int numpages,
 	ret = cpa_set_pages_array(pages, numpages,
 				  cachemode2pgprot(set_type));
 	if (!ret && new_type == _PAGE_CACHE_MODE_WC)
-		ret = change_page_attr_set_clr(0, numpages,
-					       cachemode2pgprot(
-						_PAGE_CACHE_MODE_WC),
-					       __pgprot(_PAGE_CACHE_MASK),
-					       CPA_REQ_PAGES_ARRAY, pages);
+		ret = change_page_attr_pages(pages, numpages,
+				cachemode2pgprot(_PAGE_CACHE_MODE_WC),
+				__pgprot(_PAGE_CACHE_MASK));
 	if (ret)
 		goto err_out;
 	return 0; /* Success */
Signature · 1 line
2.53.0
#13 lore raw

RFC PATCH v2 13/54 x86/mm/pat: make the direct map counters atomic

In reply to Mike Rapoport (Microsoft)

In update_page_count() pgd_lock protects only the direct map counters. The splits and collapses in CPA update the counters under pgd_lock that they hold for other reasons.

Make the counters atomic_long_t, like s390 and powerpc do, so that updating them does not need pgd_lock.

A split checks that the counter of the large pages is not zero before it decrements it. Use atomic_long_dec_if_positive() so that a concurrent update cannot drive the counter below zero between the two.

---
 arch/x86/mm/pat/set_memory.c | 28 +++++++++++++++-------------
 1 file changed, 15 insertions(+), 13 deletions(-)
arch/x86/mm/pat/set_memory.c +15 -13
index 5e3c1152d202..8076d29a2931 100644
@@ -84,56 +84,58 @@ static inline pgprot_t cachemode2pgprot(enum page_cache_mode pcm)
 }
 
 #ifdef CONFIG_PROC_FS
-static unsigned long direct_pages_count[PG_LEVEL_NUM];
+static atomic_long_t direct_pages_count[PG_LEVEL_NUM];
 
 void update_page_count(int level, unsigned long pages)
 {
-	/* Protect against CPA */
-	guard(spinlock)(&pgd_lock);
-	direct_pages_count[level] += pages;
+	atomic_long_add(pages, &direct_pages_count[level]);
 }
 
 static void split_page_count(int level)
 {
-	if (direct_pages_count[level] == 0)
+	if (atomic_long_dec_if_positive(&direct_pages_count[level]) < 0)
 		return;
 
-	direct_pages_count[level]--;
 	if (system_state == SYSTEM_RUNNING) {
 		if (level == PG_LEVEL_2M)
 			count_vm_event(DIRECT_MAP_LEVEL2_SPLIT);
 		else if (level == PG_LEVEL_1G)
 			count_vm_event(DIRECT_MAP_LEVEL3_SPLIT);
 	}
-	direct_pages_count[level - 1] += PTRS_PER_PTE;
+	atomic_long_add(PTRS_PER_PTE, &direct_pages_count[level - 1]);
 }
 
 static void collapse_page_count(int level)
 {
-	direct_pages_count[level]++;
+	atomic_long_inc(&direct_pages_count[level]);
 	if (system_state == SYSTEM_RUNNING) {
 		if (level == PG_LEVEL_2M)
 			count_vm_event(DIRECT_MAP_LEVEL2_COLLAPSE);
 		else if (level == PG_LEVEL_1G)
 			count_vm_event(DIRECT_MAP_LEVEL3_COLLAPSE);
 	}
-	direct_pages_count[level - 1] -= PTRS_PER_PTE;
+	atomic_long_sub(PTRS_PER_PTE, &direct_pages_count[level - 1]);
+}
+
+static unsigned long direct_pages(int level)
+{
+	return atomic_long_read(&direct_pages_count[level]);
 }
 
 void arch_report_meminfo(struct seq_file *m)
 {
 	seq_printf(m, "DirectMap4k:    %8lu kB\n",
-			direct_pages_count[PG_LEVEL_4K] << 2);
+		   direct_pages(PG_LEVEL_4K) << 2);
 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
 	seq_printf(m, "DirectMap2M:    %8lu kB\n",
-			direct_pages_count[PG_LEVEL_2M] << 11);
+		   direct_pages(PG_LEVEL_2M) << 11);
 #else
 	seq_printf(m, "DirectMap4M:    %8lu kB\n",
-			direct_pages_count[PG_LEVEL_2M] << 12);
+		   direct_pages(PG_LEVEL_2M) << 12);
 #endif
 	if (direct_gbpages)
 		seq_printf(m, "DirectMap1G:    %8lu kB\n",
-			direct_pages_count[PG_LEVEL_1G] << 20);
+			   direct_pages(PG_LEVEL_1G) << 20);
 }
 #else
 static inline void split_page_count(int level) { }
Signature · 1 line
2.53.0
#14 lore raw

RFC PATCH v2 14/54 x86/mm/pat: take pgd_lock only around the pgd_list walks

In reply to Mike Rapoport (Microsoft)

CPA takes pgd_lock around the split decision, the update of a large page, the split and the collapse of large pages.

Everywhere else pgd_lock protects pgd_list. CPA needs it only on 32-bit, to update the per-pgd copies of the kernel PMD entries when it changes them.

Updates of large pages are serialized by cpa_lock anyway, and the direct map counters are atomic.

Take pgd_lock only around the pgd_list walks.

Without pgd_lock, should_split_large_page() only checks CPA_REQ_SPLIT before it calls __should_split_large_page(). Fold it into __should_split_large_page() and keep the shorter name.

---
 arch/x86/mm/pat/set_memory.c | 56 +++++++++++++++++++++-----------------------
 1 file changed, 27 insertions(+), 29 deletions(-)
arch/x86/mm/pat/set_memory.c +27 -29
index 8076d29a2931..9dfe69d608b8 100644
@@ -916,24 +916,29 @@ EXPORT_SYMBOL_GPL(slow_virt_to_phys);
  */
 static void __set_pmd_pte(pte_t *kpte, unsigned long address, pte_t pte)
 {
+	struct ptdesc *ptdesc;
+
+	if (!IS_ENABLED(CONFIG_X86_32)) {
+		set_pte_atomic(kpte, pte);
+		return;
+	}
+
+	guard(spinlock)(&pgd_lock);
+
 	/* change init_mm */
 	set_pte_atomic(kpte, pte);
 
-	if (IS_ENABLED(CONFIG_X86_32)) {
-		struct ptdesc *ptdesc;
-
-		list_for_each_entry(ptdesc, &pgd_list, pt_list) {
-			pgd_t *pgd;
-			p4d_t *p4d;
-			pud_t *pud;
-			pmd_t *pmd;
-
-			pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(address);
-			p4d = p4d_offset(pgd, address);
-			pud = pud_offset(p4d, address);
-			pmd = pmd_offset(pud, address);
-			set_pte_atomic((pte_t *)pmd, pte);
-		}
+	list_for_each_entry(ptdesc, &pgd_list, pt_list) {
+		pgd_t *pgd;
+		p4d_t *p4d;
+		pud_t *pud;
+		pmd_t *pmd;
+
+		pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(address);
+		p4d = p4d_offset(pgd, address);
+		pud = pud_offset(p4d, address);
+		pmd = pmd_offset(pud, address);
+		set_pte_atomic((pte_t *)pmd, pte);
 	}
 }
 
@@ -954,8 +959,8 @@ static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
 	return prot;
 }
 
-static int __should_split_large_page(pte_t *kpte, unsigned long address,
-				     struct cpa_data *cpa)
+static int should_split_large_page(pte_t *kpte, unsigned long address,
+				   struct cpa_data *cpa)
 {
 	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
 	pgprot_t old_prot, new_prot, req_prot, chk_prot;
@@ -963,6 +968,9 @@ static int __should_split_large_page(pte_t *kpte, unsigned long address,
 	enum pg_level level;
 	bool nx, rw;
 
+	if (cpa->flags & CPA_REQ_SPLIT)
+		return 1;
+
 	/*
 	 * Check for races, another CPU might have split this page
 	 * up already:
@@ -1101,16 +1109,6 @@ static int __should_split_large_page(pte_t *kpte, unsigned long address,
 	return 0;
 }
 
-static int should_split_large_page(pte_t *kpte, unsigned long address,
-				   struct cpa_data *cpa)
-{
-	if (cpa->flags & CPA_REQ_SPLIT)
-		return 1;
-
-	guard(spinlock)(&pgd_lock);
-	return __should_split_large_page(kpte, address, cpa);
-}
-
 static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
 			  pgprot_t ref_prot, unsigned long address,
 			  unsigned long size)
@@ -1158,7 +1156,6 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 	bool nx, rw;
 	pte_t *tmp;
 
-	guard(spinlock)(&pgd_lock);
 	/*
 	 * Check for races, another CPU might have split this page
 	 * up for us already:
@@ -1304,6 +1301,8 @@ static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
 			return 0;
 	}
 
+	guard(spinlock)(&pgd_lock);
+
 	old_pmd = *pmd;
 
 	/* Success: set up a large page */
@@ -1404,7 +1403,6 @@ static int collapse_large_pages(unsigned long addr, struct list_head *pgtables)
 
 	addr &= PMD_MASK;
 
-	guard(spinlock)(&pgd_lock);
 	pgd = pgd_offset_k(addr);
 	if (pgd_none(*pgd))
 		return 0;
Signature · 1 line
2.53.0
#15 lore raw

RFC PATCH v2 15/54 x86/mm/pat: look up the effective NX/RW bits in verify_rwx()

In reply to Mike Rapoport (Microsoft)

Every CPA lookup collects the effective NX and RW bits of the upper page table levels. Only verify_rwx() needs them, and only when a mapping is about to become both writable and executable.

Walk the page tables in verify_rwx() after its early exits and let the CPA lookups return just the entry and its level. Add cpa_pgd() that picks the page table of the request, to avoid code duplication.

Such a lookup does not depend on the x86 page table format. It will move to the generic code together with the rest of CPA core logic.

---
 arch/x86/mm/pat/set_memory.c | 51 ++++++++++++++++++++++++++------------------
 1 file changed, 30 insertions(+), 21 deletions(-)
arch/x86/mm/pat/set_memory.c +30 -21
index 9dfe69d608b8..8d481e9edf75 100644
@@ -307,6 +307,14 @@ static inline unsigned long fix_addr(unsigned long addr)
 #endif
 }
 
+static pgd_t *cpa_pgd(struct cpa_data *cpa, unsigned long address)
+{
+	if (!cpa->pgd)
+		return pgd_offset_k(address);
+
+	return cpa->pgd + pgd_index(address);
+}
+
 static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
 {
 	return cpa->addr + idx * PAGE_SIZE;
@@ -688,11 +696,14 @@ static inline pgprot_t static_protections(pgprot_t prot, unsigned long start,
 /*
  * Validate strict W^X semantics.
  */
-static inline pgprot_t verify_rwx(pgprot_t old, pgprot_t new, unsigned long start,
-				  unsigned long pfn, unsigned long npg,
-				  bool nx, bool rw)
+static inline pgprot_t verify_rwx(struct cpa_data *cpa, pgprot_t old,
+				  pgprot_t new, unsigned long start,
+				  unsigned long pfn, unsigned long npg)
 {
+	unsigned int level;
 	unsigned long end;
+	bool nx, rw;
+	pgd_t *pgd;
 
 	/*
 	 * 32-bit has some unfixable W+X issues, like EFI code
@@ -712,6 +723,13 @@ static inline pgprot_t verify_rwx(pgprot_t old, pgprot_t new, unsigned long star
 	if ((pgprot_val(new) & (_PAGE_RW | _PAGE_NX)) != _PAGE_RW)
 		return new;
 
+	/*
+	 * Only a mapping about to become W+X pays for the second walk that
+	 * collects the effective NX and RW bits of the upper levels.
+	 */
+	pgd = cpa_pgd(cpa, start);
+	lookup_address_in_pgd_attr(pgd, start, &level, &nx, &rw);
+
 	/* Non-leaf translation entries can disable writing or execution. */
 	if (!rw || nx)
 		return new;
@@ -825,16 +843,11 @@ pte_t *lookup_address(unsigned long address, unsigned int *level)
 EXPORT_SYMBOL_GPL(lookup_address);
 
 static pte_t *_lookup_address_cpa(struct cpa_data *cpa, unsigned long address,
-				  unsigned int *level, bool *nx, bool *rw)
+				  unsigned int *level)
 {
-	pgd_t *pgd;
+	pgd_t *pgd = cpa_pgd(cpa, address);
 
-	if (!cpa->pgd)
-		pgd = pgd_offset_k(address);
-	else
-		pgd = cpa->pgd + pgd_index(address);
-
-	return lookup_address_in_pgd_attr(pgd, address, level, nx, rw);
+	return lookup_address_in_pgd(pgd, address, level);
 }
 
 /*
@@ -966,7 +979,6 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	pgprot_t old_prot, new_prot, req_prot, chk_prot;
 	pte_t new_pte, *tmp;
 	enum pg_level level;
-	bool nx, rw;
 
 	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
@@ -975,7 +987,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	 * Check for races, another CPU might have split this page
 	 * up already:
 	 */
-	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
+	tmp = _lookup_address_cpa(cpa, address, &level);
 	if (tmp != kpte)
 		return 1;
 
@@ -1086,8 +1098,8 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	new_prot = static_protections(req_prot, lpaddr, old_pfn, numpages,
 				      psize, CPA_DETECT);
 
-	new_prot = verify_rwx(old_prot, new_prot, lpaddr, old_pfn, numpages,
-			      nx, rw);
+	new_prot = verify_rwx(cpa, old_prot, new_prot, lpaddr, old_pfn,
+			      numpages);
 
 	/*
 	 * If there is a conflict, split the large page.
@@ -1153,14 +1165,13 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 	struct page *base = virt_to_page(pbase);
 	unsigned int i, level;
 	pgprot_t ref_prot;
-	bool nx, rw;
 	pte_t *tmp;
 
 	/*
 	 * Check for races, another CPU might have split this page
 	 * up for us already:
 	 */
-	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
+	tmp = _lookup_address_cpa(cpa, address, &level);
 	if (tmp != kpte)
 		return 1;
 
@@ -1866,11 +1877,10 @@ static int __change_page_attr(struct cpa_data *cpa)
 	int do_split, err;
 	unsigned int level;
 	pte_t *kpte, old_pte;
-	bool nx, rw;
 
 	address = __cpa_addr(cpa, cpa->curpage);
 repeat:
-	kpte = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
+	kpte = _lookup_address_cpa(cpa, address, &level);
 	if (!kpte)
 		return __cpa_process_fault(cpa, address);
 
@@ -1892,8 +1902,7 @@ static int __change_page_attr(struct cpa_data *cpa)
 		new_prot = static_protections(new_prot, address, pfn, 1, 0,
 					      CPA_PROTECT);
 
-		new_prot = verify_rwx(old_prot, new_prot, address, pfn, 1,
-				      nx, rw);
+		new_prot = verify_rwx(cpa, old_prot, new_prot, address, pfn, 1);
 
 		new_prot = pgprot_clear_protnone_bits(new_prot);
 
Signature · 1 line
2.53.0
#16 lore raw

RFC PATCH v2 16/54 x86/mm/pat: look up a large page again only after dropping cpa_lock

In reply to Mike Rapoport (Microsoft)

should_split_large_page() and __split_large_page() both look up the address again to check whether another CPU split the large page after the previous lookup.

In should_split_large_page() this cannot happen, because cpa_lock is held from the lookup in __change_page_attr() to the check.

split_large_page() drops cpa_lock to allocate a page table, so the check is needed there.

Drop the lookup from should_split_large_page() and pass it the level that __change_page_attr() found.

Move the lookup from __split_large_page() to split_large_page(), right after it retakes cpa_lock, and pass the level down.

---
 arch/x86/mm/pat/set_memory.c | 48 ++++++++++++++++++--------------------------
 1 file changed, 20 insertions(+), 28 deletions(-)
arch/x86/mm/pat/set_memory.c +20 -28
index 8d481e9edf75..967d691ef1c0 100644
@@ -973,24 +973,15 @@ static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
 }
 
 static int should_split_large_page(pte_t *kpte, unsigned long address,
-				   struct cpa_data *cpa)
+				   enum pg_level level, struct cpa_data *cpa)
 {
 	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
 	pgprot_t old_prot, new_prot, req_prot, chk_prot;
-	pte_t new_pte, *tmp;
-	enum pg_level level;
+	pte_t new_pte;
 
 	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
 
-	/*
-	 * Check for races, another CPU might have split this page
-	 * up already:
-	 */
-	tmp = _lookup_address_cpa(cpa, address, &level);
-	if (tmp != kpte)
-		return 1;
-
 	switch (level) {
 	case PG_LEVEL_2M:
 		old_prot = pmd_pgprot(*(pmd_t *)kpte);
@@ -1159,21 +1150,12 @@ static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
 
 static int
 __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
-		   pte_t *pbase)
+		   unsigned int level, pte_t *pbase)
 {
 	unsigned long lpaddr, lpinc, ref_pfn, pfn, pfninc = 1;
 	struct page *base = virt_to_page(pbase);
-	unsigned int i, level;
 	pgprot_t ref_prot;
-	pte_t *tmp;
-
-	/*
-	 * Check for races, another CPU might have split this page
-	 * up for us already:
-	 */
-	tmp = _lookup_address_cpa(cpa, address, &level);
-	if (tmp != kpte)
-		return 1;
+	unsigned int i;
 
 	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
 
@@ -1257,8 +1239,9 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 			    unsigned long address)
 {
+	unsigned int level;
 	pte_t *pte;
-	int ret;
+	int ret = 0;
 
 	spin_unlock(&cpa_lock);
 	pte = pte_alloc_one_kernel(&init_mm);
@@ -1266,13 +1249,22 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 	if (!pte)
 		return -ENOMEM;
 
-	ret = __split_large_page(cpa, kpte, address, pte);
+	/*
+	 * Check for races, another CPU might have split this page
+	 * up for us already:
+	 */
+	if (_lookup_address_cpa(cpa, address, &level) != kpte)
+		goto out;
+
+	ret = __split_large_page(cpa, kpte, address, level, pte);
 	if (ret)
-		pte_free_kernel(&init_mm, pte);
-	if (ret < 0)
-		return ret;
+		goto out;
 
 	return 0;
+
+out:
+	pte_free_kernel(&init_mm, pte);
+	return ret;
 }
 
 static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
@@ -1928,7 +1920,7 @@ static int __change_page_attr(struct cpa_data *cpa)
 	 * Check, whether we can keep the large page intact
 	 * and just change the pte:
 	 */
-	do_split = should_split_large_page(kpte, address, cpa);
+	do_split = should_split_large_page(kpte, address, level, cpa);
 	/*
 	 * When the range fits into the existing large page,
 	 * return. cp->numpages and cpa->tlbflush have been updated in
Signature · 1 line
2.53.0
#17 lore raw

RFC PATCH v2 17/54 x86/mm/pat: drop the check of existing mappings against static protections

In reply to Mike Rapoport (Microsoft)

Before deciding whether to keep a large page, CPA checks that the existing protection of the page satisfies the static protections. If it does not, CPA warns, splits the page and fixes up the new PTEs.

The only reason commit f61c5ba2885e ("x86/mm/cpa: Add sanity check for existing mappings") gave for adding the check was that

... it is possible to do a quick verification that the current mapping is correct vs. the static protection areas.

The warning fired only once, on an earlier version of the same series, and the series fixed the cause with commit 2a25dc7c79c9 ("x86/mm/init32: Mark text and rodata RO in one go").

Back in 2018 much more code changed the permissions of kernel mappings. ftrace made the whole kernel text writable and back on every update, any module could call set_memory_x() and set_memory_nx(), and nothing warned about W^X mappings.

Since then ftrace switched to text_poke(), the NX helpers are no longer exported and W^X violations are detected late in boot and by each CPA call.

A mapping that violates static protections cannot appear today:
* CPA checks the requested protection against the static protections before it writes a large page
* the page tables built at boot map the kernel text executable and the BIOS area with 4K pages
* mark_rodata_ro() enables the read-only checks of static_protections() only once all mappings of rodata are read-only

Even if such a mapping appeared, the check would hardly fix it. It sees only the large pages that later requests touch, and of a 1G page it repairs only the 2M page around the request.

The check of the existing mappings also complicates how large pages are split and stands in the way of moving core CPA logic from x86 to generic code.

Drop the check of the existing mappings and leave only the checks of the requested protection against the static protections.

---
 arch/x86/mm/pat/set_memory.c | 73 +++-----------------------------------------
 1 file changed, 5 insertions(+), 68 deletions(-)
arch/x86/mm/pat/set_memory.c +5 -68
index 967d691ef1c0..9ccc08cf220f 100644
@@ -52,7 +52,6 @@ struct cpa_data {
 };
 
 enum cpa_warn {
-	CPA_CONFLICT,
 	CPA_PROTECT,
 	CPA_DETECT,
 };
@@ -76,7 +75,6 @@ static DEFINE_SPINLOCK(cpa_lock);
 #define CPA_ST_FLUSHTLB		0x01 /* the TLB needs a flush */
 #define CPA_ST_FLUSH_ALL	0x02 /* flush the entire TLB */
 #define CPA_ST_ALIAS		0x04 /* the request is for an alias */
-#define CPA_ST_STATIC_PROT	0x08 /* enforce static protections in a split */
 
 static inline pgprot_t cachemode2pgprot(enum page_cache_mode pcm)
 {
@@ -629,7 +627,6 @@ static inline void check_conflict(int warnlvl, pgprot_t prot, pgprotval_t val,
 				  unsigned long pfn, const char *txt)
 {
 	static const char *lvltxt[] = {
-		[CPA_CONFLICT]	= "conflict",
 		[CPA_PROTECT]	= "protect",
 		[CPA_DETECT]	= "detect",
 	};
@@ -976,7 +973,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 				   enum pg_level level, struct cpa_data *cpa)
 {
 	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
-	pgprot_t old_prot, new_prot, req_prot, chk_prot;
+	pgprot_t old_prot, new_prot, req_prot;
 	pte_t new_pte;
 
 	if (cpa->flags & CPA_REQ_SPLIT)
@@ -1045,31 +1042,11 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	lpaddr = address & pmask;
 	numpages = psize >> PAGE_SHIFT;
 
-	/*
-	 * Sanity check that the existing mapping is correct versus the static
-	 * protections. static_protections() guards against !PRESENT, so no
-	 * extra conditional required here.
-	 */
-	chk_prot = static_protections(old_prot, lpaddr, old_pfn, numpages,
-				      psize, CPA_CONFLICT);
-
-	if (WARN_ON_ONCE(pgprot_val(chk_prot) != pgprot_val(old_prot))) {
-		/*
-		 * Split the large page and tell the split code to
-		 * enforce static protections.
-		 */
-		cpa->state |= CPA_ST_STATIC_PROT;
-		return 1;
-	}
-
 	/*
 	 * Optimization: If the requested pgprot is the same as the current
 	 * pgprot, then the large page can be preserved and no updates are
 	 * required independent of alignment and length of the requested
-	 * range. The above already established that the current pgprot is
-	 * correct, which in consequence makes the requested pgprot correct
-	 * as well if it is the same. The static protection scan below will
-	 * not come to a different conclusion.
+	 * range.
 	 */
 	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
 		cpa_inc_lp_sameprot(level);
@@ -1112,47 +1089,11 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	return 0;
 }
 
-static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
-			  pgprot_t ref_prot, unsigned long address,
-			  unsigned long size)
-{
-	unsigned int npg = PFN_DOWN(size);
-	pgprot_t prot;
-
-	/*
-	 * If should_split_large_page() discovered an inconsistent mapping,
-	 * remove the invalid protection in the split mapping.
-	 */
-	if (!(cpa->state & CPA_ST_STATIC_PROT))
-		goto set;
-
-	/* Hand in lpsize = 0 to enforce the protection mechanism */
-	prot = static_protections(ref_prot, address, pfn, npg, 0, CPA_PROTECT);
-
-	if (pgprot_val(prot) == pgprot_val(ref_prot))
-		goto set;
-
-	/*
-	 * If this is splitting a PMD, fix it up. PUD splits cannot be
-	 * fixed trivially as that would require to rescan the newly
-	 * installed PMD mappings after returning from split_large_page()
-	 * so an eventual further split can allocate the necessary PTE
-	 * pages. Warn for now and revisit it in case this actually
-	 * happens.
-	 */
-	if (size == PAGE_SIZE)
-		ref_prot = prot;
-	else
-		pr_warn_once("CPA: Cannot fixup static protections for PUD split\n");
-set:
-	set_pte(pte, pfn_pte(pfn, ref_prot));
-}
-
 static int
 __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 		   unsigned int level, pte_t *pbase)
 {
-	unsigned long lpaddr, lpinc, ref_pfn, pfn, pfninc = 1;
+	unsigned long ref_pfn, pfn, pfninc = 1;
 	struct page *base = virt_to_page(pbase);
 	pgprot_t ref_prot;
 	unsigned int i;
@@ -1168,16 +1109,12 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 		 */
 		ref_prot = pgprot_large_2_4k(ref_prot);
 		ref_pfn = pmd_pfn(*(pmd_t *)kpte);
-		lpaddr = address & PMD_MASK;
-		lpinc = PAGE_SIZE;
 		break;
 
 	case PG_LEVEL_1G:
 		ref_prot = pud_pgprot(*(pud_t *)kpte);
 		ref_pfn = pud_pfn(*(pud_t *)kpte);
 		pfninc = PMD_SIZE >> PAGE_SHIFT;
-		lpaddr = address & PUD_MASK;
-		lpinc = PMD_SIZE;
 		/*
 		 * Clear the PSE flags if the PRESENT flag is not set
 		 * otherwise pmd_present() will return true even on a non
@@ -1197,8 +1134,8 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 	 * Get the target pfn from the original entry:
 	 */
 	pfn = ref_pfn;
-	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc, lpaddr += lpinc)
-		split_set_pte(cpa, pbase + i, pfn, ref_prot, lpaddr, lpinc);
+	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
+		set_pte(pbase + i, pfn_pte(pfn, ref_prot));
 
 	if (within(address, PAGE_OFFSET,
 		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
Signature · 1 line
2.53.0
#18 lore raw

RFC PATCH v2 18/54 x86/mm/pat: consolidate encoding of page table entries

In reply to Mike Rapoport (Microsoft)

CPA encodes page table entries in three places: when it writes a PTE, when it updates a large page it keeps and when it splits a large page.

Each place converts between the PTE and the large page formats and fixes up PSE and PROTNONE.

The split of a PUD does it differently from the split of a PMD.

Add cpa_pte() that encodes an entry for a page table level and use it everywhere.

The check for an unchanged large page no longer clears _PAGE_GLOBAL when _PAGE_PRESENT is clear, so set_memory_global() on a non-present large page rewrites or splits it, although nothing changes. Its only caller changes the kernel text, which is always present.

---
 arch/x86/mm/pat/set_memory.c | 48 +++++++++++++++++++++-----------------------
 1 file changed, 23 insertions(+), 25 deletions(-)
arch/x86/mm/pat/set_memory.c +23 -25
index 9ccc08cf220f..068ab1e2bbc8 100644
@@ -969,6 +969,24 @@ static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
 	return prot;
 }
 
+/*
+ * The caching mode includes the PAT bit located at different bit positions
+ * in the 4K and large page formats, and _PAGE_PSE is only valid for present
+ * large pages.
+ */
+static pte_t cpa_pte(enum pg_level level, unsigned long pfn, pgprot_t prot)
+{
+	prot = pgprot_clear_protnone_bits(prot);
+
+	if (level != PG_LEVEL_4K) {
+		prot = pgprot_4k_2_large(prot);
+		if (pgprot_val(prot) & _PAGE_PRESENT)
+			pgprot_val(prot) |= _PAGE_PSE;
+	}
+
+	return pfn_pte(pfn, prot);
+}
+
 static int should_split_large_page(pte_t *kpte, unsigned long address,
 				   enum pg_level level, struct cpa_data *cpa)
 {
@@ -1018,16 +1036,6 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
 	pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
 
-	/*
-	 * req_prot is in format of 4k pages. It must be converted to large
-	 * page format: the caching mode includes the PAT bit located at
-	 * different bit positions in the two formats.
-	 */
-	req_prot = pgprot_4k_2_large(req_prot);
-	req_prot = pgprot_clear_protnone_bits(req_prot);
-	if (pgprot_val(req_prot) & _PAGE_PRESENT)
-		pgprot_val(req_prot) |= _PAGE_PSE;
-
 	/*
 	 * old_pfn points to the large page base pfn. So we need to add the
 	 * offset of the virtual address:
@@ -1048,7 +1056,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	 * required independent of alignment and length of the requested
 	 * range.
 	 */
-	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
+	if (pgprot_val(req_prot) == pgprot_val(pgprot_large_2_4k(old_prot))) {
 		cpa_inc_lp_sameprot(level);
 		return 0;
 	}
@@ -1082,7 +1090,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 		return 1;
 
 	/* All checks passed. Update the large page mapping. */
-	new_pte = pfn_pte(old_pfn, new_prot);
+	new_pte = cpa_pte(level, old_pfn, new_prot);
 	__set_pmd_pte(kpte, address, new_pte);
 	cpa->state |= CPA_ST_FLUSHTLB;
 	cpa_inc_lp_preserved(level);
@@ -1115,27 +1123,19 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 		ref_prot = pud_pgprot(*(pud_t *)kpte);
 		ref_pfn = pud_pfn(*(pud_t *)kpte);
 		pfninc = PMD_SIZE >> PAGE_SHIFT;
-		/*
-		 * Clear the PSE flags if the PRESENT flag is not set
-		 * otherwise pmd_present() will return true even on a non
-		 * present pmd.
-		 */
-		if (!(pgprot_val(ref_prot) & _PAGE_PRESENT))
-			pgprot_val(ref_prot) &= ~_PAGE_PSE;
+		ref_prot = pgprot_large_2_4k(ref_prot);
 		break;
 
 	default:
 		return -EINVAL;
 	}
 
-	ref_prot = pgprot_clear_protnone_bits(ref_prot);
-
 	/*
 	 * Get the target pfn from the original entry:
 	 */
 	pfn = ref_pfn;
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
-		set_pte(pbase + i, pfn_pte(pfn, ref_prot));
+		set_pte(pbase + i, cpa_pte(level - 1, pfn, ref_prot));
 
 	if (within(address, PAGE_OFFSET,
 		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
@@ -1833,14 +1833,12 @@ static int __change_page_attr(struct cpa_data *cpa)
 
 		new_prot = verify_rwx(cpa, old_prot, new_prot, address, pfn, 1);
 
-		new_prot = pgprot_clear_protnone_bits(new_prot);
-
 		/*
 		 * We need to keep the pfn from the existing PTE,
 		 * after all we're only going to change its attributes
 		 * not the memory it points to
 		 */
-		new_pte = pfn_pte(pfn, new_prot);
+		new_pte = cpa_pte(level, pfn, new_prot);
 		cpa->pfn = pfn;
 		/*
 		 * Do we really change anything ?
Signature · 1 line
2.53.0
#19 lore raw

RFC PATCH v2 19/54 x86/mm/pat: use enum pgtable_level in CPA

In reply to Mike Rapoport (Microsoft)

The core of CPA is going to become generic. Generic code cannot use the x86 enum pg_level to denote the page table levels.

Switch CPA, its statistics and the direct map counters to enum pgtable_level, and add a CPA private lookup that returns it.

Add pgtable_level_size() and pgtable_level_mask() helpers so that x86 could use them instead of page_level_size() and page_level_mask() to determine the size of the range that a level maps.

Add PGTABLE_LEVEL_NUM to replace PG_LEVEL_NUM in the declaration of the array of the direct map counters.

lookup_address_in_pgd() stays unchanged because it has users outside of CPA that expect enum pg_level.

The new lookup duplicates it for now. It will move to the generic code together with the rest of core CPA logic.

---
 arch/x86/mm/init_32.c        |  4 +-
 arch/x86/mm/init_64.c        | 14 +++----
 arch/x86/mm/pat/set_memory.c | 98 +++++++++++++++++++++++++++++++-------------
 include/linux/pgtable.h      | 26 ++++++++++++
 4 files changed, 104 insertions(+), 38 deletions(-)
arch/x86/mm/init_32.c +2 -2
index 8323c1f599f2..1895a71316c2 100644
@@ -367,8 +367,8 @@ kernel_physical_mapping_init(unsigned long start,
 		 * update direct mapping page count only in the first
 		 * iteration.
 		 */
-		update_page_count(PG_LEVEL_2M, pages_2m);
-		update_page_count(PG_LEVEL_4K, pages_4k);
+		update_page_count(PGTABLE_LEVEL_PMD, pages_2m);
+		update_page_count(PGTABLE_LEVEL_PTE, pages_4k);
 
 		/*
 		 * local global flush tlb, which will flush the previous
arch/x86/mm/init_64.c +7 -7
index a68998f359bf..7587b8ef88bb 100644
@@ -508,7 +508,7 @@ phys_pte_init(pte_t *pte_page, unsigned long paddr, unsigned long paddr_end,
 		paddr_last = (paddr & PAGE_MASK) + PAGE_SIZE;
 	}
 
-	update_page_count(PG_LEVEL_4K, pages);
+	update_page_count(PGTABLE_LEVEL_PTE, pages);
 
 	return paddr_last;
 }
@@ -592,7 +592,7 @@ phys_pmd_init(pmd_t *pmd_page, unsigned long paddr, unsigned long paddr_end,
 		pmd_populate_kernel_init(&init_mm, pmd, pte, init);
 		spin_unlock(&init_mm.page_table_lock);
 	}
-	update_page_count(PG_LEVEL_2M, pages);
+	update_page_count(PGTABLE_LEVEL_PMD, pages);
 	return paddr_last;
 }
 
@@ -680,7 +680,7 @@ phys_pud_init(pud_t *pud_page, unsigned long paddr, unsigned long paddr_end,
 		spin_unlock(&init_mm.page_table_lock);
 	}
 
-	update_page_count(PG_LEVEL_1G, pages);
+	update_page_count(PGTABLE_LEVEL_PUD, pages);
 
 	return paddr_last;
 }
@@ -1116,7 +1116,7 @@ remove_pte_table(pte_t *pte_start, unsigned long addr, unsigned long end,
 	/* Call free_pte_table() in remove_pmd_table(). */
 	flush_tlb_all();
 	if (direct)
-		update_page_count(PG_LEVEL_4K, -pages);
+		update_page_count(PGTABLE_LEVEL_PTE, -pages);
 }
 
 static void __meminit
@@ -1162,7 +1162,7 @@ remove_pmd_table(pmd_t *pmd_start, unsigned long addr, unsigned long end,
 
 	/* Call free_pmd_table() in remove_pud_table(). */
 	if (direct)
-		update_page_count(PG_LEVEL_2M, -pages);
+		update_page_count(PGTABLE_LEVEL_PMD, -pages);
 }
 
 static void __meminit
@@ -1196,7 +1196,7 @@ remove_pud_table(pud_t *pud_start, unsigned long addr, unsigned long end,
 	}
 
 	if (direct)
-		update_page_count(PG_LEVEL_1G, -pages);
+		update_page_count(PGTABLE_LEVEL_PUD, -pages);
 }
 
 static void __meminit
@@ -1228,7 +1228,7 @@ remove_p4d_table(p4d_t *p4d_start, unsigned long addr, unsigned long end,
 	}
 
 	if (direct)
-		update_page_count(PG_LEVEL_512G, -pages);
+		update_page_count(PGTABLE_LEVEL_P4D, -pages);
 }
 
 /* start and end are both virtual address. */
arch/x86/mm/pat/set_memory.c +69 -29

234 lines not on this page · raw message

include/linux/pgtable.h +26 -0
index 780fe849ff8b..1f33e34a059f 100644
@@ -2294,6 +2294,7 @@ enum pgtable_level {
 	PGTABLE_LEVEL_P4D,
 	PGTABLE_LEVEL_PGD,
 };
+#define PGTABLE_LEVEL_NUM	(PGTABLE_LEVEL_PGD + 1)
 
 static inline const char *pgtable_level_to_str(enum pgtable_level level)
 {
@@ -2313,6 +2314,31 @@ static inline const char *pgtable_level_to_str(enum pgtable_level level)
 	}
 }
 
+#ifdef CONFIG_MMU
+static inline unsigned long pgtable_level_size(enum pgtable_level level)
+{
+	switch (level) {
+	case PGTABLE_LEVEL_PTE:
+		return PAGE_SIZE;
+	case PGTABLE_LEVEL_PMD:
+		return PMD_SIZE;
+	case PGTABLE_LEVEL_PUD:
+		return PUD_SIZE;
+	case PGTABLE_LEVEL_P4D:
+		return P4D_SIZE;
+	case PGTABLE_LEVEL_PGD:
+		return PGDIR_SIZE;
+	}
+
+	return 0;
+}
+
+static inline unsigned long pgtable_level_mask(enum pgtable_level level)
+{
+	return ~(pgtable_level_size(level) - 1);
+}
+#endif
+
 void ptval_bytes_to_hex_str(char *buf, size_t buf_size, const void *entry, size_t entry_size);
 
 #define ptval_to_str(buf, val)								\
Signature · 1 line
2.53.0
#20 lore raw

RFC PATCH v2 20/54 x86/mm/pat: index the CPA statistics by page table level

In reply to Mike Rapoport (Microsoft)

The CPA statistics have a variable per page size and every helper picks one with a level check. This works for the x86 page sizes, but other architectures can have different page sizes.

Index the counters by enum pgtable_level and derive the page size printed for each line from the level.

The output changes on 32-bit kernels without PAE: the large page lines say "4M pages" instead of "2M pages", and so do the always zero lines of the folded PUD level instead of "1G pages". The 4K line is spelled "4k" as in /proc/meminfo.

---
 arch/x86/mm/pat/set_memory.c | 87 ++++++++++++++++++++++++--------------------
 1 file changed, 48 insertions(+), 39 deletions(-)
arch/x86/mm/pat/set_memory.c +48 -39
index 36f5031f1a0e..44e350c54899 100644
@@ -142,54 +142,64 @@ static inline void collapse_page_count(int level) { }
 
 #ifdef CONFIG_X86_CPA_STATISTICS
 
-static unsigned long cpa_1g_checked;
-static unsigned long cpa_1g_sameprot;
-static unsigned long cpa_1g_preserved;
-static unsigned long cpa_2m_checked;
-static unsigned long cpa_2m_sameprot;
-static unsigned long cpa_2m_preserved;
-static unsigned long cpa_4k_install;
+static unsigned long cpa_checked[PGTABLE_LEVEL_NUM];
+static unsigned long cpa_sameprot[PGTABLE_LEVEL_NUM];
+static unsigned long cpa_preserved[PGTABLE_LEVEL_NUM];
 
-static inline void cpa_inc_1g_checked(void)
+static inline void cpa_inc_pxd_checked(enum pgtable_level level)
 {
-	cpa_1g_checked++;
+	cpa_checked[level]++;
 }
 
-static inline void cpa_inc_2m_checked(void)
+static inline void cpa_inc_pte_install(void)
 {
-	cpa_2m_checked++;
+	cpa_checked[PGTABLE_LEVEL_PTE]++;
 }
 
-static inline void cpa_inc_4k_install(void)
+static inline void cpa_inc_pxd_sameprot(enum pgtable_level level)
 {
-	cpa_4k_install++;
+	cpa_sameprot[level]++;
 }
 
-static inline void cpa_inc_lp_sameprot(int level)
+static inline void cpa_inc_pxd_preserved(enum pgtable_level level)
 {
-	if (level == PGTABLE_LEVEL_PUD)
-		cpa_1g_sameprot++;
-	else
-		cpa_2m_sameprot++;
+	cpa_preserved[level]++;
 }
 
-static inline void cpa_inc_lp_preserved(int level)
+static const char *cpa_size_str(enum pgtable_level level, char *buf, size_t len)
 {
-	if (level == PGTABLE_LEVEL_PUD)
-		cpa_1g_preserved++;
+	unsigned long size = pgtable_level_size(level);
+
+	if (size >= SZ_1G)
+		snprintf(buf, len, "%luG", size >> 30);
+	else if (size >= SZ_1M)
+		snprintf(buf, len, "%luM", size >> 20);
 	else
-		cpa_2m_preserved++;
+		snprintf(buf, len, "%luk", size >> 10);
+
+	return buf;
+}
+
+static void cpastats_show_level(struct seq_file *m, enum pgtable_level level)
+{
+	char sz[20];
+
+	cpa_size_str(level, sz, sizeof(sz));
+	seq_printf(m, "%s pages checked:     %16lu\n", sz, cpa_checked[level]);
+	seq_printf(m, "%s pages sameprot:    %16lu\n", sz, cpa_sameprot[level]);
+	seq_printf(m, "%s pages preserved:   %16lu\n", sz,
+		   cpa_preserved[level]);
 }
 
 static int cpastats_show(struct seq_file *m, void *p)
 {
-	seq_printf(m, "1G pages checked:     %16lu\n", cpa_1g_checked);
-	seq_printf(m, "1G pages sameprot:    %16lu\n", cpa_1g_sameprot);
-	seq_printf(m, "1G pages preserved:   %16lu\n", cpa_1g_preserved);
-	seq_printf(m, "2M pages checked:     %16lu\n", cpa_2m_checked);
-	seq_printf(m, "2M pages sameprot:    %16lu\n", cpa_2m_sameprot);
-	seq_printf(m, "2M pages preserved:   %16lu\n", cpa_2m_preserved);
-	seq_printf(m, "4K pages set-checked: %16lu\n", cpa_4k_install);
+	char sz[20];
+
+	cpastats_show_level(m, PGTABLE_LEVEL_PUD);
+	cpastats_show_level(m, PGTABLE_LEVEL_PMD);
+	seq_printf(m, "%s pages set-checked: %16lu\n",
+		   cpa_size_str(PGTABLE_LEVEL_PTE, sz, sizeof(sz)),
+		   cpa_checked[PGTABLE_LEVEL_PTE]);
 	return 0;
 }
 
@@ -213,11 +223,10 @@ static int __init cpa_stats_init(void)
 }
 late_initcall(cpa_stats_init);
 #else
-static inline void cpa_inc_1g_checked(void) { }
-static inline void cpa_inc_2m_checked(void) { }
-static inline void cpa_inc_4k_install(void) { }
-static inline void cpa_inc_lp_sameprot(int level) { }
-static inline void cpa_inc_lp_preserved(int level) { }
+static inline void cpa_inc_pxd_checked(enum pgtable_level level) { }
+static inline void cpa_inc_pte_install(void) { }
+static inline void cpa_inc_pxd_sameprot(enum pgtable_level level) { }
+static inline void cpa_inc_pxd_preserved(enum pgtable_level level) { }
 #endif
 
 
@@ -1041,17 +1050,17 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	case PGTABLE_LEVEL_PMD:
 		old_prot = pmd_pgprot(*(pmd_t *)kpte);
 		old_pfn = pmd_pfn(*(pmd_t *)kpte);
-		cpa_inc_2m_checked();
 		break;
 	case PGTABLE_LEVEL_PUD:
 		old_prot = pud_pgprot(*(pud_t *)kpte);
 		old_pfn = pud_pfn(*(pud_t *)kpte);
-		cpa_inc_1g_checked();
 		break;
 	default:
 		return -EINVAL;
 	}
 
+	cpa_inc_pxd_checked(level);
+
 	psize = pgtable_level_size(level);
 	pmask = pgtable_level_mask(level);
 
@@ -1097,7 +1106,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	 * range.
 	 */
 	if (pgprot_val(req_prot) == pgprot_val(pgprot_large_2_4k(old_prot))) {
-		cpa_inc_lp_sameprot(level);
+		cpa_inc_pxd_sameprot(level);
 		return 0;
 	}
 
@@ -1133,7 +1142,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	new_pte = cpa_pte(level, old_pfn, new_prot);
 	__set_pmd_pte(kpte, address, new_pte);
 	cpa->state |= CPA_ST_FLUSHTLB;
-	cpa_inc_lp_preserved(level);
+	cpa_inc_pxd_preserved(level);
 	return 0;
 }
 
@@ -1866,7 +1875,7 @@ static int __change_page_attr(struct cpa_data *cpa)
 		pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
 		pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
 
-		cpa_inc_4k_install();
+		cpa_inc_pte_install();
 		/* Hand in lpsize = 0 to enforce the protection mechanism */
 		new_prot = static_protections(new_prot, address, pfn, 1, 0,
 					      CPA_PROTECT);
Signature · 1 line
2.53.0
#21 lore raw

RFC PATCH v2 21/54 x86/mm/pat: introduce struct cpa_leaf

In reply to Mike Rapoport (Microsoft)

The functions that handle a mapping found by the CPA lookup get the page table entry, its level and the address. Each of them decodes the pfn and the protection again.

Add struct cpa_leaf that describes the mapping and is filled once by cpa_lookup().

The leaf keeps the protection in the 4K format at every level, so the large page path applies the requested changes as is and converts the resulting protection to the large page format only to write a page table entry.

---
 arch/x86/mm/pat/set_memory.c | 194 ++++++++++++++++++++++---------------------
 1 file changed, 100 insertions(+), 94 deletions(-)
arch/x86/mm/pat/set_memory.c +100 -94
index 44e350c54899..304b7ad26c45 100644
@@ -51,6 +51,15 @@ struct cpa_data {
 	unsigned int	state;
 };
 
+struct cpa_leaf {
+	pte_t			*kpte;
+	enum pgtable_level	level;
+	unsigned long		addr;
+	unsigned long		size;
+	unsigned long		pfn;
+	pgprot_t		prot;
+};
+
 enum cpa_warn {
 	CPA_PROTECT,
 	CPA_DETECT,
@@ -887,12 +896,53 @@ static pte_t *cpa_lookup_in_pgd(pgd_t *pgdp, unsigned long address,
 	return pte_offset_kernel(pmdp, address);
 }
 
-static pte_t *_lookup_address_cpa(struct cpa_data *cpa, unsigned long address,
-				  enum pgtable_level *level)
+static void cpa_decode_leaf(struct cpa_leaf *leaf)
+{
+	enum pgtable_level level = leaf->level;
+	pte_t *kpte = leaf->kpte;
+	pte_t pte;
+	pmd_t pmd;
+	pud_t pud;
+
+	switch (level) {
+	case PGTABLE_LEVEL_PTE:
+		pte = *kpte;
+		leaf->pfn = pte_pfn(pte);
+		leaf->prot = pte_pgprot(pte);
+		break;
+	case PGTABLE_LEVEL_PMD:
+		pmd = *(pmd_t *)kpte;
+		leaf->pfn = pmd_pfn(pmd);
+		leaf->prot = pgprot_large_2_4k(pmd_pgprot(pmd));
+		break;
+	case PGTABLE_LEVEL_PUD:
+		pud = *(pud_t *)kpte;
+		leaf->pfn = pud_pfn(pud);
+		leaf->prot = pgprot_large_2_4k(pud_pgprot(pud));
+		break;
+	default:
+		leaf->pfn = 0;
+		leaf->prot = __pgprot(0);
+		break;
+	}
+}
+
+static pte_t *cpa_lookup(struct cpa_data *cpa, unsigned long address,
+			 struct cpa_leaf *leaf)
 {
 	pgd_t *pgd = cpa_pgd(cpa, address);
 
-	return cpa_lookup_in_pgd(pgd, address, level);
+	leaf->kpte = cpa_lookup_in_pgd(pgd, address, &leaf->level);
+	if (!leaf->kpte)
+		return NULL;
+	if (leaf->level == PGTABLE_LEVEL_PTE && pte_none(ptep_get(leaf->kpte)))
+		return NULL;
+
+	leaf->size = pgtable_level_size(leaf->level);
+	leaf->addr = address & pgtable_level_mask(leaf->level);
+	cpa_decode_leaf(leaf);
+
+	return leaf->kpte;
 }
 
 /*
@@ -1035,53 +1085,36 @@ static pte_t cpa_pte(enum pgtable_level level, unsigned long pfn, pgprot_t prot)
 	return pfn_pte(pfn, prot);
 }
 
-static int should_split_large_page(pte_t *kpte, unsigned long address,
-				   enum pgtable_level level,
-				   struct cpa_data *cpa)
+static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
-	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
-	pgprot_t old_prot, new_prot, req_prot;
+	unsigned long address = __cpa_addr(cpa, cpa->curpage);
+	enum pgtable_level level = leaf->level;
+	unsigned long lpaddr = leaf->addr;
+	unsigned long old_pfn = leaf->pfn;
+	unsigned long psize = leaf->size;
+	pgprot_t old_prot = leaf->prot;
+	unsigned long numpages, pfn;
+	pgprot_t new_prot, req_prot;
+	pte_t *kpte = leaf->kpte;
 	pte_t new_pte;
 
 	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
 
-	switch (level) {
-	case PGTABLE_LEVEL_PMD:
-		old_prot = pmd_pgprot(*(pmd_t *)kpte);
-		old_pfn = pmd_pfn(*(pmd_t *)kpte);
-		break;
-	case PGTABLE_LEVEL_PUD:
-		old_prot = pud_pgprot(*(pud_t *)kpte);
-		old_pfn = pud_pfn(*(pud_t *)kpte);
-		break;
-	default:
+	if (level != PGTABLE_LEVEL_PMD && level != PGTABLE_LEVEL_PUD)
 		return -EINVAL;
-	}
 
 	cpa_inc_pxd_checked(level);
 
-	psize = pgtable_level_size(level);
-	pmask = pgtable_level_mask(level);
-
 	/*
 	 * Calculate the number of pages, which fit into this large
 	 * page starting at address:
 	 */
-	lpaddr = (address + psize) & pmask;
-	numpages = (lpaddr - address) >> PAGE_SHIFT;
+	numpages = (lpaddr + psize - address) >> PAGE_SHIFT;
 	if (numpages < cpa->numpages)
 		cpa->numpages = numpages;
 
-	/*
-	 * We are safe now. Check whether the new pgprot is the same:
-	 * Convert protection attributes to 4k-format, as cpa->mask* are set
-	 * up accordingly.
-	 */
-
-	/* Clear PSE (aka _PAGE_PAT) and move PAT bit to correct position */
-	req_prot = pgprot_large_2_4k(old_prot);
-
+	req_prot = old_prot;
 	pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
 	pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
 
@@ -1092,11 +1125,6 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	pfn = old_pfn + ((address & (psize - 1)) >> PAGE_SHIFT);
 	cpa->pfn = pfn;
 
-	/*
-	 * Calculate the large page base address and the number of 4K pages
-	 * in the large page
-	 */
-	lpaddr = address & pmask;
 	numpages = psize >> PAGE_SHIFT;
 
 	/*
@@ -1105,7 +1133,7 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 	 * required independent of alignment and length of the requested
 	 * range.
 	 */
-	if (pgprot_val(req_prot) == pgprot_val(pgprot_large_2_4k(old_prot))) {
+	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
 		cpa_inc_pxd_sameprot(level);
 		return 0;
 	}
@@ -1147,44 +1175,25 @@ static int should_split_large_page(pte_t *kpte, unsigned long address,
 }
 
 static int
-__split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
-		   enum pgtable_level level, pte_t *pbase)
+__split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 {
-	unsigned long ref_pfn, pfn, pfninc = 1;
+	unsigned long address = __cpa_addr(cpa, cpa->curpage);
 	struct page *base = virt_to_page(pbase);
-	pgprot_t ref_prot;
+	enum pgtable_level level = leaf->level;
+	unsigned long pfn = leaf->pfn;
+	pgprot_t prot = leaf->prot;
+	pte_t *kpte = leaf->kpte;
+	unsigned long pfninc;
 	unsigned int i;
 
-	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
-
-	switch (level) {
-	case PGTABLE_LEVEL_PMD:
-		ref_prot = pmd_pgprot(*(pmd_t *)kpte);
-		/*
-		 * Clear PSE (aka _PAGE_PAT) and move
-		 * PAT bit to correct position.
-		 */
-		ref_prot = pgprot_large_2_4k(ref_prot);
-		ref_pfn = pmd_pfn(*(pmd_t *)kpte);
-		break;
-
-	case PGTABLE_LEVEL_PUD:
-		ref_prot = pud_pgprot(*(pud_t *)kpte);
-		ref_pfn = pud_pfn(*(pud_t *)kpte);
-		pfninc = PMD_SIZE >> PAGE_SHIFT;
-		ref_prot = pgprot_large_2_4k(ref_prot);
-		break;
-
-	default:
+	if (level != PGTABLE_LEVEL_PMD && level != PGTABLE_LEVEL_PUD)
 		return -EINVAL;
-	}
 
-	/*
-	 * Get the target pfn from the original entry:
-	 */
-	pfn = ref_pfn;
+	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
+
+	pfninc = pgtable_level_size(level - 1) >> PAGE_SHIFT;
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
-		set_pte(pbase + i, cpa_pte(level - 1, pfn, ref_prot));
+		set_pte(pbase + i, cpa_pte(level - 1, pfn, prot));
 
 	if (within(address, PAGE_OFFSET,
 		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
@@ -1222,10 +1231,11 @@ __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 	return 0;
 }
 
-static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
-			    unsigned long address)
+static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
-	enum pgtable_level level;
+	unsigned long address = __cpa_addr(cpa, cpa->curpage);
+	pte_t *kpte = leaf->kpte;
+	struct cpa_leaf tmp;
 	pte_t *pte;
 	int ret = 0;
 
@@ -1239,10 +1249,11 @@ static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 	 * Check for races, another CPU might have split this page
 	 * up for us already:
 	 */
-	if (_lookup_address_cpa(cpa, address, &level) != kpte)
+	if (cpa_lookup(cpa, address, &tmp) != kpte)
 		goto out;
+	*leaf = tmp;
 
-	ret = __split_large_page(cpa, kpte, address, level, pte);
+	ret = __split_large_page(cpa, leaf, pte);
 	if (ret)
 		goto out;
 
@@ -1851,26 +1862,21 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr)
 
 static int __change_page_attr(struct cpa_data *cpa)
 {
-	enum pgtable_level level;
 	unsigned long address;
-	pte_t *kpte, old_pte;
-	int do_split, err;
+	struct cpa_leaf leaf;
+	int do_split, ret;
 
 	address = __cpa_addr(cpa, cpa->curpage);
 repeat:
-	kpte = _lookup_address_cpa(cpa, address, &level);
-	if (!kpte)
+	if (!cpa_lookup(cpa, address, &leaf))
 		return __cpa_process_fault(cpa, address);
 
-	old_pte = *kpte;
-	if (pte_none(old_pte))
-		return __cpa_process_fault(cpa, address);
-
-	if (level == PGTABLE_LEVEL_PTE) {
+	if (leaf.level == PGTABLE_LEVEL_PTE) {
+		pte_t old_pte = *leaf.kpte;
+		pgprot_t old_prot = leaf.prot;
+		pgprot_t new_prot = leaf.prot;
+		unsigned long pfn = leaf.pfn;
 		pte_t new_pte;
-		pgprot_t old_prot = pte_pgprot(old_pte);
-		pgprot_t new_prot = pte_pgprot(old_pte);
-		unsigned long pfn = pte_pfn(old_pte);
 
 		pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
 		pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
@@ -1887,13 +1893,13 @@ static int __change_page_attr(struct cpa_data *cpa)
 		 * after all we're only going to change its attributes
 		 * not the memory it points to
 		 */
-		new_pte = cpa_pte(level, pfn, new_prot);
+		new_pte = cpa_pte(leaf.level, pfn, new_prot);
 		cpa->pfn = pfn;
 		/*
 		 * Do we really change anything ?
 		 */
 		if (pte_val(old_pte) != pte_val(new_pte)) {
-			set_pte_atomic(kpte, new_pte);
+			set_pte_atomic(leaf.kpte, new_pte);
 			cpa->state |= CPA_ST_FLUSHTLB;
 		}
 		cpa->numpages = 1;
@@ -1904,7 +1910,7 @@ static int __change_page_attr(struct cpa_data *cpa)
 	 * Check, whether we can keep the large page intact
 	 * and just change the pte:
 	 */
-	do_split = should_split_large_page(kpte, address, level, cpa);
+	do_split = should_split_large_page(cpa, &leaf);
 	/*
 	 * When the range fits into the existing large page,
 	 * return. cp->numpages and cpa->tlbflush have been updated in
@@ -1916,11 +1922,11 @@ static int __change_page_attr(struct cpa_data *cpa)
 	/*
 	 * We have to split the large page:
 	 */
-	err = split_large_page(cpa, kpte, address);
-	if (!err)
+	ret = split_large_page(cpa, &leaf);
+	if (!ret)
 		goto repeat;
 
-	return err;
+	return ret;
 }
 
 static int __change_page_attr_set_clr(struct cpa_data *cpa);
Signature · 1 line
2.53.0
#22 lore raw

RFC PATCH v2 22/54 x86/mm/pat: consolidate calculation of the new protection

In reply to Mike Rapoport (Microsoft)

The large page path and the PTE path of CPA both apply the request masks to the current protection and then run static_protections() and verify_rwx() on the result. Each path spells the arguments differently.

The generic core will need this calculation as a hook.

Move it to cpa_req_prot() and cpa_new_prot() and use them in both PTE and PxD paths.

---
 arch/x86/mm/pat/set_memory.c | 54 +++++++++++++++++++++++++++++---------------
 1 file changed, 36 insertions(+), 18 deletions(-)
arch/x86/mm/pat/set_memory.c +36 -18
index 304b7ad26c45..cb503e41340b 100644
@@ -1085,6 +1085,38 @@ static pte_t cpa_pte(enum pgtable_level level, unsigned long pfn, pgprot_t prot)
 	return pfn_pte(pfn, prot);
 }
 
+static pgprot_t cpa_req_prot(const struct cpa_data *cpa,
+			     const struct cpa_leaf *leaf)
+{
+	return __pgprot((pgprot_val(leaf->prot) & ~pgprot_val(cpa->mask_clr)) |
+			pgprot_val(cpa->mask_set));
+}
+
+static pgprot_t cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf)
+{
+	pgprot_t prot = cpa_req_prot(cpa, leaf);
+	enum pgtable_level level = leaf->level;
+	unsigned long size = leaf->size;
+	unsigned long addr = leaf->addr;
+	pgprot_t old_prot = leaf->prot;
+	unsigned long pfn = leaf->pfn;
+	int warnlvl = CPA_PROTECT;
+	unsigned long lpsize = 0;
+	unsigned long numpages;
+
+	numpages = size >> PAGE_SHIFT;
+
+	if (level != PGTABLE_LEVEL_PTE) {
+		warnlvl = CPA_DETECT;
+		lpsize = size;
+	}
+
+	/* A PTE hands in lpsize = 0 to enforce the protection mechanism */
+	prot = static_protections(prot, addr, pfn, numpages, lpsize, warnlvl);
+
+	return verify_rwx(cpa, old_prot, prot, addr, pfn, numpages);
+}
+
 static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
 	unsigned long address = __cpa_addr(cpa, cpa->curpage);
@@ -1114,9 +1146,7 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	if (numpages < cpa->numpages)
 		cpa->numpages = numpages;
 
-	req_prot = old_prot;
-	pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
-	pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
+	req_prot = cpa_req_prot(cpa, leaf);
 
 	/*
 	 * old_pfn points to the large page base pfn. So we need to add the
@@ -1148,11 +1178,7 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	 * Check whether the requested pgprot is conflicting with a static
 	 * protection requirement in the large page.
 	 */
-	new_prot = static_protections(req_prot, lpaddr, old_pfn, numpages,
-				      psize, CPA_DETECT);
-
-	new_prot = verify_rwx(cpa, old_prot, new_prot, lpaddr, old_pfn,
-			      numpages);
+	new_prot = cpa_new_prot(cpa, leaf);
 
 	/*
 	 * If there is a conflict, split the large page.
@@ -1873,20 +1899,12 @@ static int __change_page_attr(struct cpa_data *cpa)
 
 	if (leaf.level == PGTABLE_LEVEL_PTE) {
 		pte_t old_pte = *leaf.kpte;
-		pgprot_t old_prot = leaf.prot;
-		pgprot_t new_prot = leaf.prot;
+		pgprot_t new_prot;
 		unsigned long pfn = leaf.pfn;
 		pte_t new_pte;
 
-		pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
-		pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
-
 		cpa_inc_pte_install();
-		/* Hand in lpsize = 0 to enforce the protection mechanism */
-		new_prot = static_protections(new_prot, address, pfn, 1, 0,
-					      CPA_PROTECT);
-
-		new_prot = verify_rwx(cpa, old_prot, new_prot, address, pfn, 1);
+		new_prot = cpa_new_prot(cpa, &leaf);
 
 		/*
 		 * We need to keep the pfn from the existing PTE,
Signature · 1 line
2.53.0
#23 lore raw

RFC PATCH v2 23/54 x86/mm/pat: allocate the page tables for a split by level

In reply to Mike Rapoport (Microsoft)

split_large_page() allocates the page table for a split with pte_alloc_one_kernel() regardless of the level it splits. A PMD table that replaces a PUD is allocated and announced to paravirt as a PTE table.

While in practice this only matters for the accounting of page table pages, having proper allocation helpers not only makes that accounting right but will allow architectures to override page table allocation methods when core CPA logic moves to the generic code.

Add helpers to allocate and free page tables with the appropriate function:
pte_alloc_one_kernel() for a table that replaces PMD and pmd_alloc_one() for a table that replaces PUD.

Use paravirt_alloc_pmd() to notify PV guests about the new page table that replaces a PUD.

---
 arch/x86/mm/pat/set_memory.c | 31 +++++++++++++++++++++++++------
 1 file changed, 25 insertions(+), 6 deletions(-)
arch/x86/mm/pat/set_memory.c +25 -6
index cb503e41340b..0a2d19064f23 100644
@@ -1215,7 +1215,10 @@ __split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 	if (level != PGTABLE_LEVEL_PMD && level != PGTABLE_LEVEL_PUD)
 		return -EINVAL;
 
-	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
+	if (level == PGTABLE_LEVEL_PMD)
+		paravirt_alloc_pte(&init_mm, page_to_pfn(base));
+	else
+		paravirt_alloc_pmd(&init_mm, page_to_pfn(base));
 
 	pfninc = pgtable_level_size(level - 1) >> PAGE_SHIFT;
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
@@ -1257,18 +1260,34 @@ __split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 	return 0;
 }
 
+static void *cpa_alloc_pgtable(struct cpa_leaf *leaf)
+{
+	if (leaf->level == PGTABLE_LEVEL_PMD)
+		return pte_alloc_one_kernel(&init_mm);
+
+	return pmd_alloc_one(&init_mm, leaf->addr);
+}
+
+static void cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
+{
+	if (leaf->level == PGTABLE_LEVEL_PMD)
+		pte_free_kernel(&init_mm, table);
+	else
+		pmd_free(&init_mm, table);
+}
+
 static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
 	unsigned long address = __cpa_addr(cpa, cpa->curpage);
 	pte_t *kpte = leaf->kpte;
 	struct cpa_leaf tmp;
-	pte_t *pte;
+	void *table;
 	int ret = 0;
 
 	spin_unlock(&cpa_lock);
-	pte = pte_alloc_one_kernel(&init_mm);
+	table = cpa_alloc_pgtable(leaf);
 	spin_lock(&cpa_lock);
-	if (!pte)
+	if (!table)
 		return -ENOMEM;
 
 	/*
@@ -1279,14 +1298,14 @@ static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 		goto out;
 	*leaf = tmp;
 
-	ret = __split_large_page(cpa, leaf, pte);
+	ret = __split_large_page(cpa, leaf, table);
 	if (ret)
 		goto out;
 
 	return 0;
 
 out:
-	pte_free_kernel(&init_mm, pte);
+	cpa_free_pgtable(leaf, table);
 	return ret;
 }
 
Signature · 1 line
2.53.0
#24 lore raw

RFC PATCH v2 24/54 x86/mm/pat: detect unchanged mappings by comparing protections

In reply to Mike Rapoport (Microsoft)

CPA decides whether a mapping changes by encoding the new page table entry and comparing it with the existing one.

It would be suboptimal to encode actual entries in the generic code for every comparison of the existing, requested and new protections, as every architecture would need one more out-of-line hook for it.

cpa_leaf by definition has the decoded protection which can be used in comparisons.

Compare the new protection with the decoded one and encode only the page table entries that are written, as the last step.

Encoding masks out the bits the CPU does not support and _PAGE_GLOBAL bit of a non-present entry, comparing protections does not. set_memory_global() on a CPU without PGE or on a non-present page now rewrites the PTEs with the same value and flushes the TLB. Its only caller changes the kernel text, which is always present, once at boot.

---
 arch/x86/mm/pat/set_memory.c | 14 +++-----------
 1 file changed, 3 insertions(+), 11 deletions(-)
arch/x86/mm/pat/set_memory.c +3 -11
index 0a2d19064f23..f4d3e2d9c3c9 100644
@@ -1917,26 +1917,18 @@ static int __change_page_attr(struct cpa_data *cpa)
 		return __cpa_process_fault(cpa, address);
 
 	if (leaf.level == PGTABLE_LEVEL_PTE) {
-		pte_t old_pte = *leaf.kpte;
 		pgprot_t new_prot;
 		unsigned long pfn = leaf.pfn;
-		pte_t new_pte;
 
 		cpa_inc_pte_install();
 		new_prot = cpa_new_prot(cpa, &leaf);
-
-		/*
-		 * We need to keep the pfn from the existing PTE,
-		 * after all we're only going to change its attributes
-		 * not the memory it points to
-		 */
-		new_pte = cpa_pte(leaf.level, pfn, new_prot);
 		cpa->pfn = pfn;
 		/*
 		 * Do we really change anything ?
 		 */
-		if (pte_val(old_pte) != pte_val(new_pte)) {
-			set_pte_atomic(leaf.kpte, new_pte);
+		if (pgprot_val(new_prot) != pgprot_val(leaf.prot)) {
+			set_pte_atomic(leaf.kpte,
+				       cpa_pte(leaf.level, pfn, new_prot));
 			cpa->state |= CPA_ST_FLUSHTLB;
 		}
 		cpa->numpages = 1;
Signature · 1 line
2.53.0
#25 lore raw

RFC PATCH v2 25/54 x86/mm/pat: add cpa_is_direct_map()

In reply to Mike Rapoport (Microsoft)

CPA open codes the direct map range check in five places, and the generic CPA core will need the same check.

Move the check to cpa_is_direct_map().

No functional change.

---
 arch/x86/mm/pat/set_memory.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
arch/x86/mm/pat/set_memory.c +11 -10
index f4d3e2d9c3c9..cbbc51be4de7 100644
@@ -245,6 +245,12 @@ within(unsigned long addr, unsigned long start, unsigned long end)
 	return addr >= start && addr < end;
 }
 
+static inline bool cpa_is_direct_map(unsigned long addr)
+{
+	return within(addr, PAGE_OFFSET,
+		      PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT));
+}
+
 #ifdef CONFIG_X86_64
 
 static inline int
@@ -1224,8 +1230,7 @@ __split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
 		set_pte(pbase + i, cpa_pte(level - 1, pfn, prot));
 
-	if (within(address, PAGE_OFFSET,
-		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
+	if (cpa_is_direct_map(address))
 		split_page_count(level);
 
 	/*
@@ -1375,8 +1380,7 @@ static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
 		}
 	}
 
-	if (within(addr, PAGE_OFFSET,
-		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
+	if (cpa_is_direct_map(addr))
 		collapse_page_count(PGTABLE_LEVEL_PMD);
 
 	return 1;
@@ -1423,8 +1427,7 @@ static int collapse_pud_page(pud_t *pud, unsigned long addr,
 	list_add(&page_ptdesc(pud_page(*pud))->pt_list, pgtables);
 	set_pud(pud, pfn_pud(pfn, pmd_pgprot(first)));
 
-	if (within(addr, PAGE_OFFSET,
-		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))
+	if (cpa_is_direct_map(addr))
 		collapse_page_count(PGTABLE_LEVEL_PUD);
 
 	return 1;
@@ -1887,8 +1890,7 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr)
 	 * one virtual address page and its pfn. TBD: numpages can be set based
 	 * on the initial value and the level returned by lookup_address().
 	 */
-	if (within(vaddr, PAGE_OFFSET,
-		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT))) {
+	if (cpa_is_direct_map(vaddr)) {
 		cpa->numpages = 1;
 		cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
 		return 0;
@@ -1977,8 +1979,7 @@ static int cpa_process_alias(struct cpa_data *cpa)
 	 * mapping already:
 	 */
 	vaddr = __cpa_addr(cpa, cpa->curpage);
-	if (!(within(vaddr, PAGE_OFFSET,
-		    PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))) {
+	if (!cpa_is_direct_map(vaddr)) {
 
 		alias_cpa = *cpa;
 		alias_cpa.addr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
Signature · 1 line
2.53.0
#26 lore raw

RFC PATCH v2 26/54 x86/mm/pat: implement set_memory_*() with a table of operations

In reply to Mike Rapoport (Microsoft)

Every architecture that implements set_memory_*() and set_direct_map_*_noflush() has a function for each operation, and the functions differ only in the masks they pass to the page table walk. s390 and powerpc already translate an operation to masks in one place.

These entry points are going to become generic, with the masks of each operation provided by the architecture.

Describe the operations of x86 in a table of masks and request flags, and implement set_memory_*() and set_direct_map_*_noflush() with a single function that takes the request from the table.

No functional change.

---
 arch/x86/mm/pat/set_memory.c | 136 ++++++++++++++++++++++++++++---------------
 1 file changed, 88 insertions(+), 48 deletions(-)
arch/x86/mm/pat/set_memory.c +88 -48
index cbbc51be4de7..08dc69317931 100644
@@ -2392,42 +2392,98 @@ int clear_mce_nospec(unsigned long pfn)
 EXPORT_SYMBOL_GPL(clear_mce_nospec);
 #endif /* CONFIG_X86_64 */
 
-int set_memory_x(unsigned long addr, int numpages)
+enum cpa_op {
+	CPA_OP_RO,
+	CPA_OP_RW,
+	CPA_OP_X,
+	CPA_OP_NX,
+	CPA_OP_ROX,
+	CPA_OP_DIRECT_MAP_INVALID,
+	CPA_OP_DIRECT_MAP_DEFAULT,
+	CPA_OP_NR
+};
+
+struct cpa_op_prot {
+	pgprot_t	set;
+	pgprot_t	clr;
+	unsigned int	req;
+};
+
+static const struct cpa_op_prot cpa_ops[CPA_OP_NR] = {
+	[CPA_OP_RO]	= { .clr = __pgprot(_PAGE_RW | _PAGE_DIRTY) },
+	[CPA_OP_RW]	= { .set = __pgprot(_PAGE_RW) },
+	[CPA_OP_X]	= { .clr = __pgprot(_PAGE_NX) },
+	[CPA_OP_NX]	= { .set = __pgprot(_PAGE_NX) },
+	[CPA_OP_ROX] = {
+		.clr = __pgprot(_PAGE_RW | _PAGE_DIRTY | _PAGE_NX),
+		.req = CPA_REQ_COLLAPSE,
+	},
+	[CPA_OP_DIRECT_MAP_INVALID] = {
+		.clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
+	},
+	[CPA_OP_DIRECT_MAP_DEFAULT] = {
+		.set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
+	},
+};
+
+static void cpa_init_op(struct cpa_data *cpa, const struct cpa_op_prot *prot)
 {
-	if (!(__supported_pte_mask & _PAGE_NX))
-		return 0;
+	cpa->mask_set = prot->set;
+	cpa->mask_clr = prot->clr;
+	cpa->flags |= prot->req;
+}
+
+static int arch_cpa_prepare(struct cpa_data *cpa, enum cpa_op op)
+{
+	cpa_init_op(cpa, &cpa_ops[op]);
 
-	return change_page_attr_clear(addr, numpages, __pgprot(_PAGE_NX));
+	if (!(__supported_pte_mask & _PAGE_NX)) {
+		pgprot_val(cpa->mask_set) &= ~_PAGE_NX;
+		pgprot_val(cpa->mask_clr) &= ~_PAGE_NX;
+	}
+
+	return 0;
 }
 
-int set_memory_nx(unsigned long addr, int numpages)
+static int set_memory_op(unsigned long addr, int numpages, enum cpa_op op)
 {
-	if (!(__supported_pte_mask & _PAGE_NX))
-		return 0;
+	struct cpa_data cpa = {
+		.addr = addr,
+		.numpages = numpages,
+	};
+	int ret;
+
+	ret = arch_cpa_prepare(&cpa, op);
+	if (ret)
+		return ret;
 
-	return change_page_attr_set(addr, numpages, __pgprot(_PAGE_NX));
+	return change_page_attr_set_clr(addr, numpages, cpa.mask_set,
+					cpa.mask_clr, cpa.flags);
 }
 
-int set_memory_ro(unsigned long addr, int numpages)
+int set_memory_x(unsigned long addr, int numpages)
 {
-	return change_page_attr_clear(addr, numpages,
-				      __pgprot(_PAGE_RW | _PAGE_DIRTY));
+	return set_memory_op(addr, numpages, CPA_OP_X);
 }
 
-int set_memory_rox(unsigned long addr, int numpages)
+int set_memory_nx(unsigned long addr, int numpages)
 {
-	pgprot_t clr = __pgprot(_PAGE_RW | _PAGE_DIRTY);
+	return set_memory_op(addr, numpages, CPA_OP_NX);
+}
 
-	if (__supported_pte_mask & _PAGE_NX)
-		clr.pgprot |= _PAGE_NX;
+int set_memory_ro(unsigned long addr, int numpages)
+{
+	return set_memory_op(addr, numpages, CPA_OP_RO);
+}
 
-	return change_page_attr_set_clr(addr, numpages, __pgprot(0), clr,
-					CPA_REQ_COLLAPSE);
+int set_memory_rox(unsigned long addr, int numpages)
+{
+	return set_memory_op(addr, numpages, CPA_OP_ROX);
 }
 
 int set_memory_rw(unsigned long addr, int numpages)
 {
-	return change_page_attr_set(addr, numpages, __pgprot(_PAGE_RW));
+	return set_memory_op(addr, numpages, CPA_OP_RW);
 }
 
 int set_memory_np(unsigned long addr, int numpages)
@@ -2692,50 +2748,34 @@ int set_pages_rw(struct page *page, int numpages)
 	return set_memory_rw(addr, numpages);
 }
 
-static int __set_pages_p(struct page *page, int numpages)
+static int set_direct_map(struct page *page, unsigned int nr, enum cpa_op op)
 {
-	struct cpa_data cpa = { .addr = (unsigned long)page_address(page),
-				.pgd = NULL,
-				.numpages = numpages,
-				.mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
-				.mask_clr = __pgprot(0),
-				.flags = CPA_REQ_NO_CHECK_ALIAS };
-
-	/*
-	 * No alias checking needed for setting present flag. otherwise,
-	 * we may need to break large pages for 64-bit kernel text
-	 * mappings (this adds to complexity if we want to do this from
-	 * atomic context especially). Let's keep it simple!
-	 */
-	return __change_page_attr_set_clr(&cpa);
-}
+	struct cpa_data cpa = {
+		.addr = (unsigned long)page_address(page),
+		.numpages = nr,
+		.flags = CPA_REQ_NO_CHECK_ALIAS,
+	};
+	int ret;
 
-static int __set_pages_np(struct page *page, int numpages)
-{
-	struct cpa_data cpa = { .addr = (unsigned long)page_address(page),
-				.pgd = NULL,
-				.numpages = numpages,
-				.mask_set = __pgprot(0),
-				.mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
-				.flags = CPA_REQ_NO_CHECK_ALIAS };
+	ret = arch_cpa_prepare(&cpa, op);
+	if (ret)
+		return ret;
 
 	/*
-	 * No alias checking needed for setting not present flag. otherwise,
-	 * we may need to break large pages for 64-bit kernel text
-	 * mappings (this adds to complexity if we want to do this from
-	 * atomic context especially). Let's keep it simple!
+	 * set_direct_map_*_noflush() change only the direct map, not its
+	 * aliases.
 	 */
 	return __change_page_attr_set_clr(&cpa);
 }
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr)
 {
-	return __set_pages_np(page, nr);
+	return set_direct_map(page, nr, CPA_OP_DIRECT_MAP_INVALID);
 }
 
 int set_direct_map_default_noflush(struct page *page, unsigned int nr)
 {
-	return __set_pages_p(page, nr);
+	return set_direct_map(page, nr, CPA_OP_DIRECT_MAP_DEFAULT);
 }
 
 #ifdef CONFIG_DEBUG_PAGEALLOC
Signature · 1 line
2.53.0
#27 lore raw

RFC PATCH v2 27/54 x86/mm/pat: prepare the direct map counters for the generic code

In reply to Mike Rapoport (Microsoft)

The direct map counters are going to move to the generic CPA core, so that every architecture that uses the core gets them.

Prepare them for the move:

* rename them to direct_map_count_*(), which better describes what they do and does not collide with the update_page_count() of powerpc and s390
* declare direct_map_count_update() in mm_internal.h, where enum pgtable_level is visible
* print the DirectMap lines of /proc/meminfo in a loop over the page table levels, so that every architecture can choose its levels

The output in /proc/meminfo does not change, except that 2-level x86-32 booted with "gbpages" no longer prints a DirectMap1G line. It never maps 1G pages, so the line was always 0 kB.

---
 arch/x86/include/asm/pgtable_types.h |  6 ---
 arch/x86/mm/init_32.c                |  4 +-
 arch/x86/mm/init_64.c                | 14 +++---
 arch/x86/mm/mm_internal.h            |  7 +++
 arch/x86/mm/pat/set_memory.c         | 92 ++++++++++++++++++++----------------
 5 files changed, 66 insertions(+), 57 deletions(-)
arch/x86/include/asm/pgtable_types.h +0 -6
index b1a669e775f4..60ee4209c528 100644
@@ -551,12 +551,6 @@ enum pg_level {
 	PG_LEVEL_NUM
 };
 
-#ifdef CONFIG_PROC_FS
-extern void update_page_count(int level, unsigned long pages);
-#else
-static inline void update_page_count(int level, unsigned long pages) { }
-#endif
-
 /*
  * Helper function that returns the kernel pagetable entry controlling
  * the virtual address 'address'. NULL means no pagetable entry present.
arch/x86/mm/init_32.c +2 -2
index 1895a71316c2..d9e835aaf912 100644
@@ -367,8 +367,8 @@ kernel_physical_mapping_init(unsigned long start,
 		 * update direct mapping page count only in the first
 		 * iteration.
 		 */
-		update_page_count(PGTABLE_LEVEL_PMD, pages_2m);
-		update_page_count(PGTABLE_LEVEL_PTE, pages_4k);
+		direct_map_count_update(PGTABLE_LEVEL_PMD, pages_2m);
+		direct_map_count_update(PGTABLE_LEVEL_PTE, pages_4k);
 
 		/*
 		 * local global flush tlb, which will flush the previous
arch/x86/mm/init_64.c +7 -7
index 7587b8ef88bb..e2592ed2d905 100644
@@ -508,7 +508,7 @@ phys_pte_init(pte_t *pte_page, unsigned long paddr, unsigned long paddr_end,
 		paddr_last = (paddr & PAGE_MASK) + PAGE_SIZE;
 	}
 
-	update_page_count(PGTABLE_LEVEL_PTE, pages);
+	direct_map_count_update(PGTABLE_LEVEL_PTE, pages);
 
 	return paddr_last;
 }
@@ -592,7 +592,7 @@ phys_pmd_init(pmd_t *pmd_page, unsigned long paddr, unsigned long paddr_end,
 		pmd_populate_kernel_init(&init_mm, pmd, pte, init);
 		spin_unlock(&init_mm.page_table_lock);
 	}
-	update_page_count(PGTABLE_LEVEL_PMD, pages);
+	direct_map_count_update(PGTABLE_LEVEL_PMD, pages);
 	return paddr_last;
 }
 
@@ -680,7 +680,7 @@ phys_pud_init(pud_t *pud_page, unsigned long paddr, unsigned long paddr_end,
 		spin_unlock(&init_mm.page_table_lock);
 	}
 
-	update_page_count(PGTABLE_LEVEL_PUD, pages);
+	direct_map_count_update(PGTABLE_LEVEL_PUD, pages);
 
 	return paddr_last;
 }
@@ -1116,7 +1116,7 @@ remove_pte_table(pte_t *pte_start, unsigned long addr, unsigned long end,
 	/* Call free_pte_table() in remove_pmd_table(). */
 	flush_tlb_all();
 	if (direct)
-		update_page_count(PGTABLE_LEVEL_PTE, -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PTE, -pages);
 }
 
 static void __meminit
@@ -1162,7 +1162,7 @@ remove_pmd_table(pmd_t *pmd_start, unsigned long addr, unsigned long end,
 
 	/* Call free_pmd_table() in remove_pud_table(). */
 	if (direct)
-		update_page_count(PGTABLE_LEVEL_PMD, -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PMD, -pages);
 }
 
 static void __meminit
@@ -1196,7 +1196,7 @@ remove_pud_table(pud_t *pud_start, unsigned long addr, unsigned long end,
 	}
 
 	if (direct)
-		update_page_count(PGTABLE_LEVEL_PUD, -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PUD, -pages);
 }
 
 static void __meminit
@@ -1228,7 +1228,7 @@ remove_p4d_table(p4d_t *p4d_start, unsigned long addr, unsigned long end,
 	}
 
 	if (direct)
-		update_page_count(PGTABLE_LEVEL_P4D, -pages);
+		direct_map_count_update(PGTABLE_LEVEL_P4D, -pages);
 }
 
 /* start and end are both virtual address. */
arch/x86/mm/mm_internal.h +7 -0
index 7c4a41235323..8e461ae43d5f 100644
@@ -24,6 +24,13 @@ void update_cache_mode_entry(unsigned entry, enum page_cache_mode cache);
 
 extern unsigned long tlb_single_page_flush_ceiling;
 
+#ifdef CONFIG_PROC_FS
+void direct_map_count_update(enum pgtable_level level, long pages);
+#else
+static inline void direct_map_count_update(enum pgtable_level level,
+					   long pages) { }
+#endif
+
 #ifdef CONFIG_NUMA
 void __init x86_numa_init(void);
 #endif
arch/x86/mm/pat/set_memory.c +50 -42

152 lines not on this page · raw message

Signature · 1 line
2.53.0
#28 lore raw

RFC PATCH v2 28/54 x86/mm/pat: separate the generic part of CPA from the x86 hooks

In reply to Mike Rapoport (Microsoft)

The core CPA logic is going to move to mm/pageattr.c.

Draw the line between the generic and the x86 code in place first, so that the move will be purely mechanical.

The page table walk and cpa_lookup(), the decision whether to keep or split a large page, the handling of holes, the set_memory_*() and set_direct_map_*_noflush() entry points and the direct map counters are going to become generic.

x86 provides hooks for everything that depends on the page table format, the static protections, the definition of alias mapping ranges, the TLB flush and the collapse of large pages.

Which aliases a mapping has and what they may change is up to the architecture. Walking an alias and propagating its TLB flush to the request is not, so that will move to the generic part.

Split the hooks out of the functions that mix both and put them next to the code they come from.

Rename the hooks to arch_cpa_*() and __change_page_attr_set_clr() to change_page_attr_noflush().

Split change_page_attr(), which takes a request, out of change_page_attr_set_clr() and use it for the operations of set_memory_*().

Reword the comment of the large page check, which names the static protections of x86, and drop the history of the check.

No functional change.

---
 arch/x86/mm/pat/set_memory.c | 285 ++++++++++++++++++++++++-------------------
 1 file changed, 158 insertions(+), 127 deletions(-)
arch/x86/mm/pat/set_memory.c +158 -127
index 36d63119df71..34c58c7da4e3 100644
@@ -345,7 +345,7 @@ static pgd_t *cpa_pgd(struct cpa_data *cpa, unsigned long address)
 	return cpa->pgd + pgd_index(address);
 }
 
-static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
+static unsigned long cpa_addr(struct cpa_data *cpa, unsigned long idx)
 {
 	return cpa->addr + idx * PAGE_SIZE;
 }
@@ -460,14 +460,14 @@ static void __cpa_flush_tlb(void *data)
 
 static int collapse_large_pages(unsigned long addr, struct list_head *pgtables);
 
-static void cpa_collapse_large_pages(struct cpa_data *cpa)
+static void arch_cpa_collapse(struct cpa_data *cpa)
 {
 	unsigned long start, addr, end;
 	struct ptdesc *ptdesc, *tmp;
 	LIST_HEAD(pgtables);
 	int collapsed = 0;
 
-	addr = __cpa_addr(cpa, 0);
+	addr = cpa_addr(cpa, 0);
 	start = addr & PMD_MASK;
 	end = addr + PAGE_SIZE * cpa->numpages;
 
@@ -540,6 +540,17 @@ static void cpa_flush(struct cpa_data *cpa, int cache)
 	__cpa_flush(&req, cache);
 }
 
+static void arch_cpa_flush(struct cpa_data *cpa)
+{
+	/*
+	 * No need to flush, when we did not set any of the caching
+	 * attributes:
+	 */
+	int cache = !!pgprot2cachemode(cpa->mask_set);
+
+	cpa_flush(cpa, cache);
+}
+
 static bool overlaps(unsigned long r1_start, unsigned long r1_end,
 		     unsigned long r2_start, unsigned long r2_end)
 {
@@ -910,7 +921,7 @@ static pte_t *cpa_lookup_in_pgd(pgd_t *pgdp, unsigned long address,
 	return pte_offset_kernel(pmdp, address);
 }
 
-static void cpa_decode_leaf(struct cpa_leaf *leaf)
+static void arch_cpa_decode_leaf(struct cpa_leaf *leaf)
 {
 	enum pgtable_level level = leaf->level;
 	pte_t *kpte = leaf->kpte;
@@ -954,7 +965,7 @@ static pte_t *cpa_lookup(struct cpa_data *cpa, unsigned long address,
 
 	leaf->size = pgtable_level_size(leaf->level);
 	leaf->addr = address & pgtable_level_mask(leaf->level);
-	cpa_decode_leaf(leaf);
+	arch_cpa_decode_leaf(leaf);
 
 	return leaf->kpte;
 }
@@ -1099,6 +1110,22 @@ static pte_t cpa_pte(enum pgtable_level level, unsigned long pfn, pgprot_t prot)
 	return pfn_pte(pfn, prot);
 }
 
+static void arch_cpa_modify_leaf(struct cpa_leaf *leaf, pgprot_t prot)
+{
+	enum pgtable_level level = leaf->level;
+	unsigned long lpaddr = leaf->addr;
+	unsigned long pfn = leaf->pfn;
+	pte_t *kpte = leaf->kpte;
+	pte_t pte;
+
+	pte = cpa_pte(level, pfn, prot);
+
+	if (level == PGTABLE_LEVEL_PTE)
+		set_pte_atomic(kpte, pte);
+	else
+		__set_pmd_pte(kpte, lpaddr, pte);
+}
+
 static pgprot_t cpa_req_prot(const struct cpa_data *cpa,
 			     const struct cpa_leaf *leaf)
 {
@@ -1106,7 +1133,7 @@ static pgprot_t cpa_req_prot(const struct cpa_data *cpa,
 			pgprot_val(cpa->mask_set));
 }
 
-static pgprot_t cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf)
+static pgprot_t arch_cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
 	pgprot_t prot = cpa_req_prot(cpa, leaf);
 	enum pgtable_level level = leaf->level;
@@ -1133,7 +1160,7 @@ static pgprot_t cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf)
 
 static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
-	unsigned long address = __cpa_addr(cpa, cpa->curpage);
+	unsigned long address = cpa_addr(cpa, cpa->curpage);
 	enum pgtable_level level = leaf->level;
 	unsigned long lpaddr = leaf->addr;
 	unsigned long old_pfn = leaf->pfn;
@@ -1141,8 +1168,6 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	pgprot_t old_prot = leaf->prot;
 	unsigned long numpages, pfn;
 	pgprot_t new_prot, req_prot;
-	pte_t *kpte = leaf->kpte;
-	pte_t new_pte;
 
 	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
@@ -1189,41 +1214,33 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 		return 1;
 
 	/*
-	 * Check whether the requested pgprot is conflicting with a static
-	 * protection requirement in the large page.
+	 * Check whether the architecture allows the requested protection for
+	 * the whole large page.
 	 */
-	new_prot = cpa_new_prot(cpa, leaf);
+	new_prot = arch_cpa_new_prot(cpa, leaf);
 
-	/*
-	 * If there is a conflict, split the large page.
-	 *
-	 * There used to be a 4k wise evaluation trying really hard to
-	 * preserve the large pages, but experimentation has shown, that this
-	 * does not help at all. There might be corner cases which would
-	 * preserve one large page occasionally, but it's really not worth the
-	 * extra code and cycles for the common case.
-	 */
+	/* If there is a conflict, split the large page. */
 	if (pgprot_val(req_prot) != pgprot_val(new_prot))
 		return 1;
 
 	/* All checks passed. Update the large page mapping. */
-	new_pte = cpa_pte(level, old_pfn, new_prot);
-	__set_pmd_pte(kpte, address, new_pte);
+	arch_cpa_modify_leaf(leaf, new_prot);
 	cpa->state |= CPA_ST_FLUSHTLB;
 	cpa_inc_pxd_preserved(level);
 	return 0;
 }
 
-static int
-__split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
+static int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
+			       void *table)
 {
-	unsigned long address = __cpa_addr(cpa, cpa->curpage);
-	struct page *base = virt_to_page(pbase);
+	unsigned long address = cpa_addr(cpa, cpa->curpage);
+	struct page *base = virt_to_page(table);
 	enum pgtable_level level = leaf->level;
 	unsigned long pfn = leaf->pfn;
 	pgprot_t prot = leaf->prot;
 	pte_t *kpte = leaf->kpte;
 	unsigned long pfninc;
+	pte_t *pbase = table;
 	unsigned int i;
 
 	if (level != PGTABLE_LEVEL_PMD && level != PGTABLE_LEVEL_PUD)
@@ -1238,9 +1255,6 @@ __split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
 		set_pte(pbase + i, cpa_pte(level - 1, pfn, prot));
 
-	if (cpa_is_direct_map(address))
-		direct_map_count_split(level);
-
 	/*
 	 * Install the new, split up pagetable.
 	 *
@@ -1273,7 +1287,7 @@ __split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf, pte_t *pbase)
 	return 0;
 }
 
-static void *cpa_alloc_pgtable(struct cpa_leaf *leaf)
+static void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf)
 {
 	if (leaf->level == PGTABLE_LEVEL_PMD)
 		return pte_alloc_one_kernel(&init_mm);
@@ -1281,7 +1295,7 @@ static void *cpa_alloc_pgtable(struct cpa_leaf *leaf)
 	return pmd_alloc_one(&init_mm, leaf->addr);
 }
 
-static void cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
+static void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
 {
 	if (leaf->level == PGTABLE_LEVEL_PMD)
 		pte_free_kernel(&init_mm, table);
@@ -1291,14 +1305,14 @@ static void cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
 
 static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
-	unsigned long address = __cpa_addr(cpa, cpa->curpage);
+	unsigned long address = cpa_addr(cpa, cpa->curpage);
 	pte_t *kpte = leaf->kpte;
 	struct cpa_leaf tmp;
 	void *table;
 	int ret = 0;
 
 	spin_unlock(&cpa_lock);
-	table = cpa_alloc_pgtable(leaf);
+	table = arch_cpa_alloc_pgtable(leaf);
 	spin_lock(&cpa_lock);
 	if (!table)
 		return -ENOMEM;
@@ -1311,14 +1325,17 @@ static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 		goto out;
 	*leaf = tmp;
 
-	ret = __split_large_page(cpa, leaf, table);
+	ret = arch_cpa_split_leaf(cpa, leaf, table);
 	if (ret)
 		goto out;
 
+	if (cpa_is_direct_map(address))
+		direct_map_count_split(leaf->level);
+
 	return 0;
 
 out:
-	cpa_free_pgtable(leaf, table);
+	arch_cpa_free_pgtable(leaf, table);
 	return ret;
 }
 
@@ -1872,16 +1889,9 @@ static int populate_pgd(struct cpa_data *cpa, unsigned long addr)
 	return 0;
 }
 
-static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr)
+static int cpa_process_fault(struct cpa_data *cpa)
 {
-	if (cpa->pgd) {
-		/*
-		 * Right now, we only execute this code path when mapping
-		 * the EFI virtual memory map regions, no other users
-		 * provide a ->pgd value. This may change in the future.
-		 */
-		return populate_pgd(cpa, vaddr);
-	}
+	unsigned long vaddr = cpa_addr(cpa, cpa->curpage);
 
 	/*
 	 * Ignore all non primary paths.
@@ -1896,23 +1906,41 @@ static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr)
 	 * to have holes.
 	 * Also set numpages to '1' indicating that we processed cpa req for
 	 * one virtual address page and its pfn. TBD: numpages can be set based
-	 * on the initial value and the level returned by lookup_address().
+	 * on the initial value and the level returned by cpa_lookup().
 	 */
 	if (cpa_is_direct_map(vaddr)) {
 		cpa->numpages = 1;
 		cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
 		return 0;
+	}
 
-	} else if (__cpa_pfn_in_highmap(cpa->pfn)) {
-		/* Faults in the highmap are OK, so do not warn: */
-		return -EFAULT;
-	} else {
-		WARN(1, "CPA: called for zero pte. "
-			"vaddr = %lx cpa->addr = %lx\n", vaddr,
-			cpa->addr);
+	WARN(1, "CPA: called for zero pte. "
+		"vaddr = %lx cpa->addr = %lx\n", vaddr, cpa->addr);
 
-		return -EFAULT;
+	return -EFAULT;
+}
+
+static int arch_cpa_process_fault(struct cpa_data *cpa)
+{
+	unsigned long vaddr = cpa_addr(cpa, cpa->curpage);
+
+	if (cpa->pgd) {
+		/*
+		 * Right now, we only execute this code path when mapping
+		 * the EFI virtual memory map regions, no other users
+		 * provide a ->pgd value. This may change in the future.
+		 * This happens only at boot, before the scheduler starts,
+		 * so populate_pgd() may allocate with cpa_lock held.
+		 */
+		return populate_pgd(cpa, vaddr);
 	}
+
+	/* Faults in the highmap are OK, so do not warn: */
+	if (!(cpa->state & CPA_ST_ALIAS) && !cpa_is_direct_map(vaddr) &&
+	    __cpa_pfn_in_highmap(cpa->pfn))
+		return -EFAULT;
+
+	return cpa_process_fault(cpa);
 }
 
 static int __change_page_attr(struct cpa_data *cpa)
@@ -1921,24 +1949,23 @@ static int __change_page_attr(struct cpa_data *cpa)
 	struct cpa_leaf leaf;
 	int do_split, ret;
 
-	address = __cpa_addr(cpa, cpa->curpage);
+	address = cpa_addr(cpa, cpa->curpage);
 repeat:
 	if (!cpa_lookup(cpa, address, &leaf))
-		return __cpa_process_fault(cpa, address);
+		return arch_cpa_process_fault(cpa);
 
 	if (leaf.level == PGTABLE_LEVEL_PTE) {
 		pgprot_t new_prot;
 		unsigned long pfn = leaf.pfn;
 
 		cpa_inc_pte_install();
-		new_prot = cpa_new_prot(cpa, &leaf);
+		new_prot = arch_cpa_new_prot(cpa, &leaf);
 		cpa->pfn = pfn;
 		/*
 		 * Do we really change anything ?
 		 */
 		if (pgprot_val(new_prot) != pgprot_val(leaf.prot)) {
-			set_pte_atomic(leaf.kpte,
-				       cpa_pte(leaf.level, pfn, new_prot));
+			arch_cpa_modify_leaf(&leaf, new_prot);
 			cpa->state |= CPA_ST_FLUSHTLB;
 		}
 		cpa->numpages = 1;
@@ -1952,8 +1979,8 @@ static int __change_page_attr(struct cpa_data *cpa)
 	do_split = should_split_large_page(cpa, &leaf);
 	/*
 	 * When the range fits into the existing large page,
-	 * return. cp->numpages and cpa->tlbflush have been updated in
-	 * try_large_page:
+	 * return. cpa->numpages and cpa->state have been updated in
+	 * should_split_large_page():
 	 */
 	if (do_split <= 0)
 		return do_split;
@@ -1968,12 +1995,27 @@ static int __change_page_attr(struct cpa_data *cpa)
 	return ret;
 }
 
-static int __change_page_attr_set_clr(struct cpa_data *cpa);
+static int change_page_attr_noflush(struct cpa_data *cpa);
+
+static int cpa_change_alias(struct cpa_data *cpa, struct cpa_data *alias)
+{
+	int ret;
+
+	alias->state &= ~CPA_ST_FLUSHTLB;
+	alias->state |= CPA_ST_ALIAS;
+	alias->curpage = 0;
+
+	ret = change_page_attr_noflush(alias);
+	if (alias->state & CPA_ST_FLUSHTLB)
+		cpa->state |= CPA_ST_FLUSHTLB | CPA_ST_FLUSH_ALL;
+
+	return ret;
+}
 
 /*
  * Check the directmap and "high kernel map" 'aliases'.
  */
-static int cpa_process_alias(struct cpa_data *cpa)
+static int arch_cpa_process_alias(struct cpa_data *cpa)
 {
 	struct cpa_data alias_cpa;
 	unsigned long vaddr;
@@ -1986,14 +2028,11 @@ static int cpa_process_alias(struct cpa_data *cpa)
 	 * No need to redo, when the primary call touched the direct
 	 * mapping already:
 	 */
-	vaddr = __cpa_addr(cpa, cpa->curpage);
+	vaddr = cpa_addr(cpa, cpa->curpage);
 	if (!cpa_is_direct_map(vaddr)) {
 
 		alias_cpa = *cpa;
 		alias_cpa.addr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
-		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
-		alias_cpa.state |= CPA_ST_ALIAS;
-		alias_cpa.curpage = 0;
 
 		/* Directmap always has NX set, do not modify. */
 		if (__supported_pte_mask & _PAGE_NX) {
@@ -2001,9 +2040,7 @@ static int cpa_process_alias(struct cpa_data *cpa)
 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
 		}
 
-		ret = __change_page_attr_set_clr(&alias_cpa);
-		if (alias_cpa.state & CPA_ST_FLUSHTLB)
-			cpa->state |= CPA_ST_FLUSHTLB | CPA_ST_FLUSH_ALL;
+		ret = cpa_change_alias(cpa, &alias_cpa);
 		if (ret)
 			return ret;
 	}
@@ -2019,9 +2056,6 @@ static int cpa_process_alias(struct cpa_data *cpa)
 		alias_cpa = *cpa;
 		alias_cpa.addr = (cpa->pfn << PAGE_SHIFT) +
 				 __START_KERNEL_map - phys_base;
-		alias_cpa.state &= ~CPA_ST_FLUSHTLB;
-		alias_cpa.state |= CPA_ST_ALIAS;
-		alias_cpa.curpage = 0;
 
 		/*
 		 * [_text, _brk_end) also covers data, do not modify NX except
@@ -2036,16 +2070,14 @@ static int cpa_process_alias(struct cpa_data *cpa)
 		 * The high mapping range is imprecise, so ignore the
 		 * return value.
 		 */
-		__change_page_attr_set_clr(&alias_cpa);
-		if (alias_cpa.state & CPA_ST_FLUSHTLB)
-			cpa->state |= CPA_ST_FLUSHTLB | CPA_ST_FLUSH_ALL;
+		cpa_change_alias(cpa, &alias_cpa);
 	}
 #endif
 
 	return 0;
 }
 
-static int __change_page_attr_set_clr(struct cpa_data *cpa)
+static int change_page_attr_noflush(struct cpa_data *cpa)
 {
 	unsigned long numpages = cpa->numpages;
 	unsigned long rempages = numpages;
@@ -2072,7 +2104,7 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 
 		if (!(cpa->state & CPA_ST_ALIAS) &&
 		    !(cpa->flags & CPA_REQ_NO_CHECK_ALIAS)) {
-			ret = cpa_process_alias(cpa);
+			ret = arch_cpa_process_alias(cpa);
 			if (ret)
 				goto out;
 		}
@@ -2096,28 +2128,13 @@ static int __change_page_attr_set_clr(struct cpa_data *cpa)
 	return ret;
 }
 
-static int change_page_attr_set_clr(unsigned long addr, int numpages,
-				    pgprot_t mask_set, pgprot_t mask_clr,
-				    int in_flag)
+static int change_page_attr(struct cpa_data *cpa)
 {
-	struct cpa_data cpa;
-	int ret, cache;
-
-	memset(&cpa, 0, sizeof(cpa));
-
-	/*
-	 * Check, if we are requested to set a not supported
-	 * feature.  Clearing non-supported features is OK.
-	 */
-	mask_set = canon_pgprot(mask_set);
-
-	if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) &&
-	    !(in_flag & CPA_REQ_SPLIT))
-		return 0;
+	int ret;
 
 	/* Ensure we are PAGE_SIZE aligned */
-	if (addr & ~PAGE_MASK) {
-		addr &= PAGE_MASK;
+	if (cpa->addr & ~PAGE_MASK) {
+		cpa->addr &= PAGE_MASK;
 		/*
 		 * People should not be passing in unaligned addresses:
 		 */
@@ -2129,40 +2146,27 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 
 	vm_unmap_aliases();
 
-	cpa.addr = addr;
-	cpa.numpages = numpages;
-	cpa.mask_set = mask_set;
-	cpa.mask_clr = mask_clr;
-	cpa.flags = in_flag;
-	cpa.curpage = 0;
-
-	ret = __change_page_attr_set_clr(&cpa);
+	ret = change_page_attr_noflush(cpa);
 
 	/*
 	 * Check whether we really changed something:
 	 */
-	if (!(cpa.state & CPA_ST_FLUSHTLB))
-		goto out;
-
-	/*
-	 * No need to flush, when we did not set any of the caching
-	 * attributes:
-	 */
-	cache = !!pgprot2cachemode(mask_set);
+	if (!(cpa->state & CPA_ST_FLUSHTLB))
+		return ret;
 
 	/*
 	 * On error; flush everything to be sure.
 	 */
 	if (ret)
-		cpa.state |= CPA_ST_FLUSH_ALL;
+		cpa->state |= CPA_ST_FLUSH_ALL;
 
-	cpa_flush(&cpa, cache);
+	arch_cpa_flush(cpa);
 
 	if (ret)
-		goto out;
+		return ret;
 
-	if (!(cpa.flags & CPA_REQ_COLLAPSE))
-		goto out;
+	if (!(cpa->flags & CPA_REQ_COLLAPSE))
+		return 0;
 
 	/*
 	 * Take the mmap write lock on init_mm to avoid a use-after-free if
@@ -2172,12 +2176,36 @@ static int change_page_attr_set_clr(unsigned long addr, int numpages,
 	 */
 	scoped_guard(mmap_write_lock, &init_mm) {
 		guard(spinlock)(&cpa_lock);
-		cpa_collapse_large_pages(&cpa);
+		arch_cpa_collapse(cpa);
 	}
-out:
+
 	return ret;
 }
 
+static int change_page_attr_set_clr(unsigned long addr, int numpages,
+				    pgprot_t mask_set, pgprot_t mask_clr,
+				    int in_flag)
+{
+	struct cpa_data cpa = {
+		.addr = addr,
+		.numpages = numpages,
+		.mask_clr = mask_clr,
+		.flags = in_flag,
+	};
+
+	/*
+	 * Check, if we are requested to set a not supported
+	 * feature.  Clearing non-supported features is OK.
+	 */
+	cpa.mask_set = canon_pgprot(mask_set);
+
+	if (!pgprot_val(cpa.mask_set) && !pgprot_val(mask_clr) &&
+	    !(in_flag & CPA_REQ_SPLIT))
+		return 0;
+
+	return change_page_attr(&cpa);
+}
+
 static inline int change_page_attr_set(unsigned long addr, int numpages,
 				       pgprot_t mask)
 {
@@ -2235,7 +2263,7 @@ static int change_page_attr_pages(struct page **pages, int numpages,
 		cpa.numpages = n;
 		cpa.curpage = 0;
 		cpa.state = 0;
-		ret = __change_page_attr_set_clr(&cpa);
+		ret = change_page_attr_noflush(&cpa);
 		req.state |= cpa.state;
 		if (ret)
 			break;
@@ -2465,8 +2493,11 @@ static int set_memory_op(unsigned long addr, int numpages, enum cpa_op op)
 	if (ret)
 		return ret;
 
-	return change_page_attr_set_clr(addr, numpages, cpa.mask_set,
-					cpa.mask_clr, cpa.flags);
+	if (!pgprot_val(cpa.mask_set) && !pgprot_val(cpa.mask_clr) &&
+	    !(cpa.flags & CPA_REQ_SPLIT))
+		return 0;
+
+	return change_page_attr(&cpa);
 }
 
 int set_memory_x(unsigned long addr, int numpages)
@@ -2561,7 +2592,7 @@ static int __set_memory_enc_pgtable(unsigned long addr, int numpages, bool enc)
 	if (ret)
 		goto vmm_fail;
 
-	ret = __change_page_attr_set_clr(&cpa);
+	ret = change_page_attr_noflush(&cpa);
 
 	/*
 	 * After changing the encryption attribute, we need to flush TLBs again
@@ -2773,7 +2804,7 @@ static int set_direct_map(struct page *page, unsigned int nr, enum cpa_op op)
 	 * set_direct_map_*_noflush() change only the direct map, not its
 	 * aliases.
 	 */
-	return __change_page_attr_set_clr(&cpa);
+	return change_page_attr_noflush(&cpa);
 }
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr)
@@ -2883,7 +2914,7 @@ int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
 
 	cpa.mask_set = __pgprot(_PAGE_PRESENT | page_flags);
 
-	retval = __change_page_attr_set_clr(&cpa);
+	retval = change_page_attr_noflush(&cpa);
 	__flush_tlb_all();
 
 out:
@@ -2918,7 +2949,7 @@ int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
 
 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
 
-	retval = __change_page_attr_set_clr(&cpa);
+	retval = change_page_attr_noflush(&cpa);
 	__flush_tlb_all();
 
 	return retval;
Signature · 1 line
2.53.0
#29 lore raw

RFC PATCH v2 29/54 x86/mm/pat, mm: pull CPA core to mm/

In reply to Mike Rapoport (Microsoft)

Currently there are seven independent implementations for set_memory_*() and set_direct_map_*().

With increasing demand for kernel page table manipulations, for example "Direct Map Removal Support for guest_memfd" [1] and "mm: ASI direct map management" [2], it makes sense to have a generic core in mm/ that implements the common parts, like page table walks, decisions when to keep or split large mappings and statistics, with helpers in the architecture specific code.

The common core will replace seven different policies of what and when set_memory_*() and set_direct_map_*() would do with the page tables with a single one that sets common expectations for the callers.

x86's implementation is the most versatile and most battle-tested, and as such it is the best base for the generic implementation.

It has all the pieces: it preserves large mappings when it can, it splits when it must, it handles the direct map alias, it serializes against itself and it sanity checks the result.

Every architecture that reports DirectMap lines in /proc/meminfo has its own copy of the counters and of the code that prints them. They all count the same thing: how the direct map is mapped at every page table level.

Pull the core logic of x86 CPA to mm/pageattr.c, together with the direct map counters and their vmstat events.

Add GENERIC_PAGEATTR Kconfig option to let architectures opt in to the generic implementation and enable it on x86.

Declare architecture hooks for page table format, restrictions on allowed and supported protections, alias mapping definitions and TLB management in include/linux/pageattr.h. The hooks that not every architecture needs have defaults.

Apart from the table of operations, the x86 set_memory_*() and set_direct_map_*_noflush() only build a request and pass it to the core. Move them to mm/pageattr.c as well. An architecture that uses the core provides its operations with arch_cpa_prepare().

On x86 only the statistics change: X86_CPA_STATISTICS becomes CPA_STATISTICS and the debugfs file moves from x86/cpa_stats to cpa_stats.

The vmstat events of the direct map counters will show up on every architecture that uses the core.

[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]/

---
 arch/x86/Kconfig                  |   9 +-
 arch/x86/include/asm/pageattr.h   |  28 ++
 arch/x86/include/asm/set_memory.h |   5 -
 arch/x86/mm/init_32.c             |   1 +
 arch/x86/mm/init_64.c             |   1 +
 arch/x86/mm/mm_internal.h         |   7 -
 arch/x86/mm/pat/set_memory.c      | 720 +-------------------------------------
 include/asm-generic/set_memory.h  |  11 +
 include/linux/pageattr.h          | 161 +++++++++
 include/linux/vm_event_item.h     |   2 +-
 mm/Kconfig                        |   3 +
 mm/Kconfig.debug                  |   8 +
 mm/Makefile                       |   1 +
 mm/pageattr.c                     | 625 +++++++++++++++++++++++++++++++++
 mm/vmstat.c                       |   2 +-
 15 files changed, 853 insertions(+), 731 deletions(-)
arch/x86/Kconfig +1 -8
index 58dce0b66179..f4aceaceaf65 100644
@@ -178,6 +178,7 @@ config X86
 	select GENERIC_IRQ_PROBE
 	select GENERIC_IRQ_RESERVATION_MODE
 	select GENERIC_IRQ_SHOW
+	select GENERIC_PAGEATTR
 	select GENERIC_PENDING_IRQ		if SMP
 	select GENERIC_SMP_IDLE_THREAD
 	select GENERIC_GETTIMEOFDAY
@@ -1473,14 +1474,6 @@ config X86_DIRECT_GBPAGES
 	  supports them), so don't confuse the user by printing
 	  that we have them enabled.
 
-config X86_CPA_STATISTICS
-	bool "Enable statistic for Change Page Attribute"
-	depends on DEBUG_FS
-	help
-	  Expose statistics about the Change Page Attribute mechanism, which
-	  helps to determine the effectiveness of preserving large and huge
-	  page mappings when mapping protections are changed.
-
 config X86_MEM_ENCRYPT
 	select ARCH_HAS_FORCE_DMA_UNENCRYPTED
 	select DYNAMIC_PHYSICAL_MASK
arch/x86/include/asm/pageattr.h new file +28 -0
new file mode 100644
index 000000000000..dea7141c3713
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_X86_PAGEATTR_H
+#define _ASM_X86_PAGEATTR_H
+
+static inline bool cpa_is_direct_map(unsigned long addr)
+{
+	return addr >= PAGE_OFFSET &&
+	       addr < PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT);
+}
+#define cpa_is_direct_map cpa_is_direct_map
+
+pgprot_t arch_cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf);
+#define arch_cpa_new_prot arch_cpa_new_prot
+
+int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
+			void *table);
+#define arch_cpa_split_leaf arch_cpa_split_leaf
+
+int arch_cpa_process_fault(struct cpa_data *cpa);
+#define arch_cpa_process_fault arch_cpa_process_fault
+
+int arch_cpa_process_alias(struct cpa_data *cpa);
+#define arch_cpa_process_alias arch_cpa_process_alias
+
+void arch_cpa_collapse(struct cpa_data *cpa);
+#define arch_cpa_collapse arch_cpa_collapse
+
+#endif /* _ASM_X86_PAGEATTR_H */
arch/x86/include/asm/set_memory.h +0 -5
index 39271a5ea925..7c1981305796 100644
@@ -6,9 +6,6 @@
 #include <asm-generic/set_memory.h>
 #include <asm/pgtable.h>
 
-#define set_memory_rox set_memory_rox
-int set_memory_rox(unsigned long addr, int numpages);
-
 /*
  * The set_memory_* API can be used to change various attributes of a virtual
  * address range. The attributes include:
@@ -86,8 +83,6 @@ int set_pages_wb(struct page *page, int numpages);
 int set_pages_ro(struct page *page, int numpages);
 int set_pages_rw(struct page *page, int numpages);
 
-int set_direct_map_invalid_noflush(struct page *page, unsigned int nr);
-int set_direct_map_default_noflush(struct page *page, unsigned int nr);
 bool kernel_page_present(struct page *page);
 
 extern int kernel_set_to_readonly;
arch/x86/mm/init_32.c +1 -0
index d9e835aaf912..39c84a07449e 100644
@@ -30,6 +30,7 @@
 #include <linux/initrd.h>
 #include <linux/cpumask.h>
 #include <linux/gfp.h>
+#include <linux/pageattr.h>
 
 #include <asm/asm.h>
 #include <asm/bios_ebda.h>
arch/x86/mm/init_64.c +1 -0
index e2592ed2d905..56acc97a7bf6 100644
@@ -33,6 +33,7 @@
 #include <linux/nmi.h>
 #include <linux/gfp.h>
 #include <linux/kcore.h>
+#include <linux/pageattr.h>
 
 #include <asm/processor.h>
 #include <asm/bios_ebda.h>
arch/x86/mm/mm_internal.h +0 -7
index 8e461ae43d5f..7c4a41235323 100644
@@ -24,13 +24,6 @@ void update_cache_mode_entry(unsigned entry, enum page_cache_mode cache);
 
 extern unsigned long tlb_single_page_flush_ceiling;
 
-#ifdef CONFIG_PROC_FS
-void direct_map_count_update(enum pgtable_level level, long pages);
-#else
-static inline void direct_map_count_update(enum pgtable_level level,
-					   long pages) { }
-#endif
-
 #ifdef CONFIG_NUMA
 void __init x86_numa_init(void);
 #endif
arch/x86/mm/pat/set_memory.c +11 -709

866 lines not on this page · raw message

include/asm-generic/set_memory.h +11 -0
index c86abf6bc7ba..7ac5c3d3d92d 100644
@@ -10,4 +10,15 @@ int set_memory_rw(unsigned long addr, int numpages);
 int set_memory_x(unsigned long addr, int numpages);
 int set_memory_nx(unsigned long addr, int numpages);
 
+#ifdef CONFIG_GENERIC_PAGEATTR
+int set_memory_rox(unsigned long addr, int numpages);
+#define set_memory_rox set_memory_rox
+
+#ifdef CONFIG_ARCH_HAS_SET_DIRECT_MAP
+struct page;
+int set_direct_map_invalid_noflush(struct page *page, unsigned int nr);
+int set_direct_map_default_noflush(struct page *page, unsigned int nr);
+#endif
+#endif
+
 #endif
include/linux/pageattr.h new file +161 -0

161 lines not on this page · raw message

include/linux/vm_event_item.h +1 -1
index 2628ccda076a..4d2ab343abf9 100644
@@ -139,7 +139,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
 		ZSWPOUT,
 		ZSWPWB,
 #endif
-#ifdef CONFIG_X86
+#ifdef CONFIG_GENERIC_PAGEATTR
 		DIRECT_MAP_LEVEL2_SPLIT,
 		DIRECT_MAP_LEVEL3_SPLIT,
 		DIRECT_MAP_LEVEL2_COLLAPSE,
mm/Kconfig +3 -0
index afff1b25b543..3948e64dc590 100644
@@ -1138,6 +1138,9 @@ config MEM_SOFT_DIRTY
 config GENERIC_EARLY_IOREMAP
 	bool
 
+config GENERIC_PAGEATTR
+	bool
+
 config STACK_MAX_DEFAULT_SIZE_MB
 	int "Default maximum user stack size for 32-bit processes (MB)"
 	default 100
mm/Kconfig.debug +8 -0
index 9ae75229c76d..556a2e47cd9e 100644
@@ -180,6 +180,14 @@ config DEBUG_RODATA_TEST
 	help
 	  This option enables a testcase for the setting rodata read-only.
 
+config CPA_STATISTICS
+	bool "Enable statistic for Change Page Attribute"
+	depends on GENERIC_PAGEATTR && DEBUG_FS
+	help
+	  Expose statistics about the Change Page Attribute mechanism, which
+	  helps to determine the effectiveness of preserving large and huge
+	  page mappings when mapping protections are changed.
+
 config PTDUMP_DEBUGFS
 	bool "Export kernel pagetable layout to userspace via debugfs"
 	depends on DEBUG_KERNEL
mm/Makefile +1 -0
index 2a3ec53d62ee..0de865d02c70 100644
@@ -142,6 +142,7 @@ obj-$(CONFIG_HMM_MIRROR) += hmm.o
 obj-$(CONFIG_MEMFD_CREATE) += memfd.o
 obj-$(CONFIG_MAPPING_DIRTY_HELPERS) += mapping_dirty_helpers.o
 obj-$(CONFIG_PTDUMP) += ptdump.o
+obj-$(CONFIG_GENERIC_PAGEATTR) += pageattr.o
 obj-$(CONFIG_PAGE_REPORTING) += page_reporting.o
 obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
 obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
mm/pageattr.c new file +625 -0

625 lines not on this page · raw message

mm/vmstat.c +1 -1
index c6beac6be2bc..330d443597e4 100644
@@ -1467,7 +1467,7 @@ const char * const vmstat_text[] = {
 	[I(ZSWPOUT)]				= "zswpout",
 	[I(ZSWPWB)]				= "zswpwb",
 #endif
-#ifdef CONFIG_X86
+#ifdef CONFIG_GENERIC_PAGEATTR
 	[I(DIRECT_MAP_LEVEL2_SPLIT)]		= "direct_map_level2_splits",
 	[I(DIRECT_MAP_LEVEL3_SPLIT)]		= "direct_map_level3_splits",
 	[I(DIRECT_MAP_LEVEL2_COLLAPSE)]		= "direct_map_level2_collapses",
Signature · 1 line
2.53.0
#30 lore raw

RFC PATCH v2 30/54 mm/pageattr: introduce arch_cpa_can_split()

In reply to Mike Rapoport (Microsoft)

Currently CPA core presumes that the split of a large mapping is always possible. After deciding to split a large mapping, core drops the locks, allocates a new page table and calls arch_cpa_split_leaf().

If an architecture does not support splitting large mappings, the only way for it to inform the core is to fail arch_cpa_split_leaf().

arch_cpa_split_leaf() only updates the page tables, and normally shouldn't fail. A failure there means something went terribly wrong, so having it check if splits are supported at all would mix capability and corner case checks.

Besides, if an architecture does not support splitting, the locks and allocation dance would be there for nothing.

Add arch_cpa_can_split() and fail a request that needs a split the architecture cannot do before the allocation, with a warning.

By default an architecture cannot split large mappings.

An architecture that can split must override both arch_cpa_can_split() and arch_cpa_split_leaf().

Since x86 can split all large mappings, hardwire its override of arch_cpa_can_split() to true.

---
 arch/x86/include/asm/pageattr.h | 7 ++++++-
 include/linux/pageattr.h        | 8 +++++++-
 mm/pageattr.c                   | 3 +++
 3 files changed, 16 insertions(+), 2 deletions(-)
arch/x86/include/asm/pageattr.h +6 -1
index dea7141c3713..8a3e2a35211d 100644
@@ -14,7 +14,12 @@ pgprot_t arch_cpa_new_prot(struct cpa_data *cpa, struct cpa_leaf *leaf);
 
 int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
 			void *table);
-#define arch_cpa_split_leaf arch_cpa_split_leaf
+static inline bool arch_cpa_can_split(struct cpa_data *cpa,
+				      struct cpa_leaf *leaf)
+{
+	return true;
+}
+#define arch_cpa_can_split arch_cpa_can_split
 
 int arch_cpa_process_fault(struct cpa_data *cpa);
 #define arch_cpa_process_fault arch_cpa_process_fault
include/linux/pageattr.h +7 -1
index f8b6b17e0b0b..25f04e61ee85 100644
@@ -96,7 +96,13 @@ static inline pgprot_t arch_cpa_new_prot(struct cpa_data *cpa,
 }
 #endif
 
-#ifndef arch_cpa_split_leaf
+#ifndef arch_cpa_can_split
+static inline bool arch_cpa_can_split(struct cpa_data *cpa,
+				      struct cpa_leaf *leaf)
+{
+	return false;
+}
+
 static inline int arch_cpa_split_leaf(struct cpa_data *cpa,
 				      struct cpa_leaf *leaf, void *table)
 {
mm/pageattr.c +3 -0
index 6fb89632b679..dcece32ebad2 100644
@@ -421,6 +421,9 @@ static int __change_page_attr(struct cpa_data *cpa)
 	/*
 	 * We have to split the large page:
 	 */
+	if (WARN_ON_ONCE(!arch_cpa_can_split(cpa, &leaf)))
+		return -EINVAL;
+
 	ret = split_large_page(cpa, &leaf);
 	if (!ret)
 		goto repeat;
Signature · 1 line
2.53.0
#31 lore raw

RFC PATCH v2 31/54 mm/pageattr: introduce cpa_flush_tlb_kernel_range()

In reply to Mike Rapoport (Microsoft)

Many architectures that implement set_memory_*() APIs flush the TLB after a page table update with flush_tlb_kernel_range() for the range of the request.

Add cpa_flush_tlb_kernel_range() helper for their arch_cpa_flush() hooks.

When to flush and whether to flush more than the request stays up to the architecture.

LoongArch, ARM, powerpc, riscv and arm64 will use it when they switch to the CPA core.

---
 include/linux/pageattr.h | 1 +
 mm/pageattr.c            | 8 ++++++++
 2 files changed, 9 insertions(+)
include/linux/pageattr.h +1 -0
index 25f04e61ee85..091408ad328f 100644
@@ -65,6 +65,7 @@ static inline unsigned long cpa_addr(struct cpa_data *cpa, unsigned long idx)
 
 int cpa_process_fault(struct cpa_data *cpa);
 int cpa_change_alias(struct cpa_data *cpa, struct cpa_data *alias);
+void cpa_flush_tlb_kernel_range(struct cpa_data *cpa);
 
 int change_page_attr(struct cpa_data *cpa);
 
mm/pageattr.c +8 -0
index dcece32ebad2..852e0989dac9 100644
@@ -14,6 +14,8 @@
 #include <linux/vmalloc.h>
 #include <linux/set_memory.h>
 
+#include <asm/tlbflush.h>
+
 /*
  * Serialize CPA using cpa_lock so that:
  * - concurrent requests don't split or change the same large mapping at the
@@ -482,6 +484,12 @@ int change_page_attr_noflush(struct cpa_data *cpa)
 	return ret;
 }
 
+void cpa_flush_tlb_kernel_range(struct cpa_data *cpa)
+{
+	flush_tlb_kernel_range(cpa->addr,
+			       cpa->addr + cpa->numpages * PAGE_SIZE);
+}
+
 int cpa_change_alias(struct cpa_data *cpa, struct cpa_data *alias)
 {
 	int ret;
Signature · 1 line
2.53.0
#32 lore raw

RFC PATCH v2 32/54 asm-generic: add an empty pageattr.h

In reply to Mike Rapoport (Microsoft)

linux/pageattr.h includes asm/pageattr.h for the overrides of the CPA hooks. An architecture that is fine with all the defaults has nothing to put there.

Add an empty asm-generic/pageattr.h and make it mandatory, so that such an architecture does not need an empty header of its own.

LoongArch, ARM and powerpc will pick up the asm-generic/pageattr.h when they switch to the CPA core.

---
 include/asm-generic/Kbuild     | 1 +
 include/asm-generic/pageattr.h | 5 +++++
 2 files changed, 6 insertions(+)
include/asm-generic/Kbuild +1 -0
index b7a388bef6ea..fd9fb2c3260b 100644
@@ -42,6 +42,7 @@ mandatory-y += mmu_context.h
 mandatory-y += module.h
 mandatory-y += module.lds.h
 mandatory-y += msi.h
+mandatory-y += pageattr.h
 mandatory-y += pci.h
 mandatory-y += percpu.h
 mandatory-y += percpu_types.h
include/asm-generic/pageattr.h new file +5 -0
new file mode 100644
index 000000000000..07bf3b0e84a0
@@ -0,0 +1,5 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __ASM_GENERIC_PAGEATTR_H
+#define __ASM_GENERIC_PAGEATTR_H
+
+#endif /* __ASM_GENERIC_PAGEATTR_H */
Signature · 1 line
2.53.0
#33 lore raw

RFC PATCH v2 33/54 LoongArch: use pfn_is_nosave() to exclude firmware ranges from hibernation

In reply to Mike Rapoport (Microsoft)

Commit 619b52777a49 ("LoongArch: Fix kernel_page_present() for KPRANGE/XKPRANGE") made kernel_page_present() filter out firmware pages, such as EFI runtime services code and data, to prevent hibernation from saving and restoring them.

kernel_page_present() reports whether a page is mapped in the kernel page tables, while excluding physical memory from the hibernation image is what pfn_is_nosave() is for.

Move the check for firmware pages to pfn_is_nosave().

---
 arch/loongarch/mm/pageattr.c     | 3 +--
 arch/loongarch/power/hibernate.c | 6 +++++-
 2 files changed, 6 insertions(+), 3 deletions(-)
arch/loongarch/mm/pageattr.c +1 -2
index a7dcff40f759..a728db40f9e0 100644
@@ -3,7 +3,6 @@
  * Copyright (C) 2024 Loongson Technology Corporation Limited
  */
 
-#include <linux/memblock.h>
 #include <linux/pagewalk.h>
 #include <linux/pgtable.h>
 #include <asm/set_memory.h>
@@ -168,7 +167,7 @@ bool kernel_page_present(struct page *page)
 	unsigned long addr = (unsigned long)page_address(page);
 
 	if (addr < vm_map_base)
-		return memblock_is_memory(__pa(addr));
+		return true;
 
 	pgd = pgd_offset_k(addr);
 	if (pgd_none(pgdp_get(pgd)))
arch/loongarch/power/hibernate.c +5 -1
index 3de38ffb11c3..65dbf1aed4a7 100644
@@ -4,6 +4,7 @@
 #include <asm/sections.h>
 #include <asm/time.h>
 #include <asm/tlbflush.h>
+#include <linux/memblock.h>
 #include <linux/suspend.h>
 
 static u32 saved_crmd;
@@ -44,7 +45,10 @@ int pfn_is_nosave(unsigned long pfn)
 	unsigned long nosave_begin_pfn = PFN_DOWN(__pa(&__nosave_begin));
 	unsigned long nosave_end_pfn = PFN_UP(__pa(&__nosave_end));
 
-	return	(pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
+	if (pfn >= nosave_begin_pfn && pfn < nosave_end_pfn)
+		return 1;
+
+	return !memblock_is_memory(PFN_PHYS(pfn));
 }
 
 extern int swsusp_asm_suspend(void);
Signature · 1 line
2.53.0
#34 lore raw

RFC PATCH v2 34/54 LoongArch: stop pretending LoongArch supports set_direct_map APIs

In reply to Mike Rapoport (Microsoft)

LoongArch selects ARCH_HAS_SET_DIRECT_MAP and implements set_direct_map*() APIs to allow coexistence of hibernation with KFENCE, see commit f04de6d8f252 ("LoongArch: Add ARCH_HAS_SET_DIRECT_MAP support").

However, LoongArch does not have page tables for its direct map to begin with. It maps the physical memory with a hardware window, so there is no way to change the permissions of an individual page there.

Protection of KFENCE pages is handled outside the direct map: they are mapped in the dedicated address space area and their virtual address is explicitly set with set_page_address() to keep page_address() working for those pages.

Selecting ARCH_HAS_SET_DIRECT_MAP enables secretmem on LoongArch, although without the actual ability to modify the direct map, secretmem becomes a limited memfd and does not provide the security it promises.

After the rework of the temporary mappings in the hibernation code [1], there is no need for LoongArch to pretend it supports direct map operations.

Remove the set_direct_map*() implementation and stop enabling ARCH_HAS_SET_DIRECT_MAP.

Removing support for ARCH_HAS_SET_DIRECT_MAP effectively disables secretmem, and memfd_secret() returns -ENOSYS on LoongArch.

[1] https://lore.kernel.org/all/[email protected]

---
 arch/loongarch/Kconfig                  |  1 -
 arch/loongarch/include/asm/set_memory.h |  4 ---
 arch/loongarch/mm/pageattr.c            | 60 ---------------------------------
 3 files changed, 65 deletions(-)
arch/loongarch/Kconfig +0 -1
index b5ed4881d3c0..bad699e2847f 100644
@@ -27,7 +27,6 @@ config LOONGARCH
 	select ARCH_HAS_PREEMPT_LAZY
 	select ARCH_HAS_PTE_SPECIAL if 64BIT
 	select ARCH_HAS_SET_MEMORY
-	select ARCH_HAS_SET_DIRECT_MAP
 	select ARCH_HAS_TICK_BROADCAST if GENERIC_CLOCKEVENTS_BROADCAST
 	select ARCH_HAS_UBSAN
 	select ARCH_HAS_VDSO_ARCH_DATA
arch/loongarch/include/asm/set_memory.h +0 -4
index 4bb01172fbc2..64c7f942e8ec 100644
@@ -14,8 +14,4 @@ int set_memory_nx(unsigned long addr, int numpages);
 int set_memory_ro(unsigned long addr, int numpages);
 int set_memory_rw(unsigned long addr, int numpages);
 
-bool kernel_page_present(struct page *page);
-int set_direct_map_default_noflush(struct page *page, unsigned int nr);
-int set_direct_map_invalid_noflush(struct page *page, unsigned int nr);
-
 #endif /* _ASM_LOONGARCH_SET_MEMORY_H */
arch/loongarch/mm/pageattr.c +0 -60

63 lines not on this page · raw message

Signature · 1 line
2.53.0
#35 lore raw

RFC PATCH v2 35/54 LoongArch: drop the huge page handling from set_memory()

In reply to Mike Rapoport (Microsoft)

set_memory() never finds a huge mapping on LoongArch.

The direct map and the kernel image are in the direct mapping windows, which have no page tables, and set_memory() skips them.

Everything in the vmalloc area is mapped with base pages, because LoongArch selects neither HAVE_ARCH_HUGE_VMALLOC nor HAVE_ARCH_HUGE_VMAP.

The only huge kernel mapping is the vmemmap, and nothing changes its protections.

The PGD, P4D, PUD and PMD handlers of the set_memory() page table walk are dead code. Drop them.

---
 arch/loongarch/mm/pageattr.c | 56 --------------------------------------------
 1 file changed, 56 deletions(-)
arch/loongarch/mm/pageattr.c +0 -56
index 7283059d6e1f..11cea93c7415 100644
@@ -24,58 +24,6 @@ static unsigned long set_pageattr_masks(unsigned long val, struct mm_walk *walk)
 	return new_val;
 }
 
-static int pageattr_pgd_entry(pgd_t *pgd, unsigned long addr,
-			      unsigned long next, struct mm_walk *walk)
-{
-	pgd_t val = pgdp_get(pgd);
-
-	if (pgd_leaf(val)) {
-		val = __pgd(set_pageattr_masks(pgd_val(val), walk));
-		set_pgd(pgd, val);
-	}
-
-	return 0;
-}
-
-static int pageattr_p4d_entry(p4d_t *p4d, unsigned long addr,
-			      unsigned long next, struct mm_walk *walk)
-{
-	p4d_t val = p4dp_get(p4d);
-
-	if (p4d_leaf(val)) {
-		val = __p4d(set_pageattr_masks(p4d_val(val), walk));
-		set_p4d(p4d, val);
-	}
-
-	return 0;
-}
-
-static int pageattr_pud_entry(pud_t *pud, unsigned long addr,
-			      unsigned long next, struct mm_walk *walk)
-{
-	pud_t val = pudp_get(pud);
-
-	if (pud_leaf(val)) {
-		val = __pud(set_pageattr_masks(pud_val(val), walk));
-		set_pud(pud, val);
-	}
-
-	return 0;
-}
-
-static int pageattr_pmd_entry(pmd_t *pmd, unsigned long addr,
-			      unsigned long next, struct mm_walk *walk)
-{
-	pmd_t val = pmdp_get(pmd);
-
-	if (pmd_leaf(val)) {
-		val = __pmd(set_pageattr_masks(pmd_val(val), walk));
-		set_pmd(pmd, val);
-	}
-
-	return 0;
-}
-
 static int pageattr_pte_entry(pte_t *pte, unsigned long addr,
 			      unsigned long next, struct mm_walk *walk)
 {
@@ -94,10 +42,6 @@ static int pageattr_pte_hole(unsigned long addr, unsigned long next,
 }
 
 static const struct mm_walk_ops pageattr_ops = {
-	.pgd_entry = pageattr_pgd_entry,
-	.p4d_entry = pageattr_p4d_entry,
-	.pud_entry = pageattr_pud_entry,
-	.pmd_entry = pageattr_pmd_entry,
 	.pte_entry = pageattr_pte_entry,
 	.pte_hole = pageattr_pte_hole,
 	.walk_lock = PGWALK_RDLOCK,
Signature · 1 line
2.53.0
#36 lore raw

RFC PATCH v2 36/54 LoongArch: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

The availability of the generic CPA core makes LoongArch's implementation of set_memory_*() APIs unnecessary.

The page table walk in arch/loongarch/mm/pageattr.c can be replaced with several simple hooks required by CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points. For LoongArch this means that:

* an empty entry in the range is reported with a warning and -EFAULT
* nothing is written or flushed when nothing changes
* a request that fails flushes the entire TLB
* set_memory_rox() is a single request instead of set_memory_ro() followed by set_memory_x()
* requests are serialized by the core, rather than by the init_mm write lock
* lazily unmapped vmap areas are purged before a request, so that they do not keep stale TLB entries with the old protection

---
 arch/loongarch/Kconfig                  |   1 +
 arch/loongarch/include/asm/set_memory.h |   8 +--
 arch/loongarch/mm/pageattr.c            | 102 ++++++++------------------------
 3 files changed, 28 insertions(+), 83 deletions(-)
arch/loongarch/Kconfig +1 -0
index bad699e2847f..455a72b8669d 100644
@@ -107,6 +107,7 @@ config LOONGARCH
 	select GENERIC_LIB_LSHRDI3
 	select GENERIC_LIB_UCMPDI2
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
+	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/loongarch/include/asm/set_memory.h +1 -7
index 64c7f942e8ec..5496a3ee27da 100644
@@ -6,12 +6,6 @@
 #ifndef _ASM_LOONGARCH_SET_MEMORY_H
 #define _ASM_LOONGARCH_SET_MEMORY_H
 
-/*
- * Functions to change memory attributes.
- */
-int set_memory_x(unsigned long addr, int numpages);
-int set_memory_nx(unsigned long addr, int numpages);
-int set_memory_ro(unsigned long addr, int numpages);
-int set_memory_rw(unsigned long addr, int numpages);
+#include <asm-generic/set_memory.h>
 
 #endif /* _ASM_LOONGARCH_SET_MEMORY_H */
arch/loongarch/mm/pageattr.c +26 -76

126 lines not on this page · raw message

Signature · 1 line
2.53.0
#37 lore raw

RFC PATCH v2 37/54 ARM: mm: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

The availability of the generic CPA core makes ARM's implementation of set_memory_*() APIs unnecessary and it can be replaced with several hooks required by CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points. For ARM this means that:

* a hole in the range fails the request with a warning instead of getting a page table
* nothing is written or flushed when nothing changes
* a request on a section, which ioremap() may create in the vmalloc area on !SMP, still fails with a warning and -EINVAL
* a request on a static I/O mapping, which may use sections in the vmalloc area, fails with a warning and -EINVAL as well
* a request that fails flushes the entire TLB
* set_memory_rox() is a single request instead of set_memory_ro() followed by set_memory_x()
* lazily unmapped vmap areas and unused kmaps are purged before a request, so that they do not keep stale mappings or TLB entries with the old protection

ARM only changes ranges mapped with base pages: modules and vmalloc, as checked before, and the KFENCE pool, which arch_kfence_init_pool() splits.

KFENCE keeps set_memory_valid(), which runs with interrupts disabled. It now walks with apply_to_existing_page_range(), which never allocates, rather than apply_to_page_range(), which allocates a page table for a hole with GFP_KERNEL.

---
 arch/arm/Kconfig                  |  1 +
 arch/arm/include/asm/set_memory.h |  6 +--
 arch/arm/mm/pageattr.c            | 96 +++++++++++++++++++++++++--------------
 3 files changed, 65 insertions(+), 38 deletions(-)
arch/arm/Kconfig +1 -0
index 0cc289a7184a..7a7ccc113126 100644
@@ -77,6 +77,7 @@ config ARM
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
+	select GENERIC_PAGEATTR if MMU
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/arm/include/asm/set_memory.h +2 -4
index 0211b9c5b14d..4f1988dad160 100644
@@ -7,10 +7,8 @@
 #define _ASMARM_SET_MEMORY_H
 
 #ifdef CONFIG_MMU
-int set_memory_ro(unsigned long addr, int numpages);
-int set_memory_rw(unsigned long addr, int numpages);
-int set_memory_x(unsigned long addr, int numpages);
-int set_memory_nx(unsigned long addr, int numpages);
+#include <asm-generic/set_memory.h>
+
 int set_memory_valid(unsigned long addr, int numpages, int enable);
 #else
 static inline int set_memory_ro(unsigned long addr, int numpages) { return 0; }
arch/arm/mm/pageattr.c +62 -34

130 lines not on this page · raw message

Signature · 1 line
2.53.0
#38 lore raw

RFC PATCH v2 38/54 mm/pageattr: let a leaf cover a contiguous block of entries

In reply to Mike Rapoport (Microsoft)

Some architectures map a naturally aligned range with a block of adjacent entries that the TLB may cache as a single translation: the 16K, 512K and 8M pages of powerpc 8xx, Svnapot on riscv and the contiguous bit of arm64.

The entries of such a block have to change together, or the block has to be broken up first, exactly like a large page.

Let arch_cpa_decode_leaf() extend a leaf to the whole block, so that the core keeps the block when a request covers it entirely and splits it otherwise.

Breaking up a block only rewrites its entries and it does not need to allocate new page table page, so the core can call arch_cpa_split_leaf() without dropping cpa_lock.

Update the CPA statistics so that they count contiguous blocks separately from large pages and single PTEs.

The block counters stay at zero on architectures without blocks.

There are no users yet. powerpc 8xx, riscv and arm64 will use it when they switch to the core.

---
 mm/pageattr.c | 79 ++++++++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 56 insertions(+), 23 deletions(-)
mm/pageattr.c +56 -23
index 852e0989dac9..2f357a8c24d2 100644
@@ -94,39 +94,63 @@ void cpa_report_meminfo(struct seq_file *m, unsigned long levels)
 
 #ifdef CONFIG_CPA_STATISTICS
 
-static unsigned long cpa_checked[PGTABLE_LEVEL_NUM];
-static unsigned long cpa_sameprot[PGTABLE_LEVEL_NUM];
-static unsigned long cpa_preserved[PGTABLE_LEVEL_NUM];
+struct cpa_stats {
+	unsigned long	checked;
+	unsigned long	sameprot;
+	unsigned long	preserved;
+};
+
+/* Large pages and contiguous blocks, by the level of their entries */
+static struct cpa_stats cpa_pages[PGTABLE_LEVEL_NUM];
+static struct cpa_stats cpa_blocks[PGTABLE_LEVEL_NUM];
 
-static inline void cpa_inc_pxd_checked(enum pgtable_level level)
+static struct cpa_stats *cpa_leaf_stats(const struct cpa_leaf *leaf)
 {
-	cpa_checked[level]++;
+	if (leaf->size != pgtable_level_size(leaf->level))
+		return &cpa_blocks[leaf->level];
+
+	return &cpa_pages[leaf->level];
+}
+
+static inline void cpa_inc_checked(const struct cpa_leaf *leaf)
+{
+	cpa_leaf_stats(leaf)->checked++;
 }
 
 static inline void cpa_inc_pte_install(void)
 {
-	cpa_checked[PGTABLE_LEVEL_PTE]++;
+	cpa_pages[PGTABLE_LEVEL_PTE].checked++;
 }
 
-static inline void cpa_inc_pxd_sameprot(enum pgtable_level level)
+static inline void cpa_inc_sameprot(const struct cpa_leaf *leaf)
 {
-	cpa_sameprot[level]++;
+	cpa_leaf_stats(leaf)->sameprot++;
 }
 
-static inline void cpa_inc_pxd_preserved(enum pgtable_level level)
+static inline void cpa_inc_preserved(const struct cpa_leaf *leaf)
 {
-	cpa_preserved[level]++;
+	cpa_leaf_stats(leaf)->preserved++;
 }
 
 static void cpastats_show_level(struct seq_file *m, enum pgtable_level level)
 {
+	struct cpa_stats *s = &cpa_pages[level];
 	char sz[20];
 
 	cpa_size_str(level, sz, sizeof(sz));
-	seq_printf(m, "%s pages checked:     %16lu\n", sz, cpa_checked[level]);
-	seq_printf(m, "%s pages sameprot:    %16lu\n", sz, cpa_sameprot[level]);
-	seq_printf(m, "%s pages preserved:   %16lu\n", sz,
-		   cpa_preserved[level]);
+	seq_printf(m, "%s pages checked:     %16lu\n", sz, s->checked);
+	seq_printf(m, "%s pages sameprot:    %16lu\n", sz, s->sameprot);
+	seq_printf(m, "%s pages preserved:   %16lu\n", sz, s->preserved);
+}
+
+static void cpastats_show_blocks(struct seq_file *m, enum pgtable_level level)
+{
+	const char *name = pgtable_level_to_str(level);
+	struct cpa_stats *s = &cpa_blocks[level];
+
+	seq_printf(m, "%s blocks checked:   %16lu\n", name, s->checked);
+	seq_printf(m, "%s blocks sameprot:  %16lu\n", name, s->sameprot);
+	seq_printf(m, "%s blocks preserved: %16lu\n", name, s->preserved);
 }
 
 static int cpastats_show(struct seq_file *m, void *p)
@@ -137,7 +161,9 @@ static int cpastats_show(struct seq_file *m, void *p)
 	cpastats_show_level(m, PGTABLE_LEVEL_PMD);
 	seq_printf(m, "%s pages set-checked: %16lu\n",
 		   cpa_size_str(PGTABLE_LEVEL_PTE, sz, sizeof(sz)),
-		   cpa_checked[PGTABLE_LEVEL_PTE]);
+		   cpa_pages[PGTABLE_LEVEL_PTE].checked);
+	cpastats_show_blocks(m, PGTABLE_LEVEL_PMD);
+	cpastats_show_blocks(m, PGTABLE_LEVEL_PTE);
 	return 0;
 }
 
@@ -160,10 +186,10 @@ static int __init cpa_stats_init(void)
 }
 late_initcall(cpa_stats_init);
 #else
-static inline void cpa_inc_pxd_checked(enum pgtable_level level) { }
+static inline void cpa_inc_checked(const struct cpa_leaf *leaf) { }
 static inline void cpa_inc_pte_install(void) { }
-static inline void cpa_inc_pxd_sameprot(enum pgtable_level level) { }
-static inline void cpa_inc_pxd_preserved(enum pgtable_level level) { }
+static inline void cpa_inc_sameprot(const struct cpa_leaf *leaf) { }
+static inline void cpa_inc_preserved(const struct cpa_leaf *leaf) { }
 #endif
 
 static pte_t *cpa_lookup_in_pgd(pgd_t *pgdp, unsigned long address,
@@ -253,10 +279,10 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	if (cpa->flags & CPA_REQ_SPLIT)
 		return 1;
 
-	if (level != PGTABLE_LEVEL_PMD && level != PGTABLE_LEVEL_PUD)
+	if (level > PGTABLE_LEVEL_PUD)
 		return -EINVAL;
 
-	cpa_inc_pxd_checked(level);
+	cpa_inc_checked(leaf);
 
 	/*
 	 * Calculate the number of pages, which fit into this large
@@ -284,7 +310,7 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	 * range.
 	 */
 	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
-		cpa_inc_pxd_sameprot(level);
+		cpa_inc_sameprot(leaf);
 		return 0;
 	}
 
@@ -307,7 +333,7 @@ static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	/* All checks passed. Update the large page mapping. */
 	arch_cpa_modify_leaf(leaf, new_prot);
 	cpa->state |= CPA_ST_FLUSHTLB;
-	cpa_inc_pxd_preserved(level);
+	cpa_inc_preserved(leaf);
 	return 0;
 }
 
@@ -319,6 +345,13 @@ static int split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 	void *table;
 	int ret = 0;
 
+	/*
+	 * A block of entries is broken up in place, without a page table and
+	 * without dropping cpa_lock.
+	 */
+	if (leaf->size != pgtable_level_size(leaf->level))
+		return arch_cpa_split_leaf(cpa, leaf, NULL);
+
 	spin_unlock(&cpa_lock);
 	table = arch_cpa_alloc_pgtable(leaf);
 	spin_lock(&cpa_lock);
@@ -389,7 +422,7 @@ static int __change_page_attr(struct cpa_data *cpa)
 	if (!cpa_lookup(cpa, address, &leaf))
 		return arch_cpa_process_fault(cpa);
 
-	if (leaf.level == PGTABLE_LEVEL_PTE) {
+	if (leaf.size == PAGE_SIZE) {
 		pgprot_t new_prot;
 		unsigned long pfn = leaf.pfn;
 
Signature · 1 line
2.53.0
#39 lore raw

RFC PATCH v2 39/54 powerpc: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

powerpc changes kernel page protections with apply_to_existing_page_range() and a callback that updates one PTE and flushes it.

A request flushes the TLB once for every page, and large mappings cannot be changed at all, so huge vmalloc ranges are refused up front.

On hash, only the start of a request is checked to be in the vmalloc or the I/O region.

The availability of the generic CPA core makes powerpc's implementation of set_memory_*() APIs unnecessary and it can be replaced with several hooks required by the CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points. For powerpc this means that:

* the TLB is flushed once per request, after a ptesync on radix
* a large mapping is changed in place when a request covers it entirely; a request for a part of it fails with a warning and -EINVAL, because powerpc cannot split
* huge vmalloc ranges are no longer refused up front; on 8xx a 16K, 512K or 8M page changes as one
* on hash, the whole request has to be in the vmalloc or the I/O region
* an empty PTE in a vmalloc range is reported with a warning and -EFAULT where the old walk skipped it
* requests are serialized by the core; the old walk ran without a lock
* lazily unmapped vmap areas and unused kmaps are purged before a request, so that they do not keep stale mappings or TLB entries with the old protection; set_memory_*() may now sleep there

The hooks decode an entry with pte_pfn() and pte_pgprot(), which work for the leaves of every level on book3s64, and write it with pte_update(), which keeps the bits the hardware updates and removes the hash page table entry where there is one.

On 8xx the decode hook extends a leaf to its block with __pte_leaf_size(), and pte_update() writes the whole block. An 8M page spans two page tables, and pte_update() takes it by its first PMD entry.

__kernel_map_pages() runs in the page allocator with interrupts disabled. It keeps changing the PTEs with apply_to_existing_page_range(), now with one flush per call. It was the only user of set_memory_np() and set_memory_p(), so they are removed.

---
 arch/powerpc/Kconfig                  |   1 +
 arch/powerpc/include/asm/set_memory.h |  46 +---------
 arch/powerpc/mm/pageattr.c            | 160 +++++++++++++++++++---------------
 3 files changed, 94 insertions(+), 113 deletions(-)
arch/powerpc/Kconfig +1 -0
index c3b6cd655606..fbe3a3abeea8 100644
@@ -211,6 +211,7 @@ config PPC
 	select GENERIC_IOREMAP
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
+	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP		if PCI
 	select GENERIC_SMP_IDLE_THREAD
 	select HAS_IOPORT			if PCI
arch/powerpc/include/asm/set_memory.h +1 -45

51 lines not on this page · raw message

arch/powerpc/mm/pageattr.c +92 -68

207 lines not on this page · raw message

Signature · 1 line
2.53.0
#40 lore raw

RFC PATCH v2 40/54 riscv: replace set_memory_rw_nx() with set_memory_nx() and set_memory_rw()

In reply to Mike Rapoport (Microsoft)

free_initmem() is the only user of set_memory_rw_nx(). Keeping it would require the generic set_memory() to provide an operation for riscv alone.

Make free_initmem() clear the executable bit with set_memory_nx() and then make the range writable with set_memory_rw(), like x86 does in free_init_pages(). In this order the init text never becomes writable and executable.

Remove set_memory_rw_nx().

---
 arch/riscv/include/asm/set_memory.h | 2 --
 arch/riscv/kernel/setup.c           | 6 +++++-
 arch/riscv/mm/pageattr.c            | 6 ------
 3 files changed, 5 insertions(+), 9 deletions(-)
arch/riscv/include/asm/set_memory.h +0 -2
index e9f9960c1947..b9a8c7033c7a 100644
@@ -15,7 +15,6 @@ int set_memory_ro(unsigned long addr, int numpages);
 int set_memory_rw(unsigned long addr, int numpages);
 int set_memory_x(unsigned long addr, int numpages);
 int set_memory_nx(unsigned long addr, int numpages);
-int set_memory_rw_nx(unsigned long addr, int numpages);
 static __always_inline int set_kernel_memory(char *startp, char *endp,
 					     int (*set_memory)(unsigned long start,
 							       int num_pages))
@@ -31,7 +30,6 @@ static inline int set_memory_ro(unsigned long addr, int numpages) { return 0; }
 static inline int set_memory_rw(unsigned long addr, int numpages) { return 0; }
 static inline int set_memory_x(unsigned long addr, int numpages) { return 0; }
 static inline int set_memory_nx(unsigned long addr, int numpages) { return 0; }
-static inline int set_memory_rw_nx(unsigned long addr, int numpages) { return 0; }
 static inline int set_kernel_memory(char *startp, char *endp,
 				    int (*set_memory)(unsigned long start,
 						      int num_pages))
arch/riscv/kernel/setup.c +5 -1
index d79f99b86033..948f0e27aebd 100644
@@ -378,7 +378,11 @@ bool arch_cpu_is_hotpluggable(int cpu)
 void free_initmem(void)
 {
 	if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX)) {
-		set_kernel_memory(lm_alias(__init_begin), lm_alias(__init_end), set_memory_rw_nx);
+		/* Clear X before setting W, so that the range is never W+X */
+		set_kernel_memory(lm_alias(__init_begin), lm_alias(__init_end),
+				  set_memory_nx);
+		set_kernel_memory(lm_alias(__init_begin), lm_alias(__init_end),
+				  set_memory_rw);
 		if (IS_ENABLED(CONFIG_64BIT))
 			set_kernel_memory(__init_begin, __init_end, set_memory_nx);
 	}
arch/riscv/mm/pageattr.c +0 -6
index 5a1a3b4473c9..433ac98234ed 100644
@@ -351,12 +351,6 @@ static int __set_memory(unsigned long addr, int numpages, pgprot_t set_mask,
 	return ret;
 }
 
-int set_memory_rw_nx(unsigned long addr, int numpages)
-{
-	return __set_memory(addr, numpages, __pgprot(_PAGE_READ | _PAGE_WRITE),
-			    __pgprot(_PAGE_EXEC));
-}
-
 int set_memory_ro(unsigned long addr, int numpages)
 {
 	return __set_memory(addr, numpages, __pgprot(_PAGE_READ),
Signature · 1 line
2.53.0
#41 lore raw

RFC PATCH v2 41/54 riscv: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

riscv changes kernel page protections with a page table walk of its own, and the walk gets several things wrong:

* it splits a large page that a request covers in part even when the request does not change it, like the linear map alias for set_memory_x()
* it splits the linear map alias of a vmalloc area down to PAGE_SIZE, page by page, even when the area is mapped with large pages
* it writes every entry in the range, including the empty ones
* for memory that is mapped but is not RAM, like ioremap(), it dereferences a NULL page array when it looks for the alias
* it flushes the entire TLB on every request, even for set_direct_map_*_noflush(), whose callers flush themselves

The availability of the generic CPA core makes riscv's implementation of set_memory_*() APIs unnecessary and it can be replaced with several hooks required by CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points, which correct all of these:

* a large page is split only when a request changes a part of it, both in the requested range and in its alias
* an empty entry in the range is reported with a warning and -EFAULT
* memory that is not RAM has no alias to walk
* a request flushes the TLB for its range, and the entire TLB after a split, a change of an alias or a failure
* set_direct_map_*_noflush() flush only what they must: a split, and on 32-bit an entry that becomes valid

Other changes that come with the core:

* requests are serialized by the core, rather than by the init_mm write lock; the page table dump may now run during a split, which never frees a table, and sees either the leaf or a complete table
* lazily unmapped vmap areas are purged before a request, so that they do not keep stale TLB entries with the old protection
* set_memory_rox() is a single request instead of set_memory_ro() followed by set_memory_x()
* a NAPOT block changes as a whole and is never split: a request on a part of one fails with a warning and -EINVAL; no kernel mapping uses NAPOT blocks yet

---
 arch/riscv/Kconfig                  |   1 +
 arch/riscv/include/asm/pageattr.h   |  17 ++
 arch/riscv/include/asm/set_memory.h |   8 +-
 arch/riscv/mm/pageattr.c            | 448 ++++++++++--------------------------
 4 files changed, 137 insertions(+), 337 deletions(-)
arch/riscv/Kconfig +1 -0
index e7891a2a89da..0453c665fc64 100644
@@ -122,6 +122,7 @@ config RISCV
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
+	select GENERIC_PAGEATTR if MMU
 	select GENERIC_PENDING_IRQ if SMP
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
arch/riscv/include/asm/pageattr.h new file +17 -0
new file mode 100644
index 000000000000..137af4296ebb
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_RISCV_PAGEATTR_H
+#define _ASM_RISCV_PAGEATTR_H
+
+#ifdef CONFIG_64BIT
+#define cpa_is_direct_map(addr)	is_linear_mapping(addr)
+
+bool arch_cpa_can_split(struct cpa_data *cpa, struct cpa_leaf *leaf);
+int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
+			void *table);
+#define arch_cpa_can_split arch_cpa_can_split
+
+int arch_cpa_process_alias(struct cpa_data *cpa);
+#define arch_cpa_process_alias arch_cpa_process_alias
+#endif
+
+#endif /* _ASM_RISCV_PAGEATTR_H */
arch/riscv/include/asm/set_memory.h +2 -6
index b9a8c7033c7a..edbf7d46f809 100644
@@ -11,10 +11,8 @@
  * Functions to change memory attributes.
  */
 #ifdef CONFIG_MMU
-int set_memory_ro(unsigned long addr, int numpages);
-int set_memory_rw(unsigned long addr, int numpages);
-int set_memory_x(unsigned long addr, int numpages);
-int set_memory_nx(unsigned long addr, int numpages);
+#include <asm-generic/set_memory.h>
+
 static __always_inline int set_kernel_memory(char *startp, char *endp,
 					     int (*set_memory)(unsigned long start,
 							       int num_pages))
@@ -38,8 +36,6 @@ static inline int set_kernel_memory(char *startp, char *endp,
 }
 #endif
 
-int set_direct_map_invalid_noflush(struct page *page, unsigned int nr);
-int set_direct_map_default_noflush(struct page *page, unsigned int nr);
 bool kernel_page_present(struct page *page);
 
 #endif /* __ASSEMBLER__ */
arch/riscv/mm/pageattr.c +117 -331

503 lines not on this page · raw message

Signature · 1 line
2.53.0
#42 lore raw

RFC PATCH v2 42/54 riscv: count the mappings of the linear map

In reply to Mike Rapoport (Microsoft)

The CPA core keeps a counter of the linear map entries at every page table level and displays the "Breakdown of page table sizes used in the kernel's identity mapping of RAM" in /proc/meminfo.

When a large mapping is split, the counters of the split level and the one below are updated as well as direct_map_level2_splits or direct_map_level3_splits event counters displayed in /proc/vmstat.

The initial updates for these counters happen when an architecture creates its linear map.

riscv doesn't seed these counters, so the CPA core cannot update them during a split, and the split events stay at zero.

Count the linear map when it is created at boot and on memory hot-plug and hot-remove.

Report the counters in /proc/meminfo, as x86 and s390 do.

---
 arch/riscv/mm/init.c     | 20 ++++++++++++++++++++
 arch/riscv/mm/pageattr.c | 15 +++++++++++++++
 2 files changed, 35 insertions(+)
arch/riscv/mm/init.c +20 -0
index e1bcc3a16129..b466db515ee1 100644
@@ -28,6 +28,9 @@
 #include <linux/kfence.h>
 #include <linux/execmem.h>
 #include <linux/vmemmap-optimization.h>
+#ifdef CONFIG_MMU
+#include <linux/pageattr.h>
+#endif
 
 #include <asm/alternative.h>
 #include <asm/fixmap.h>
@@ -1201,6 +1204,15 @@ asmlinkage void __init setup_vm(uintptr_t dtb_pa)
 	pt_ops_set_fixmap();
 }
 
+static enum pgtable_level __meminit linear_map_level(uintptr_t map_size)
+{
+	if (map_size == PUD_SIZE)
+		return PGTABLE_LEVEL_PUD;
+	if (map_size == PMD_SIZE)
+		return PGTABLE_LEVEL_PMD;
+	return PGTABLE_LEVEL_PTE;
+}
+
 static void __meminit create_linear_mapping_range(phys_addr_t start, phys_addr_t end,
 						  uintptr_t fixed_map_size, const pgprot_t *pgprot)
 {
@@ -1214,6 +1226,7 @@ static void __meminit create_linear_mapping_range(phys_addr_t start, phys_addr_t
 
 		create_pgd_mapping(swapper_pg_dir, va, pa, map_size,
 				   pgprot ? *pgprot : pgprot_from_va(va));
+		direct_map_count_update(linear_map_level(map_size), 1);
 	}
 }
 
@@ -1599,6 +1612,8 @@ static void __meminit remove_pte_mapping(pte_t *pte_base, unsigned long addr, un
 		pte_clear(&init_mm, addr, ptep);
 		if (is_vmemmap)
 			free_vmemmap_storage(pte_page(pte), PAGE_SIZE, altmap);
+		else
+			direct_map_count_update(PGTABLE_LEVEL_PTE, -1);
 	}
 }
 
@@ -1620,6 +1635,8 @@ static void __meminit remove_pmd_mapping(pmd_t *pmd_base, unsigned long addr, un
 			pmd_clear(pmdp);
 			if (is_vmemmap)
 				free_vmemmap_storage(pmd_page(pmd), PMD_SIZE, altmap);
+			else
+				direct_map_count_update(PGTABLE_LEVEL_PMD, -1);
 			continue;
 		}
 
@@ -1648,6 +1665,9 @@ static void __meminit remove_pud_mapping(pud_t *pud_base, unsigned long addr, un
 				pud_clear(pudp);
 				if (is_vmemmap)
 					free_vmemmap_storage(pud_page(pud), PUD_SIZE, altmap);
+				else
+					direct_map_count_update(
+						PGTABLE_LEVEL_PUD, -1);
 			}
 			continue;
 		}
arch/riscv/mm/pageattr.c +15 -0
index bb8629da0d1d..22826ba688c3 100644
@@ -5,12 +5,27 @@
 
 #include <linux/pageattr.h>
 #include <linux/pgtable.h>
+#include <linux/proc_fs.h>
 #include <linux/vmalloc.h>
 #include <linux/cacheflush.h>
 #include <asm/tlbflush.h>
 #include <asm/bitops.h>
 #include <asm/set_memory.h>
 
+#ifdef CONFIG_PROC_FS
+void arch_report_meminfo(struct seq_file *m)
+{
+	unsigned long levels = BIT(PGTABLE_LEVEL_PTE);
+
+	if (IS_ENABLED(CONFIG_64BIT))
+		levels |= BIT(PGTABLE_LEVEL_PMD);
+	if (pgtable_l4_enabled())
+		levels |= BIT(PGTABLE_LEVEL_PUD);
+
+	cpa_report_meminfo(m, levels);
+}
+#endif
+
 void arch_cpa_decode_leaf(struct cpa_leaf *leaf)
 {
 	pte_t pte = ptep_get(leaf->kpte);
Signature · 1 line
2.53.0
#43 lore raw

RFC PATCH v2 43/54 mm/pageattr: let an architecture allocate the page tables for a split

In reply to Mike Rapoport (Microsoft)

The core allocates the page table for a split with pte_alloc_one_kernel() and pmd_alloc_one(). s390 cannot use them.

vmem_map_init() write protects the kernel image before the page allocator is up, so a split at that time has to allocate from memblock.

A fallback to memblock in the core would not be enough. With CMMA, the decompressor marks all memory as no-DAT, and a page has to be switched back to DAT before it is used as a page table.

vmem_pte_alloc() and vmem_crst_alloc() do both: they fall back to memblock and initialize the page.

Memory hot-remove frees the tables of the identity map with vmem_free_pages(), so a segment table in the identity map has to come from vmem_crst_alloc() rather than from pmd_alloc_one().

Let an architecture provide arch_cpa_alloc_pgtable() and arch_cpa_free_pgtable().

There are no users yet. s390 will use them when it switches to the core.

---
 include/linux/pageattr.h | 6 ++++++
 mm/pageattr.c            | 6 ++++--
 2 files changed, 10 insertions(+), 2 deletions(-)
include/linux/pageattr.h +6 -0
index 091408ad328f..1a4e7c5dca98 100644
@@ -111,6 +111,12 @@ static inline int arch_cpa_split_leaf(struct cpa_data *cpa,
 }
 #endif
 
+#ifndef arch_cpa_alloc_pgtable
+void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf);
+
+void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table);
+#endif
+
 #ifndef cpa_is_direct_map
 static inline bool cpa_is_direct_map(unsigned long addr)
 {
mm/pageattr.c +4 -2
index 2f357a8c24d2..e05281a2b169 100644
@@ -249,7 +249,8 @@ static pte_t *cpa_lookup(struct cpa_data *cpa, unsigned long address,
 	return leaf->kpte;
 }
 
-static void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf)
+#ifndef arch_cpa_alloc_pgtable
+void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf)
 {
 	if (leaf->level == PGTABLE_LEVEL_PMD)
 		return pte_alloc_one_kernel(&init_mm);
@@ -257,13 +258,14 @@ static void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf)
 	return pmd_alloc_one(&init_mm, leaf->addr);
 }
 
-static void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
+void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table)
 {
 	if (leaf->level == PGTABLE_LEVEL_PMD)
 		pte_free_kernel(&init_mm, table);
 	else
 		pmd_free(&init_mm, table);
 }
+#endif
 
 static int should_split_large_page(struct cpa_data *cpa, struct cpa_leaf *leaf)
 {
Signature · 1 line
2.53.0
#44 lore raw

RFC PATCH v2 44/54 mm/pageattr: derive direct map counter updates from the level sizes

In reply to Mike Rapoport (Microsoft)

The direct map counters add PTRS_PER_PTE entries at the next level for every split.

That is right on x86, riscv and arm64, where all levels have the same number of entries and PTRS_PER_PTE is the same as PTRS_PER_PMD.

This is not the case on s390.

An s390 segment table has 2048 entries and a page table has 256, i.e. PTRS_PER_PMD is 2048 and PTRS_PER_PTE is 256.

A split of a PUD mapping on s390 would add 2048 entries to the PMD counters.

Replace the hard-coded PTRS_PER_PTE in the counter update with a helper that derives the number of entries from the sizes of the two levels.

---
 mm/pageattr.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
mm/pageattr.c +7 -2
index e05281a2b169..555e55e7ecea 100644
@@ -48,6 +48,11 @@ void direct_map_count_update(enum pgtable_level level, long pages)
 	atomic_long_add(pages, &cpa_direct_map_pages[level]);
 }
 
+static long nr_entries(enum pgtable_level level)
+{
+	return pgtable_level_size(level) / pgtable_level_size(level - 1);
+}
+
 void direct_map_count_split(enum pgtable_level level)
 {
 	if (atomic_long_dec_if_positive(&cpa_direct_map_pages[level]) < 0)
@@ -59,7 +64,7 @@ void direct_map_count_split(enum pgtable_level level)
 		else if (level == PGTABLE_LEVEL_PUD)
 			count_vm_event(DIRECT_MAP_LEVEL3_SPLIT);
 	}
-	atomic_long_add(PTRS_PER_PTE, &cpa_direct_map_pages[level - 1]);
+	atomic_long_add(nr_entries(level), &cpa_direct_map_pages[level - 1]);
 }
 
 void direct_map_count_collapse(enum pgtable_level level)
@@ -71,7 +76,7 @@ void direct_map_count_collapse(enum pgtable_level level)
 		else if (level == PGTABLE_LEVEL_PUD)
 			count_vm_event(DIRECT_MAP_LEVEL3_COLLAPSE);
 	}
-	atomic_long_sub(PTRS_PER_PTE, &cpa_direct_map_pages[level - 1]);
+	atomic_long_sub(nr_entries(level), &cpa_direct_map_pages[level - 1]);
 }
 
 void cpa_report_meminfo(struct seq_file *m, unsigned long levels)
Signature · 1 line
2.53.0
#45 lore raw

RFC PATCH v2 45/54 s390/boot: map the identity map with 4K pages for debug_pagealloc

In reply to Mike Rapoport (Microsoft)

debug_pagealloc maps and unmaps single pages of the identity map, so it needs the identity map to use 4K pages.

The decompressor maps it with large pages regardless, and vmem_map_init() then splits it with __set_memory_4k().

The s390 implementation of change_page_attr() skips the PTE level for that request, so the split costs little more than filling the new page tables.

The generic CPA core, which s390 is going to use, has no such shortcut:
after the split it would visit each page of the identity map, taking cpa_lock and walking the page table for every one of them.

Parse debug_pagealloc in the decompressor and map the identity map with 4K pages when it is enabled, like x86 and arm64 do for their direct and linear maps. Drop the split from vmem_map_init().

---
 arch/s390/boot/boot.h     | 1 +
 arch/s390/boot/ipl_parm.c | 9 +++++++++
 arch/s390/boot/vmem.c     | 3 ++-
 arch/s390/mm/vmem.c       | 2 --
 4 files changed, 12 insertions(+), 3 deletions(-)
arch/s390/boot/boot.h +1 -0
index 61a205b489fb..07ca806ff8ff 100644
@@ -110,6 +110,7 @@ extern const char kernel_version[];
 extern unsigned long memory_limit;
 extern unsigned long vmalloc_size;
 extern int vmalloc_size_set;
+extern bool debug_pagealloc;
 extern char __boot_data_start[], __boot_data_end[];
 extern char __boot_data_preserved_start[], __boot_data_preserved_end[];
 extern char __vmlinux_relocs_64_start[], __vmlinux_relocs_64_end[];
arch/s390/boot/ipl_parm.c +9 -0
index ac4cf1ced71d..cf6c6679c5a5 100644
@@ -34,6 +34,7 @@ int __bootdata_preserved(cmma_flag) = 1;
 unsigned long vmalloc_size = VMALLOC_DEFAULT_SIZE;
 unsigned long memory_limit;
 int vmalloc_size_set;
+bool debug_pagealloc = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
 
 static inline int __diag308(unsigned long subcode, void *addr)
 {
@@ -332,6 +333,14 @@ void parse_boot_command_line(void)
 			stack_protector_debug = 1;
 #endif
 
+#ifdef CONFIG_DEBUG_PAGEALLOC
+		if (parameq(param, "debug_pagealloc")) {
+			rc = kstrtobool(val, &enabled);
+			if (!rc)
+				debug_pagealloc = enabled;
+		}
+#endif
+
 #if IS_ENABLED(CONFIG_KVM)
 		if (parameq(param, "prot_virt")) {
 			rc = kstrtobool(val, &enabled);
arch/s390/boot/vmem.c +2 -1
index ff6d58a476ba..3a6cd62c31ae 100644
@@ -286,8 +286,9 @@ static unsigned long resolve_pa_may_alloc(unsigned long addr, unsigned long size
 static bool large_page_mapping_allowed(enum populate_mode mode)
 {
 	switch (mode) {
-	case POPULATE_DIRECT:
 	case POPULATE_IDENTITY:
+		return !debug_pagealloc;
+	case POPULATE_DIRECT:
 	case POPULATE_KERNEL:
 #ifdef CONFIG_KASAN
 	case POPULATE_KASAN_MAP_SHADOW:
arch/s390/mm/vmem.c +0 -2
index d2879ce860a1..191326ee7ec8 100644
@@ -681,8 +681,6 @@ void __init vmem_map_init(void)
 	 */
 	if (!cpu_has_bear())
 		set_memory_x(0, 1);
-	if (debug_pagealloc_enabled())
-		__set_memory_4k(__va(0), absolute_pointer(__va(0)) + ident_map_size);
 	pr_info("Write protected kernel read-only data: %luk\n",
 		(unsigned long)(__end_rodata - _stext) >> 10);
 }
Signature · 1 line
2.53.0
#46 lore raw

RFC PATCH v2 46/54 s390: remove set_memory_rwnx()

In reply to Mike Rapoport (Microsoft)

set_memory_rwnx() has no users since commit 33bd8d153c33 ("s390: Keep inittext section writable").

Remove it.

---
 arch/s390/include/asm/set_memory.h | 1 -
 1 file changed, 1 deletion(-)
arch/s390/include/asm/set_memory.h +0 -1
index e3562bf0c1aa..23987b721ed9 100644
@@ -57,7 +57,6 @@ __SET_MEMORY_FUNC(set_memory_rw, SET_MEMORY_RW)
 __SET_MEMORY_FUNC(set_memory_nx, SET_MEMORY_NX)
 __SET_MEMORY_FUNC(set_memory_x, SET_MEMORY_X)
 __SET_MEMORY_FUNC(set_memory_rox, SET_MEMORY_RO | SET_MEMORY_X)
-__SET_MEMORY_FUNC(set_memory_rwnx, SET_MEMORY_RW | SET_MEMORY_NX)
 __SET_MEMORY_FUNC(set_memory_4k, SET_MEMORY_4K)
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr);
Signature · 1 line
2.53.0
#47 lore raw

RFC PATCH v2 47/54 s390: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

s390 implementation of set_memory_*() APIs has a few shortcomings:

* it splits every large page that a request touches, even when the request covers it with one protection
* it writes every entry of the range, whether anything changes or not
* only VM_ALLOC areas change their identity map alias, so the identity map alias of the kernel image stays writable after the image is write protected

The availability of the generic CPA core makes s390's implementation of set_memory_*() APIs unnecessary and it can be replaced with several hooks required by CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points. For s390 this means that:

* a large page is kept when a request covers it with one protection and split only otherwise
* nothing is written when nothing changes
* a hole in the identity map is skipped
* an unmapped address outside of the identity map is reported with a warning and -EFAULT
* the identity map alias follows read-only and read-write changes of any mapping of RAM outside the identity map, the kernel image included
* set_memory_4k() is implemented using a split request to the core
* the direct map counters are the generic ones; the DirectMap lines of /proc/meminfo do not change
* requests are serialized by the core, rather than by cpa_mutex; the page table dump may now run during a split by set_direct_map_*_noflush(), which never frees a table, and sees either the leaf or a complete table
* lazily unmapped vmap areas are purged before a request, so that they do not keep stale TLB entries with the old protection

The page table modification hooks write entries with pgt_set(), which uses CRDTE or CSPG, so there is no need to flush the TLB at the end of a CPA request.

vmem.c keeps split_pud_page() for memory hot-remove, built from the same hooks.

The boot time counts of the decompressor are folded into the generic counters in paging_init(), before the first split.

---
 arch/s390/Kconfig                  |   1 +
 arch/s390/include/asm/pageattr.h   |  21 ++
 arch/s390/include/asm/set_memory.h |  55 +---
 arch/s390/mm/dump_pagetables.c     |   2 -
 arch/s390/mm/init.c                |  15 ++
 arch/s390/mm/pageattr.c            | 496 ++++++++++++++++---------------------
 arch/s390/mm/vmem.c                |  10 +-
 7 files changed, 272 insertions(+), 328 deletions(-)
arch/s390/Kconfig +1 -0
index 7138d923d86f..413b886a9e9a 100644
@@ -180,6 +180,7 @@ config S390
 	select GENERIC_CPU_VULNERABILITIES
 	select GENERIC_ENTRY
 	select GENERIC_GETTIMEOFDAY
+	select GENERIC_PAGEATTR
 	select GENERIC_SMP_IDLE_THREAD
 	select GENERIC_IOREMAP
 	select GLOB
arch/s390/include/asm/pageattr.h new file +21 -0
new file mode 100644
index 000000000000..83c4a40a9b20
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_S390_PAGEATTR_H
+#define _ASM_S390_PAGEATTR_H
+
+void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf);
+void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table);
+#define arch_cpa_alloc_pgtable arch_cpa_alloc_pgtable
+
+int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
+			void *table);
+static inline bool arch_cpa_can_split(struct cpa_data *cpa,
+				      struct cpa_leaf *leaf)
+{
+	return true;
+}
+#define arch_cpa_can_split arch_cpa_can_split
+
+int arch_cpa_process_alias(struct cpa_data *cpa);
+#define arch_cpa_process_alias arch_cpa_process_alias
+
+#endif /* _ASM_S390_PAGEATTR_H */
arch/s390/include/asm/set_memory.h +11 -44

76 lines not on this page · raw message

arch/s390/mm/dump_pagetables.c +0 -2
index a23a0bd4d8a8..7533dc22e0e9 100644
@@ -247,9 +247,7 @@ static int ptdump_show(struct seq_file *m, void *v)
 		.marker = markers,
 	};
 
-	mutex_lock(&cpa_mutex);
 	ptdump_walk_pgd(&st.ptdump, &init_mm, NULL);
-	mutex_unlock(&cpa_mutex);
 	return 0;
 }
 DEFINE_SHOW_ATTRIBUTE(ptdump);
arch/s390/mm/init.c +15 -0
index be7e009e7b59..ce51c2ca8e3b 100644
@@ -24,6 +24,7 @@
 #include <linux/init.h>
 #include <linux/pagemap.h>
 #include <linux/memblock.h>
+#include <linux/pageattr.h>
 #include <linux/memory.h>
 #include <linux/pfn.h>
 #include <linux/poison.h>
@@ -95,11 +96,25 @@ void __init arch_zone_limits_init(unsigned long *max_zone_pfns)
 	max_zone_pfns[ZONE_NORMAL] = max_low_pfn;
 }
 
+static long __init direct_pages(int type)
+{
+	return atomic_long_read(&direct_pages_count[type]);
+}
+
 /*
  * paging_init() sets up the page tables
  */
 void __init paging_init(void)
 {
+	if (IS_ENABLED(CONFIG_PROC_FS)) {
+		direct_map_count_update(PGTABLE_LEVEL_PTE,
+					direct_pages(PG_DIRECT_MAP_4K));
+		direct_map_count_update(PGTABLE_LEVEL_PMD,
+					direct_pages(PG_DIRECT_MAP_1M));
+		direct_map_count_update(PGTABLE_LEVEL_PUD,
+					direct_pages(PG_DIRECT_MAP_2G));
+	}
+
 	vmem_map_init();
 	zone_dma_limit = DMA_BIT_MASK(31);
 }
arch/s390/mm/pageattr.c +217 -279

555 lines not on this page · raw message

arch/s390/mm/vmem.c +7 -3
index 191326ee7ec8..3cf4e6987ac0 100644
@@ -6,6 +6,7 @@
 #include <linux/memory_hotplug.h>
 #include <linux/cpufeature.h>
 #include <linux/memblock.h>
+#include <linux/pageattr.h>
 #include <linux/pfn.h>
 #include <linux/mm.h>
 #include <linux/init.h>
@@ -198,7 +199,8 @@ static int __ref modify_pte_table(pmd_t *pmd, unsigned long addr,
 	ret = 0;
 out:
 	if (direct)
-		update_page_count(PG_DIRECT_MAP_4K, add ? pages : -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PTE,
+					add ? pages : -pages);
 	return ret;
 }
 
@@ -295,7 +297,8 @@ static int __ref modify_pmd_table(pud_t *pud, unsigned long addr,
 	ret = 0;
 out:
 	if (direct)
-		update_page_count(PG_DIRECT_MAP_1M, add ? pages : -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PMD,
+					add ? pages : -pages);
 	return ret;
 }
 
@@ -365,7 +368,8 @@ static int modify_pud_table(p4d_t *p4d, unsigned long addr, unsigned long end,
 	ret = 0;
 out:
 	if (direct)
-		update_page_count(PG_DIRECT_MAP_2G, add ? pages : -pages);
+		direct_map_count_update(PGTABLE_LEVEL_PUD,
+					add ? pages : -pages);
 	return ret;
 }
 
Signature · 1 line
2.53.0
#48 lore raw

RFC PATCH v2 48/54 mm/pageattr: let an architecture bracket the set_memory() entry points

In reply to Mike Rapoport (Microsoft)

arm64 changes its kernel page tables in lazy MMU mode, so that a request pays for one set of barriers for a range rather than one for every entry it writes.

The core cannot enter lazy MMU mode by itself. On powerpc with the hash MMU that disables preemption, and a CPA request may sleep.

Call arch_cpa_enter() and arch_cpa_leave() around the request of the generic set_memory_*() and set_direct_map_*_noflush(). They do nothing by default.

arm64 will use them to enable lazy MMU mode when it switches to the core.

---
 include/linux/pageattr.h | 12 ++++++++++++
 mm/pageattr.c            | 12 ++++++++++--
 2 files changed, 22 insertions(+), 2 deletions(-)
include/linux/pageattr.h +12 -0
index 1a4e7c5dca98..a2a7235a633e 100644
@@ -171,4 +171,16 @@ static inline void cpa_init_op(struct cpa_data *cpa,
 
 int arch_cpa_prepare(struct cpa_data *cpa, enum cpa_op op);
 
+#ifndef arch_cpa_enter
+static inline void arch_cpa_enter(void)
+{
+}
+#endif
+
+#ifndef arch_cpa_leave
+static inline void arch_cpa_leave(void)
+{
+}
+#endif
+
 #endif /* _LINUX_PAGEATTR_H */
mm/pageattr.c +10 -2
index 555e55e7ecea..d8ca8fb9bdd1 100644
@@ -615,7 +615,11 @@ static int set_memory_op(unsigned long addr, int numpages, enum cpa_op op)
 	    !(cpa.flags & CPA_REQ_SPLIT))
 		return 0;
 
-	return change_page_attr(&cpa);
+	arch_cpa_enter();
+	ret = change_page_attr(&cpa);
+	arch_cpa_leave();
+
+	return ret;
 }
 
 int set_memory_x(unsigned long addr, int numpages)
@@ -661,7 +665,11 @@ static int set_direct_map(struct page *page, unsigned int nr, enum cpa_op op)
 	 * set_direct_map_*_noflush() change only the direct map, not its
 	 * aliases.
 	 */
-	return change_page_attr_noflush(&cpa);
+	arch_cpa_enter();
+	ret = change_page_attr_noflush(&cpa);
+	arch_cpa_leave();
+
+	return ret;
 }
 
 int set_direct_map_invalid_noflush(struct page *page, unsigned int nr)
Signature · 1 line
2.53.0
#49 lore raw

RFC PATCH v2 49/54 arm64: mm: allocate page tables in the callers of split_p{mu}d()

In reply to Mike Rapoport (Microsoft)

The generic CPA core allocates the page table for a split before it takes cpa_lock and hands it to the architecture hook that splits a large mapping.

Let the callers of split_pmd() and split_pud() allocate the table, so that the arm64's hook can use the helpers as they are.

No functional change.

---
 arch/arm64/mm/mmu.c | 93 +++++++++++++++++++++++++++++++----------------------
 1 file changed, 54 insertions(+), 39 deletions(-)
arch/arm64/mm/mmu.c +54 -39
index 140520b351e2..0f96efea9057 100644
@@ -601,20 +601,14 @@ static void split_contpte(pte_t *ptep)
 		__set_pte(ptep, pte_mknoncont(__ptep_get(ptep)));
 }
 
-static int split_pmd(pmd_t *pmdp, pmd_t pmd, gfp_t gfp, bool to_cont)
+static void split_pmd(pmd_t *pmdp, pmd_t pmd, pte_t *ptep, bool to_cont)
 {
 	pmdval_t tableprot = PMD_TYPE_TABLE | PMD_TABLE_UXN | PMD_TABLE_AF;
+	phys_addr_t pte_phys = virt_to_phys(ptep);
 	unsigned long pfn = pmd_pfn(pmd);
 	pgprot_t prot = pmd_pgprot(pmd);
-	phys_addr_t pte_phys;
-	pte_t *ptep;
 	int i;
 
-	pte_phys = pgd_pgtable_alloc_init_mm_gfp(PGTABLE_LEVEL_PTE, gfp);
-	if (pte_phys == INVALID_PHYS_ADDR)
-		return -ENOMEM;
-	ptep = (pte_t *)phys_to_virt(pte_phys);
-
 	if (pgprot_val(prot) & PMD_SECT_PXN)
 		tableprot |= PMD_TABLE_PXN;
 
@@ -634,8 +628,6 @@ static int split_pmd(pmd_t *pmdp, pmd_t pmd, gfp_t gfp, bool to_cont)
 	 */
 	dsb(ishst);
 	__pmd_populate(pmdp, pte_phys, tableprot);
-
-	return 0;
 }
 
 static void split_contpmd(pmd_t *pmdp)
@@ -647,21 +639,15 @@ static void split_contpmd(pmd_t *pmdp)
 		set_pmd(pmdp, pmd_mknoncont(pmdp_get(pmdp)));
 }
 
-static int split_pud(pud_t *pudp, pud_t pud, gfp_t gfp, bool to_cont)
+static void split_pud(pud_t *pudp, pud_t pud, pmd_t *pmdp, bool to_cont)
 {
 	pudval_t tableprot = PUD_TYPE_TABLE | PUD_TABLE_UXN | PUD_TABLE_AF;
 	unsigned int step = PMD_SIZE >> PAGE_SHIFT;
+	phys_addr_t pmd_phys = virt_to_phys(pmdp);
 	unsigned long pfn = pud_pfn(pud);
 	pgprot_t prot = pud_pgprot(pud);
-	phys_addr_t pmd_phys;
-	pmd_t *pmdp;
 	int i;
 
-	pmd_phys = pgd_pgtable_alloc_init_mm_gfp(PGTABLE_LEVEL_PMD, gfp);
-	if (pmd_phys == INVALID_PHYS_ADDR)
-		return -ENOMEM;
-	pmdp = (pmd_t *)phys_to_virt(pmd_phys);
-
 	if (pgprot_val(prot) & PMD_SECT_PXN)
 		tableprot |= PUD_TABLE_PXN;
 
@@ -681,8 +667,17 @@ static int split_pud(pud_t *pudp, pud_t pud, gfp_t gfp, bool to_cont)
 	 */
 	dsb(ishst);
 	__pud_populate(pudp, pmd_phys, tableprot);
+}
 
-	return 0;
+static void *split_pgtable_alloc(enum pgtable_level level, gfp_t gfp)
+{
+	phys_addr_t phys;
+
+	phys = pgd_pgtable_alloc_init_mm_gfp(level, gfp);
+	if (phys == INVALID_PHYS_ADDR)
+		return NULL;
+
+	return phys_to_virt(phys);
 }
 
 static int split_kernel_leaf_mapping_locked(unsigned long addr)
@@ -692,6 +687,7 @@ static int split_kernel_leaf_mapping_locked(unsigned long addr)
 	pud_t *pudp, pud;
 	pmd_t *pmdp, pmd;
 	pte_t *ptep, pte;
+	void *table;
 	int ret = 0;
 
 	/*
@@ -728,9 +724,13 @@ static int split_kernel_leaf_mapping_locked(unsigned long addr)
 	if (!pud_present(pud))
 		goto out;
 	if (pud_leaf(pud)) {
-		ret = split_pud(pudp, pud, GFP_PGTABLE_KERNEL, true);
-		if (ret)
+		table = split_pgtable_alloc(PGTABLE_LEVEL_PMD,
+					    GFP_PGTABLE_KERNEL);
+		if (!table) {
+			ret = -ENOMEM;
 			goto out;
+		}
+		split_pud(pudp, pud, table, true);
 	}
 
 	/*
@@ -753,9 +753,13 @@ static int split_kernel_leaf_mapping_locked(unsigned long addr)
 		 */
 		if (ALIGN_DOWN(addr, PMD_SIZE) == addr)
 			goto out;
-		ret = split_pmd(pmdp, pmd, GFP_PGTABLE_KERNEL, true);
-		if (ret)
+		table = split_pgtable_alloc(PGTABLE_LEVEL_PTE,
+					    GFP_PGTABLE_KERNEL);
+		if (!table) {
+			ret = -ENOMEM;
 			goto out;
+		}
+		split_pmd(pmdp, pmd, table, true);
 	}
 
 	/*
@@ -874,12 +878,18 @@ static int split_to_ptes_pud_entry(pud_t *pudp, unsigned long addr,
 {
 	gfp_t gfp = *(gfp_t *)walk->private;
 	pud_t pud = pudp_get(pudp);
-	int ret = 0;
+	pmd_t *pmdp;
 
-	if (pud_leaf(pud))
-		ret = split_pud(pudp, pud, gfp, false);
+	if (!pud_leaf(pud))
+		return 0;
 
-	return ret;
+	pmdp = split_pgtable_alloc(PGTABLE_LEVEL_PMD, gfp);
+	if (!pmdp)
+		return -ENOMEM;
+
+	split_pud(pudp, pud, pmdp, false);
+
+	return 0;
 }
 
 static int split_to_ptes_pmd_entry(pmd_t *pmdp, unsigned long addr,
@@ -887,21 +897,26 @@ static int split_to_ptes_pmd_entry(pmd_t *pmdp, unsigned long addr,
 {
 	gfp_t gfp = *(gfp_t *)walk->private;
 	pmd_t pmd = pmdp_get(pmdp);
-	int ret = 0;
+	pte_t *ptep;
 
-	if (pmd_leaf(pmd)) {
-		if (pmd_cont(pmd))
-			split_contpmd(pmdp);
-		ret = split_pmd(pmdp, pmd, gfp, false);
+	if (!pmd_leaf(pmd))
+		return 0;
 
-		/*
-		 * We have split the pmd directly to ptes so there is no need to
-		 * visit each pte to check if they are contpte.
-		 */
-		walk->action = ACTION_CONTINUE;
-	}
+	ptep = split_pgtable_alloc(PGTABLE_LEVEL_PTE, gfp);
+	if (!ptep)
+		return -ENOMEM;
 
-	return ret;
+	if (pmd_cont(pmd))
+		split_contpmd(pmdp);
+	split_pmd(pmdp, pmd, ptep, false);
+
+	/*
+	 * We have split the pmd directly to ptes so there is no need to
+	 * visit each pte to check if they are contpte.
+	 */
+	walk->action = ACTION_CONTINUE;
+
+	return 0;
 }
 
 static int split_to_ptes_pte_entry(pte_t *ptep, unsigned long addr,
Signature · 1 line
2.53.0
#50 lore raw

RFC PATCH v2 50/54 arm64: use the generic CPA core

In reply to Mike Rapoport (Microsoft)

arm64 implementation of set_memory_*() APIs has a few shortcomings:

* the page table walk that changes kernel page protections is preceded by another walk that splits the mappings at both ends of a request down to base pages, whether the request needs that or not
* the linear alias of a vmalloc area is changed and flushed page by page
* set_memory_*() refuse anything but a single VM_ALLOC area, a check that dates from when a live mapping could not be split at all and makes arm64 the odd one out among the architectures

The availability of the generic CPA core makes arm64's implementation of set_memory_*() APIs unnecessary and it can be replaced with several hooks required by CPA core.

This way the core can manage the policy decisions and the architecture only has to take care of the page table manipulation.

Switch to the generic CPA core and its set_memory() entry points. For arm64 this means that:

* set_memory_*() accept any kernel mapping; a request that needs a split arm64 cannot do fails with a warning and -EINVAL
* a contiguous block of entries is kept or changed like a large page; its entries are rewritten one by one, so the block has mixed permissions for a few stores, the same window every change has before its TLB flush
* the linear alias follows read-only and read-write changes when rodata_full is set, as before, for any mapping of RAM
* a request and its aliases run in one lazy MMU section
* requests are serialized by the core; the old walk ran without a lock
* KFENCE and debug_pagealloc change the linear map with interrupts disabled and keep a lockless set_memory_valid()
* the linear alias of data and bss, which may use block mappings, is mapped and unmapped for hibernation by a request of its own

The mappings at both ends of a request are still split to base pages before the walk, so the core does not split yet.

---
 arch/arm64/Kconfig                  |   1 +
 arch/arm64/include/asm/pageattr.h   |  18 ++
 arch/arm64/include/asm/set_memory.h |   2 -
 arch/arm64/mm/mmu.c                 |  21 +-
 arch/arm64/mm/pageattr.c            | 387 +++++++++++++++++++-----------------
 5 files changed, 246 insertions(+), 183 deletions(-)
arch/arm64/Kconfig +1 -0
index 9b08b2457a55..846fae788b3c 100644
@@ -138,6 +138,7 @@ config ARM64
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
+	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/arm64/include/asm/pageattr.h new file +18 -0
new file mode 100644
index 000000000000..9634cb523298
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __ASM_PAGEATTR_H
+#define __ASM_PAGEATTR_H
+
+#define cpa_is_direct_map(addr)	__is_lm_address(__tag_reset(addr))
+
+int arch_cpa_process_alias(struct cpa_data *cpa);
+#define arch_cpa_process_alias arch_cpa_process_alias
+
+void arch_cpa_enter(void);
+#define arch_cpa_enter arch_cpa_enter
+
+void arch_cpa_leave(void);
+#define arch_cpa_leave arch_cpa_leave
+
+int arm64_change_page_attr(struct cpa_data *cpa);
+
+#endif /* __ASM_PAGEATTR_H */
arch/arm64/include/asm/set_memory.h +0 -2
index 0091ba12200e..4c4ca9cd50c8 100644
@@ -11,8 +11,6 @@ bool can_set_direct_map(void);
 
 int set_memory_valid(unsigned long addr, int numpages, int enable);
 
-int set_direct_map_invalid_noflush(struct page *page, unsigned int numpages);
-int set_direct_map_default_noflush(struct page *page, unsigned int numpages);
 bool kernel_page_present(struct page *page);
 
 int set_memory_encrypted(unsigned long addr, int numpages);
arch/arm64/mm/mmu.c +18 -3
index 0f96efea9057..c8f3961b4555 100644
@@ -13,6 +13,7 @@
 #include <linux/init.h>
 #include <linux/ioport.h>
 #include <linux/kexec.h>
+#include <linux/pageattr.h>
 #include <linux/libfdt.h>
 #include <linux/mman.h>
 #include <linux/nodemask.h>
@@ -1078,9 +1079,23 @@ static void __init __map_memblock(phys_addr_t start, phys_addr_t end,
 
 static void mark_linear_data_alias_valid(bool valid)
 {
-	set_memory_valid((unsigned long)lm_alias(__init_end),
-			 (unsigned long)(__bss_stop - __init_end) / PAGE_SIZE,
-			 valid);
+	pgprot_t valid_prot = __pgprot(PTE_PRESENT_VALID_KERNEL);
+	pgprot_t invalid_prot = __pgprot(PTE_PRESENT_INVALID);
+	struct cpa_data cpa = {
+		.addr = (unsigned long)lm_alias(__init_end),
+		.numpages = (__bss_stop - __init_end) / PAGE_SIZE,
+		.mask_set = valid ? valid_prot : invalid_prot,
+		.mask_clr = valid ? invalid_prot : valid_prot,
+		.flags = CPA_REQ_NO_CHECK_ALIAS,
+	};
+	int ret;
+
+	ret = split_kernel_leaf_mapping(cpa.addr,
+					cpa.addr + cpa.numpages * PAGE_SIZE);
+	if (WARN_ON_ONCE(ret))
+		return;
+
+	arm64_change_page_attr(&cpa);
 }
 
 static int arm64_hibernate_pm_notify(struct notifier_block *nb,
arch/arm64/mm/pageattr.c +209 -178

468 lines not on this page · raw message

Signature · 1 line
2.53.0
#51 lore raw

RFC PATCH v2 51/54 arm64: let the generic CPA core split large mappings

In reply to Mike Rapoport (Microsoft)

When BBML3 is available, set_memory_*() calls split both ends of a request to base pages before updating the protections, under a mutex, whether the request needs that or not.

The KFENCE pool is split by a walk of its own under the same mutex.

Implement arch_cpa_can_split() and arch_cpa_split_leaf() hooks to let CPA core logic decide which large mappings should be split and synchronize the splits against other CPA operations.

The CPA core makes sure that only the blocks and contiguous entries that must be split are actually split.

Before it splits a mapping, the core calls arch_cpa_can_split(), which allows a split only where the CPU supports BBML3:

* after the capabilities are finalized, when system_supports_bbml3()
* before that, only on the boot CPU, when cpu_supports_bbml3()

With BBML3 a translation of the old size may linger in the TLB, so the split needs no TLB flush, as before.

With that:

* the late KFENCE pool is split by a CPA_REQ_SPLIT request, straight to base pages, so that it cannot race with the splits of the core
* split_kernel_leaf_mapping(), the mutex and page_alloc_available go; a split before the page allocator is populated fails with -ENOMEM from the allocation instead of a warning
* the boot time split of the linear map keeps its current implementation

---
 arch/arm64/include/asm/mmu.h      |   3 -
 arch/arm64/include/asm/pageattr.h |   5 +
 arch/arm64/mm/init.c              |   3 -
 arch/arm64/mm/mmu.c               | 222 +++++++-------------------------------
 arch/arm64/mm/pageattr.c          |  22 +---
 5 files changed, 45 insertions(+), 210 deletions(-)
arch/arm64/include/asm/mmu.h +0 -3
index 5e1211c540ab..9b7f16fa24d0 100644
@@ -70,7 +70,6 @@ extern void create_pgd_mapping(struct mm_struct *mm, phys_addr_t phys,
 			       pgprot_t prot, bool page_mappings_only);
 extern void *fixmap_remap_fdt(phys_addr_t dt_phys, int *size, pgprot_t prot);
 extern void mark_linear_text_alias_ro(void);
-extern int split_kernel_leaf_mapping(unsigned long start, unsigned long end);
 extern void linear_map_maybe_split_to_ptes(void);
 
 /*
@@ -104,7 +103,5 @@ void kpti_install_ng_mappings(void);
 static inline void kpti_install_ng_mappings(void) {}
 #endif
 
-extern bool page_alloc_available;
-
 #endif	/* !__ASSEMBLER__ */
 #endif
arch/arm64/include/asm/pageattr.h +5 -0
index 9634cb523298..2f8c16d39d23 100644
@@ -4,6 +4,11 @@
 
 #define cpa_is_direct_map(addr)	__is_lm_address(__tag_reset(addr))
 
+int arch_cpa_split_leaf(struct cpa_data *cpa, struct cpa_leaf *leaf,
+			void *table);
+bool arch_cpa_can_split(struct cpa_data *cpa, struct cpa_leaf *leaf);
+#define arch_cpa_can_split arch_cpa_can_split
+
 int arch_cpa_process_alias(struct cpa_data *cpa);
 #define arch_cpa_process_alias arch_cpa_process_alias
 
arch/arm64/mm/init.c +0 -3
index 4e7682dfe366..84ba461861c5 100644
@@ -379,11 +379,8 @@ void __init arch_mm_preinit(void)
 	}
 }
 
-bool page_alloc_available __ro_after_init;
-
 void __init mem_init(void)
 {
-	page_alloc_available = true;
 	swiotlb_update_mem_attributes();
 }
 
arch/arm64/mm/mmu.c +39 -183

268 lines not on this page · raw message

arch/arm64/mm/pageattr.c +1 -21
index 14a791b8e645..a2f5266b77b2 100644
@@ -130,7 +130,6 @@ int arch_cpa_process_alias(struct cpa_data *cpa)
 	pteval_t prot = pgprot_val(cpa->mask_set) | pgprot_val(cpa->mask_clr);
 	unsigned long vaddr = cpa_addr(cpa, cpa->curpage);
 	struct cpa_data alias_cpa;
-	unsigned long alias;
 	int ret;
 
 	if (!rodata_full || !(prot & PTE_RDONLY))
@@ -140,14 +139,8 @@ int arch_cpa_process_alias(struct cpa_data *cpa)
 	if (cpa_is_direct_map(vaddr) || !pfn_valid(cpa->pfn))
 		return 0;
 
-	alias = (unsigned long)page_address(pfn_to_page(cpa->pfn));
-	ret = split_kernel_leaf_mapping(alias,
-					alias + cpa->numpages * PAGE_SIZE);
-	if (WARN_ON_ONCE(ret))
-		return ret;
-
 	alias_cpa = *cpa;
-	alias_cpa.addr = alias;
+	alias_cpa.addr = (unsigned long)page_address(pfn_to_page(cpa->pfn));
 	pgprot_val(alias_cpa.mask_set) &= PTE_RDONLY | PTE_WRITE;
 	pgprot_val(alias_cpa.mask_clr) &= PTE_RDONLY | PTE_WRITE;
 
@@ -181,19 +174,11 @@ static const struct cpa_op_prot cpa_ops[CPA_OP_NR] = {
 
 int arch_cpa_prepare(struct cpa_data *cpa, enum cpa_op op)
 {
-	unsigned long start = PAGE_ALIGN_DOWN(cpa->addr);
-	unsigned long end = start + cpa->numpages * PAGE_SIZE;
-	int ret;
-
 	/* Nothing in the linear map is invalid without can_set_direct_map() */
 	if ((op == CPA_OP_DIRECT_MAP_INVALID ||
 	     op == CPA_OP_DIRECT_MAP_DEFAULT) && !can_set_direct_map())
 		return 0;
 
-	ret = split_kernel_leaf_mapping(start, end);
-	if (WARN_ON_ONCE(ret))
-		return ret;
-
 	cpa_init_op(cpa, &cpa_ops[op]);
 
 	/*
@@ -297,11 +282,6 @@ static int __change_memory_common(unsigned long start, unsigned long size,
 		.mask_clr = clear_mask,
 		.flags = CPA_REQ_NO_CHECK_ALIAS,
 	};
-	int ret;
-
-	ret = split_kernel_leaf_mapping(start, start + size);
-	if (WARN_ON_ONCE(ret))
-		return ret;
 
 	return arm64_change_page_attr(&cpa);
 }
Signature · 1 line
2.53.0
#52 lore raw

RFC PATCH v2 52/54 arm64: count the mappings of the linear map

In reply to Mike Rapoport (Microsoft)

The core keeps a counter of the direct map entries at every page table level. A split moves an entry to the level below and counts a direct_map_level2_splits or direct_map_level3_splits event in /proc/vmstat. The counters start from what the architecture mapped.

arm64 never counts its linear map, so the core finds no large pages to take a split from, and the split events stay at zero.

Count the linear map when it is created at boot and on memory hotplug, and when memory is removed. map_mem() maps the kernel alias and the KFENCE pool before it maps all of memory over them, so only the entries that were empty count. The split of the linear map at boot, when not all CPUs support BBML3, bypasses the core, so count its splits as well.

Report the counters in /proc/meminfo.

---
 arch/arm64/mm/mmu.c      | 28 ++++++++++++++++++++++++++++
 arch/arm64/mm/pageattr.c | 13 +++++++++++++
 2 files changed, 41 insertions(+)
arch/arm64/mm/mmu.c +28 -0
index 40c5ac95f574..c415b81fb6f3 100644
@@ -160,9 +160,19 @@ static void init_clear_pgtable(void *table)
 	dsb(ishst);
 }
 
+static void linear_map_count(unsigned long addr, enum pgtable_level level,
+			     long nr)
+{
+	if (__is_lm_address(addr))
+		direct_map_count_update(level, nr);
+}
+
 static void init_pte(pte_t *ptep, unsigned long addr, unsigned long end,
 		     phys_addr_t phys, pgprot_t prot)
 {
+	unsigned long start = addr;
+	long nr = 0;
+
 	do {
 		pte_t old_pte = __ptep_get(ptep);
 
@@ -179,8 +189,12 @@ static void init_pte(pte_t *ptep, unsigned long addr, unsigned long end,
 		BUG_ON(!pgattr_change_is_safe(pte_val(old_pte),
 					      pte_val(__ptep_get(ptep))));
 
+		if (pte_none(old_pte))
+			nr++;
 		phys += PAGE_SIZE;
 	} while (ptep++, addr += PAGE_SIZE, addr != end);
+
+	linear_map_count(start, PGTABLE_LEVEL_PTE, nr);
 }
 
 static bool pte_range_has_valid_noncont(pte_t *ptep)
@@ -274,6 +288,9 @@ static int init_pmd(pmd_t *pmdp, unsigned long addr, unsigned long end,
 			 */
 			BUG_ON(!pgattr_change_is_safe(pmd_val(old_pmd),
 						      READ_ONCE(pmd_val(*pmdp))));
+
+			if (pmd_none(old_pmd))
+				linear_map_count(addr, PGTABLE_LEVEL_PMD, 1);
 		} else {
 			int ret;
 
@@ -410,6 +427,9 @@ static int alloc_init_pud(p4d_t *p4dp, unsigned long addr, unsigned long end,
 			 */
 			BUG_ON(!pgattr_change_is_safe(pud_val(old_pud),
 						      READ_ONCE(pud_val(*pudp))));
+
+			if (pud_none(old_pud))
+				linear_map_count(addr, PGTABLE_LEVEL_PUD, 1);
 		} else {
 			ret = alloc_init_cont_pmd(pudp, addr, next, phys, prot,
 						  pgtable_alloc, flags);
@@ -750,6 +770,7 @@ static int split_to_ptes_pud_entry(pud_t *pudp, unsigned long addr,
 		return -ENOMEM;
 
 	split_pud(pudp, pud, pmdp, false);
+	direct_map_count_split(PGTABLE_LEVEL_PUD);
 
 	return 0;
 }
@@ -771,6 +792,7 @@ static int split_to_ptes_pmd_entry(pmd_t *pmdp, unsigned long addr,
 	if (pmd_cont(pmd))
 		split_contpmd(pmdp);
 	split_pmd(pmdp, pmd, ptep, false);
+	direct_map_count_split(PGTABLE_LEVEL_PMD);
 
 	/*
 	 * We have split the pmd directly to ptes so there is no need to
@@ -1424,6 +1446,8 @@ static void unmap_hotplug_pte_range(pmd_t *pmdp, unsigned long addr,
 			flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
 			free_hotplug_page_range(pte_page(pte),
 						PAGE_SIZE, altmap);
+		} else {
+			direct_map_count_update(PGTABLE_LEVEL_PTE, -1);
 		}
 		/* unmap_hotplug_range() flushes TLB for !free_mapped */
 	} while (addr += PAGE_SIZE, addr < end);
@@ -1458,6 +1482,8 @@ static void unmap_hotplug_pmd_range(pud_t *pudp, unsigned long addr,
 				flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
 				free_hotplug_page_range(pmd_page(pmd),
 							PMD_SIZE, altmap);
+			} else {
+				direct_map_count_update(PGTABLE_LEVEL_PMD, -1);
 			}
 			/* unmap_hotplug_range() flushes TLB for !free_mapped */
 			continue;
@@ -1489,6 +1515,8 @@ static void unmap_hotplug_pud_range(p4d_t *p4dp, unsigned long addr,
 				flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
 				free_hotplug_page_range(pud_page(pud),
 							PUD_SIZE, altmap);
+			} else {
+				direct_map_count_update(PGTABLE_LEVEL_PUD, -1);
 			}
 			/* unmap_hotplug_range() flushes TLB for !free_mapped */
 			continue;
arch/arm64/mm/pageattr.c +13 -0
index a2f5266b77b2..5e6782ef4b6c 100644
@@ -9,6 +9,7 @@
 #include <linux/sched.h>
 #include <linux/vmalloc.h>
 #include <linux/pageattr.h>
+#include <linux/proc_fs.h>
 
 #include <asm/cacheflush.h>
 #include <asm/pgtable-prot.h>
@@ -16,6 +17,18 @@
 #include <asm/tlbflush.h>
 #include <asm/kfence.h>
 
+#ifdef CONFIG_PROC_FS
+void arch_report_meminfo(struct seq_file *m)
+{
+	unsigned long levels = BIT(PGTABLE_LEVEL_PTE) | BIT(PGTABLE_LEVEL_PMD);
+
+	if (pud_sect_supported())
+		levels |= BIT(PGTABLE_LEVEL_PUD);
+
+	cpa_report_meminfo(m, levels);
+}
+#endif
+
 void arch_cpa_decode_leaf(struct cpa_leaf *leaf)
 {
 	enum pgtable_level level = leaf->level;
Signature · 1 line
2.53.0
#53 lore raw

RFC PATCH v2 53/54 arch, mm: enable the generic CPA core with ARCH_HAS_SET_MEMORY

In reply to Mike Rapoport (Microsoft)

Every architecture that selects ARCH_HAS_SET_MEMORY now uses the generic CPA core, and a new one should not need to select two symbols to get it.

Enable GENERIC_PAGEATTR for ARCH_HAS_SET_MEMORY on MMU kernels and drop the selects from the architectures.

---
 arch/arm/Kconfig       | 1 -
 arch/arm64/Kconfig     | 1 -
 arch/loongarch/Kconfig | 1 -
 arch/powerpc/Kconfig   | 1 -
 arch/riscv/Kconfig     | 1 -
 arch/s390/Kconfig      | 1 -
 arch/x86/Kconfig       | 1 -
 mm/Kconfig             | 2 +-
 8 files changed, 1 insertion(+), 8 deletions(-)
arch/arm/Kconfig +0 -1
index 7a7ccc113126..0cc289a7184a 100644
@@ -77,7 +77,6 @@ config ARM
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
-	select GENERIC_PAGEATTR if MMU
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/arm64/Kconfig +0 -1
index 846fae788b3c..9b08b2457a55 100644
@@ -138,7 +138,6 @@ config ARM64
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
-	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/loongarch/Kconfig +0 -1
index 455a72b8669d..bad699e2847f 100644
@@ -107,7 +107,6 @@ config LOONGARCH
 	select GENERIC_LIB_LSHRDI3
 	select GENERIC_LIB_UCMPDI2
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
-	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
 	select GENERIC_SMP_IDLE_THREAD
arch/powerpc/Kconfig +0 -1
index fbe3a3abeea8..c3b6cd655606 100644
@@ -211,7 +211,6 @@ config PPC
 	select GENERIC_IOREMAP
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
-	select GENERIC_PAGEATTR
 	select GENERIC_PCI_IOMAP		if PCI
 	select GENERIC_SMP_IDLE_THREAD
 	select HAS_IOPORT			if PCI
arch/riscv/Kconfig +0 -1
index 0453c665fc64..e7891a2a89da 100644
@@ -122,7 +122,6 @@ config RISCV
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
 	select GENERIC_LIB_DEVMEM_IS_ALLOWED
-	select GENERIC_PAGEATTR if MMU
 	select GENERIC_PENDING_IRQ if SMP
 	select GENERIC_PCI_IOMAP
 	select GENERIC_SCHED_CLOCK
arch/s390/Kconfig +0 -1
index 413b886a9e9a..7138d923d86f 100644
@@ -180,7 +180,6 @@ config S390
 	select GENERIC_CPU_VULNERABILITIES
 	select GENERIC_ENTRY
 	select GENERIC_GETTIMEOFDAY
-	select GENERIC_PAGEATTR
 	select GENERIC_SMP_IDLE_THREAD
 	select GENERIC_IOREMAP
 	select GLOB
arch/x86/Kconfig +0 -1
index f4aceaceaf65..6cf8f121879a 100644
@@ -178,7 +178,6 @@ config X86
 	select GENERIC_IRQ_PROBE
 	select GENERIC_IRQ_RESERVATION_MODE
 	select GENERIC_IRQ_SHOW
-	select GENERIC_PAGEATTR
 	select GENERIC_PENDING_IRQ		if SMP
 	select GENERIC_SMP_IDLE_THREAD
 	select GENERIC_GETTIMEOFDAY
mm/Kconfig +1 -1
index 3948e64dc590..97e152442e1a 100644
@@ -1139,7 +1139,7 @@ config GENERIC_EARLY_IOREMAP
 	bool
 
 config GENERIC_PAGEATTR
-	bool
+	def_bool ARCH_HAS_SET_MEMORY && MMU
 
 config STACK_MAX_DEFAULT_SIZE_MB
 	int "Default maximum user stack size for 32-bit processes (MB)"
Signature · 1 line
2.53.0
#54 lore raw

RFC PATCH v2 54/54 mm/pageattr: document CPA core and the architecture hooks

In reply to Mike Rapoport (Microsoft)

Add kernel-doc for the API and the hooks in include/linux/pageattr.h.

---
 include/linux/pageattr.h | 277 ++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 275 insertions(+), 2 deletions(-)
include/linux/pageattr.h +275 -2
index a2a7235a633e..855c65295f6e 100644
@@ -5,10 +5,69 @@
 #include <linux/mm.h>
 #include <linux/pgtable.h>
 
+/**
+ * DOC: Kernel Page Table Protection Modifications
+ *
+ * There are two families of APIs that allow modifying the protection of the
+ * kernel mappings:
+ *
+ * set_memory_*() change the protection of an arbitrary kernel mapping.
+ *
+ * set_direct_map_*() change the protection of the direct/identity/linear
+ * mapping.
+ *
+ * change_page_attr() and change_page_attr_noflush(), or CPA for short,
+ * implement the generic part of these APIs and leave the page table
+ * specifics to the architecture.
+ *
+ * CPA walks the kernel page tables, determines at what level the
+ * protection change must be done, splits large mappings if necessary and
+ * updates the protection of the requested range.
+ *
+ * CPA keeps the mappings as large as it can. A large page stays intact
+ * when a request changes all of it the same way, and is split only when a
+ * request changes a part of it.
+ *
+ * The same holds for a contiguous block of entries that the TLB may cache as
+ * one translation, like, for example, the contiguous bit of arm64.
+ *
+ * CPA keeps the alias mappings of the memory consistent: when the protection
+ * of a page changes, its other mappings, like the direct map, change with it
+ * according to architecture requirements.
+ *
+ * Every step of a request looks up and changes the page tables under
+ * cpa_lock. It keeps concurrent requests from splitting or changing the same
+ * large mapping at the same time, and a collapse, which holds it as well,
+ * from freeing page tables under a CPA lookup. A step drops cpa_lock to
+ * allocate a page table for a split and repeats the lookup after retaking the
+ * lock.
+ *
+ * Page table walkers that don't take cpa_lock, like ptdump and text poking,
+ * rely on the init_mm mmap lock instead. A collapse frees page tables, so it
+ * holds that lock for writing.
+ *
+ * The architecture describes its page tables with the hooks below: the format
+ * of a page table entry, how a large page is split and whether it can be split
+ * at all, which mappings are aliases and how the TLB is flushed.
+ *
+ * The hooks that have a default are optional.
+ */
+
 struct seq_file;
 
-/*
- * The current flushing context - we pass it instead of 5 arguments:
+/**
+ * struct cpa_data - a request to change the protection of kernel mappings
+ * @addr: the virtual address of the first page
+ * @pgd: the page tables to change, NULL for init_mm
+ * @mask_set: the protection bits to set, in the architecture's PTE format
+ * @mask_clr: the protection bits to clear, in the architecture's PTE format
+ * @numpages: the number of pages; while the walk runs, the number of pages
+ *	of the current step
+ * @curpage: the index of the first page of the current step
+ * @pfn: the pfn of the first page of the current step; for an architecture
+ *	that populates holes, the caller sets it to the first pfn to map
+ * @flags: CPA_REQ_* request flags set by the caller
+ * @state: CPA_ST_* state flags set by change_page_attr()
  */
 struct cpa_data {
 	unsigned long	addr;
@@ -22,6 +81,18 @@ struct cpa_data {
 	unsigned int	state;
 };
 
+/**
+ * struct cpa_leaf - a mapping found by the lookup
+ * @kpte: the page table entry corresponding to @addr or the first entry in a
+ *	contiguous block
+ * @level: the level at which the lookup found the mapping
+ * @addr: the first virtual address of the mapping
+ * @size: the size of the mapping: the size of @level, or of the contiguous
+ *	block
+ * @pfn: the first pfn of the mapping
+ * @prot: the protection of the mapping in the architecture's PTE format, as
+ *	decoded by arch_cpa_decode_leaf()
+ */
 struct cpa_leaf {
 	pte_t			*kpte;
 	enum pgtable_level	level;
@@ -63,14 +134,46 @@ static inline unsigned long cpa_addr(struct cpa_data *cpa, unsigned long idx)
 	return cpa->addr + idx * PAGE_SIZE;
 }
 
+/* Helpers for the hooks */
 int cpa_process_fault(struct cpa_data *cpa);
 int cpa_change_alias(struct cpa_data *cpa, struct cpa_data *alias);
 void cpa_flush_tlb_kernel_range(struct cpa_data *cpa);
 
+/**
+ * change_page_attr() - change the protection of kernel mappings and flush the
+ *	TLB
+ * @cpa: the request
+ *
+ * Unmaps the unused kmap and the lazily freed vmap aliases first, as they
+ * may map the pages with the old protection. With CPA_REQ_COLLAPSE, also
+ * collapses large pages after the flush.
+ *
+ * On failure, the pages processed before it keep their new protection, and
+ * arch_cpa_flush() is called with CPA_ST_FLUSH_ALL if any of them changed.
+ *
+ * Context: May sleep.
+ * Return: 0 on success, -errno on failure.
+ */
 int change_page_attr(struct cpa_data *cpa);
 
+/**
+ * change_page_attr_noflush() - change the protection of kernel mappings
+ * @cpa: the request
+ *
+ * Unlike change_page_attr(), it doesn't unmap the kmap and vmap aliases of
+ * the pages, and the caller is responsible for flushing the TLB.
+ *
+ * Context: May sleep to allocate a page table for a split.
+ * Return: 0 on success, -errno on failure.
+ */
 int change_page_attr_noflush(struct cpa_data *cpa);
 
+/*
+ * The direct map counters behind the DirectMap lines of /proc/meminfo.
+ * change_page_attr() counts the large pages of the direct map it splits,
+ * and the architecture counts every other change of its direct map. The
+ * architecture prints the counters with cpa_report_meminfo().
+ */
 #ifdef CONFIG_PROC_FS
 void direct_map_count_update(enum pgtable_level level, long pages);
 void direct_map_count_split(enum pgtable_level level);
@@ -83,12 +186,60 @@ static inline void direct_map_count_split(enum pgtable_level level) { }
 static inline void direct_map_count_collapse(enum pgtable_level level) { }
 #endif
 
+/**
+ * arch_cpa_decode_leaf() - decode a page table entry
+ * @leaf: the mapping to decode
+ *
+ * Fill @leaf->pfn and @leaf->prot from the entry @leaf->kpte at @leaf->level.
+ * If the entry is a part of a contiguous block, extend @leaf to the block.
+ *
+ * @leaf->prot has the same format at every level: the PTE format, without
+ * the pfn and without the bits that tell a large entry from a small one.
+ * arch_cpa_modify_leaf() converts it back. The entry may be not present,
+ * but it is never empty.
+ *
+ * Context: cpa_lock held, must not sleep.
+ */
 void arch_cpa_decode_leaf(struct cpa_leaf *leaf);
 
+/**
+ * arch_cpa_modify_leaf() - change the protection of a mapping
+ * @leaf: the mapping to change
+ * @prot: the new protection
+ *
+ * Store the entry of @leaf, or every entry of its contiguous block, with
+ * @prot. The TLB is flushed after the walk, by arch_cpa_flush() or by the
+ * caller of change_page_attr_noflush().
+ * An architecture whose TLB may cache an entry that is not valid handles an
+ * entry that becomes valid here.
+ *
+ * Context: cpa_lock held, must not sleep.
+ */
 void arch_cpa_modify_leaf(struct cpa_leaf *leaf, pgprot_t prot);
 
+/**
+ * arch_cpa_flush() - flush the TLB for the pages of a request
+ * @cpa: the request
+ *
+ * CPA_ST_FLUSH_ALL in @cpa->state means an alias of the pages changed as
+ * well, or the request failed.
+ * An architecture without aliases, one that flushes the aliases in
+ * arch_cpa_process_alias(), or one whose page table updates flush the TLB by
+ * themselves may ignore it.
+ */
 void arch_cpa_flush(struct cpa_data *cpa);
 
+/**
+ * arch_cpa_new_prot() - adjust the protections calculated in cpa_req_prot()
+ * with architecture constraints
+ * @cpa: the request
+ * @leaf: the mapping to change
+ *
+ * A large page is split when the result differs from cpa_req_prot().
+ *
+ * Context: cpa_lock held, must not sleep.
+ * Return: the new protection of @leaf.
+ */
 #ifndef arch_cpa_new_prot
 static inline pgprot_t arch_cpa_new_prot(struct cpa_data *cpa,
 					 struct cpa_leaf *leaf)
@@ -98,12 +249,42 @@ static inline pgprot_t arch_cpa_new_prot(struct cpa_data *cpa,
 #endif
 
 #ifndef arch_cpa_can_split
+/**
+ * arch_cpa_can_split() - check if a large page can be split
+ * @cpa: the request
+ * @leaf: the large page
+ *
+ * Refuse a split before a page table is allocated for it. A request that
+ * needs a split the architecture cannot do fails with a warning and
+ * -EINVAL. The default refuses every split.
+ *
+ * An architecture must override both arch_cpa_can_split() and
+ * arch_cpa_split_leaf() or none.
+ *
+ * Context: cpa_lock held, must not sleep.
+ * Return: true if arch_cpa_split_leaf() can split @leaf.
+ */
 static inline bool arch_cpa_can_split(struct cpa_data *cpa,
 				      struct cpa_leaf *leaf)
 {
 	return false;
 }
 
+/**
+ * arch_cpa_split_leaf() - split a large page
+ * @cpa: the request
+ * @leaf: the large page
+ * @table: the page table page from arch_cpa_alloc_pgtable(), NULL for a
+ *	contiguous block
+ *
+ * Replace @leaf with @table, filled with entries that map the same memory
+ * with the same protection. A contiguous block is split by making each of
+ * its entries a mapping of its own.
+ * In both cases, do the TLB maintenance the CPU requires for the change.
+ *
+ * Context: cpa_lock held, must not sleep.
+ * Return: 0 on success, -errno on failure.
+ */
 static inline int arch_cpa_split_leaf(struct cpa_data *cpa,
 				      struct cpa_leaf *leaf, void *table)
 {
@@ -112,11 +293,35 @@ static inline int arch_cpa_split_leaf(struct cpa_data *cpa,
 #endif
 
 #ifndef arch_cpa_alloc_pgtable
+/**
+ * arch_cpa_alloc_pgtable() - allocate the page table for a split
+ * @leaf: the large page to split
+ *
+ * An architecture must override both arch_cpa_alloc_pgtable() and
+ * arch_cpa_free_pgtable() or none.
+ *
+ * Context: May sleep.
+ * Return: the page table, NULL on failure.
+ */
 void *arch_cpa_alloc_pgtable(struct cpa_leaf *leaf);
 
+/**
+ * arch_cpa_free_pgtable() - free a page table from arch_cpa_alloc_pgtable()
+ * @leaf: the large page the table was allocated for
+ * @table: the page table
+ *
+ * Context: cpa_lock held, must not sleep.
+ */
 void arch_cpa_free_pgtable(struct cpa_leaf *leaf, void *table);
 #endif
 
+/**
+ * cpa_is_direct_map() - check if an address is in the direct map
+ * @addr: the virtual address
+ *
+ * Return: true if @addr is in the range of the direct map, which may have
+ * holes.
+ */
 #ifndef cpa_is_direct_map
 static inline bool cpa_is_direct_map(unsigned long addr)
 {
@@ -124,6 +329,22 @@ static inline bool cpa_is_direct_map(unsigned long addr)
 }
 #endif
 
+/**
+ * arch_cpa_process_fault() - handle a page without a mapping
+ * @cpa: the request, its current page has no mapping
+ *
+ * On entry @cpa->numpages is the number of pages left in the request, and
+ * @cpa->pfn is the pfn of the previous step, or the one the caller set. To
+ * skip pages, set @cpa->numpages to their number and return 0. Without
+ * CPA_ST_ALIAS in @cpa->state, also set @cpa->pfn to the pfn of the first
+ * skipped page, which arch_cpa_process_alias() uses next.
+ *
+ * The default skips a page of an alias and a page in a hole of the direct
+ * map, and fails with a warning for any other address.
+ *
+ * Context: cpa_lock held, must not sleep.
+ * Return: 0 to continue the walk, -errno to fail the request.
+ */
 #ifndef arch_cpa_process_fault
 static inline int arch_cpa_process_fault(struct cpa_data *cpa)
 {
@@ -131,6 +352,19 @@ static inline int arch_cpa_process_fault(struct cpa_data *cpa)
 }
 #endif
 
+/**
+ * arch_cpa_process_alias() - change the aliases of the current pages
+ * @cpa: the request
+ *
+ * Change the aliases of the @cpa->numpages pages at @cpa->pfn that the
+ * current step of the walk processed. Each alias is changed with
+ * cpa_change_alias() on a copy of @cpa with the address and the masks of
+ * the alias. cpa_change_alias() sets CPA_ST_FLUSH_ALL in @cpa when the
+ * alias changed; an architecture may flush the alias here instead.
+ *
+ * Context: May sleep to split the large pages of an alias.
+ * Return: 0 on success, -errno on failure.
+ */
 #ifndef arch_cpa_process_alias
 static inline int arch_cpa_process_alias(struct cpa_data *cpa)
 {
@@ -138,12 +372,23 @@ static inline int arch_cpa_process_alias(struct cpa_data *cpa)
 }
 #endif
 
+/**
+ * arch_cpa_collapse() - collapse the large pages of a request
+ * @cpa: the request
+ *
+ * Replace the page tables of the range of a CPA_REQ_COLLAPSE request with
+ * large pages where all their entries map contiguous memory with the same
+ * protection. The TLB is already flushed for the request.
+ *
+ * Context: init_mm write locked, cpa_lock held, must not sleep.
+ */
 #ifndef arch_cpa_collapse
 static inline void arch_cpa_collapse(struct cpa_data *cpa)
 {
 }
 #endif
 
+/* The operations of set_memory_*() and set_direct_map_*_noflush() */
 enum cpa_op {
 	CPA_OP_RO,
 	CPA_OP_RW,
@@ -155,6 +400,12 @@ enum cpa_op {
 	CPA_OP_NR
 };
 
+/**
+ * struct cpa_op_prot - the masks and flags of an operation
+ * @set: the protection bits to set, in the architecture's PTE format
+ * @clr: the protection bits to clear, in the architecture's PTE format
+ * @req: CPA_REQ_* flags of the request
+ */
 struct cpa_op_prot {
 	pgprot_t	set;
 	pgprot_t	clr;
@@ -169,15 +420,37 @@ static inline void cpa_init_op(struct cpa_data *cpa,
 	cpa->flags |= prot->req;
 }
 
+/**
+ * arch_cpa_prepare() - prepare the request of an operation
+ * @cpa: the request with the address and the number of pages
+ * @op: the operation
+ *
+ * Fill the masks and the flags of @cpa for @op, usually with cpa_init_op()
+ * from a table of the operations. A request with empty masks succeeds
+ * without changing anything.
+ *
+ * Return: 0 on success, -errno to refuse the request.
+ */
 int arch_cpa_prepare(struct cpa_data *cpa, enum cpa_op op);
 
 #ifndef arch_cpa_enter
+/**
+ * arch_cpa_enter() - start the request of an operation
+ *
+ * Together with arch_cpa_leave() it brackets the request of set_memory_*() and
+ * set_direct_map_*_noflush(), so that an architecture can batch the page table
+ * updates of the request, for example in lazy MMU mode. The request may sleep.
+ * A direct call of change_page_attr() is not bracketed.
+ */
 static inline void arch_cpa_enter(void)
 {
 }
 #endif
 
 #ifndef arch_cpa_leave
+/**
+ * arch_cpa_leave() - end the request of an operation
+ */
 static inline void arch_cpa_leave(void)
 {
 }
Signature · 1 line
2.53.0