Skip to contentSkip to conversation

riscv: Memory type control for platforms with physical memory aliases

PATCH In review Samuel Holland 13 participants 73 messages Nov 13, 2025 – Apr 30

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

v3 cover riscv: Memory type control for platforms with physical memory aliases

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

These physical memory aliases are only visible to architecture code. Generic MM code only ever sees the primary (cacheable) alias. The major change from v1 of this series is that I was asked to move the hooks from pfn_pXX()/pXX_pfn() to set_pXX()/pXXp_get().

- Patches 1-10 ensure that architecture-specific code that hooks page table reads and writes is always called, and the calls are balanced.
- Patches 11-14 refactor existing platform-specific memory type support to be modeled as variants on top of the standard Svpbmt extension, and apply the memory type transformation during PTE reads/writes.
- Patches 15-20 add a new DT binding to describe physical memory regions, and implement a new memory type variant that transforms the PFN to use the desired alias when reading/writing page tables.
- Patches 21-22 enable this new memory type variant on StarFive JH7100 and ESWIN EIC7700.

I have boot-tested this series and tested DMA on SoCs with each of the four ways to select a memory type: SiFive FU740 (none), SiFive P470-based SoC (Svpbmt), Allwinner D1 (XTheadMae), StarFive JH7100 (aliases), and ESWIN EIC7700 (aliases).

Here is some basic perf benchmark data comparing relative performance between v6.17 and either the generic MM changes or the whole series:

Test | Scenario | FU740 | P470 | D1 | EIC7700
=============================================================

 syscall     | patch 1-10 | +3.17% | +0.89% | +2.60% |  +0.68%
   basic     |     series | -2.52% | -1.41% | +1.37% |  -0.64%
 -------------------------------------------------------------
 syscall     | patch 1-10 | +0.17% | -0.57% | +2.79% |  -1.12%
   fork      |     series | -1.31% | -5.91% | -1.50% |  -2.73%
 -------------------------------------------------------------
 syscall     | patch 1-10 | -0.24% | -0.30% | +2.76% |  +1.32%
   execve    |     series | -1.65% | -4.82% | -1.38% |  -0.66%
 -------------------------------------------------------------
 sched       | patch 1-10 | +1.54% | -5.76% | -5.09% |  -1.04%
   messaging |     series | +0.66% | +2.00% | +1.40% |  +1.97%

-------------------------------------------------------------

The benchmark results are stable within each machine, and the same binary was used on all machines. I would have expected the preparatory changes (patch 1-10) to hurt performance somewhat, due to READ_ONCE/ WRITE_ONCE generating additional loads/stores, but surprisingly performance was improved in some cases. The variation across machines in response to the entire series is expected, as each of these machines gets a different version of the alternative block.

Changes in v3:
- Use upstream commit/patch for Anshuman Khandual's changes
- Rebased on top of torvalds/master (v6.18-rc5+)
- Add a checkpatch rule to warn on page table pointer dereference
- Select DMA_DIRECT_REMAP when any memory type extension is enabled
- Split PMR_IS_ALIAS flag from PMR_ALIAS_MASK number
- Add "model" property to DT binding example to fix validation
- Fix the logic to allow an alias to be paired with region entry 0
- Fix the entry number of the paired region in the DT
- Keep the ERRATA_STARFIVE_JH7100 option but update its description
- CC all core MM reviewers

Changes in v2:
- Keep Kconfig options for each PBMT variant separate/non-overlapping
- Move fixup code sequences to set_pXX() and pXXp_get()
- Only define ALT_UNFIX_MT in configurations that need it
- Improve inline documentation of ALT_FIXUP_MT/ALT_UNFIX_MT
- Fix erroneously-escaped newline in assembly ALTERNATIVE_CFG_3 macro
- Remove references to Physical Address Width (no longer part of Smmpt)
- Remove special first entry from the list of physical memory regions
- Fix compatible string in DT binding example
- Put new code behind a new Kconfig option RISCV_ISA_XLINUXMEMALIAS
- Document the calling convention of riscv_fixup/unfix_memory_alias()
- Do not transform !pte_present() (e.g. swap) PTEs
- Export riscv_fixup/unfix_memory_alias() to fix module compilation
- Move the JH7100 DT changes from jh7100-common.dtsi to jh7100.dtsi
- Keep RISCV_DMA_NONCOHERENT and RISCV_NONSTANDARD_CACHE_OPS selected

Anshuman Khandual (4):
mm/ptdump: replace READ_ONCE() with standard page table accessors
mm: replace READ_ONCE() with standard page table accessors mm/dirty: replace READ_ONCE() with pudp_get() perf/events: replace READ_ONCE() with standard page table accessors

Samuel Holland (18):
mm: Move the fallback definitions of pXXp_get()
mm: Always use page table accessor functions
checkpatch: Warn on page table access without accessors
mm: Allow page table accessors to be non-idempotent
riscv: hibernate: Replace open-coded pXXp_get()
riscv: mm: Always use page table accessor functions
riscv: mm: Simplify set_p4d() and set_pgd()
riscv: mm: Deduplicate _PAGE_CHG_MASK definition
riscv: ptdump: Only show N and MT bits when enabled in the kernel
riscv: mm: Fix up memory types when writing page tables
riscv: mm: Expose all page table bits to assembly code
riscv: alternative: Add an ALTERNATIVE_3 macro
riscv: alternative: Allow calls with alternate link registers
riscv: Fix logic for selecting DMA_DIRECT_REMAP
dt-bindings: riscv: Describe physical memory regions
riscv: mm: Use physical memory aliases to apply PMAs
riscv: dts: starfive: jh7100: Use physical memory ranges for DMA
riscv: dts: eswin: eic7700: Use physical memory ranges for DMA

 .../bindings/riscv/physical-memory.yaml       |  92 +++++++
 arch/riscv/Kconfig                            |  19 +-
 arch/riscv/Kconfig.errata                     |  11 +-
 arch/riscv/Kconfig.socs                       |   4 +
 arch/riscv/boot/dts/eswin/eic7700.dtsi        |   5 +
 .../boot/dts/starfive/jh7100-common.dtsi      |  24 --
 arch/riscv/boot/dts/starfive/jh7100.dtsi      |   4 +
 arch/riscv/include/asm/alternative-macros.h   |  45 +++-
 arch/riscv/include/asm/errata_list.h          |  45 ----
 arch/riscv/include/asm/hwcap.h                |   1 +
 arch/riscv/include/asm/pgtable-32.h           |  17 +-
 arch/riscv/include/asm/pgtable-64.h           | 228 +++++++++++++-----
 arch/riscv/include/asm/pgtable-bits.h         |  43 +++-
 arch/riscv/include/asm/pgtable.h              |  67 ++---
 arch/riscv/kernel/alternative.c               |   4 +-
 arch/riscv/kernel/cpufeature.c                |   6 +
 arch/riscv/kernel/hibernate.c                 |  18 +-
 arch/riscv/kernel/setup.c                     |   1 +
 arch/riscv/kvm/gstage.c                       |   6 +-
 arch/riscv/mm/Makefile                        |   1 +
 arch/riscv/mm/init.c                          |  68 +++---
 arch/riscv/mm/memory-alias.S                  | 123 ++++++++++
 arch/riscv/mm/pgtable.c                       | 114 +++++++--
 arch/riscv/mm/ptdump.c                        |  16 +-
 fs/dax.c                                      |   4 +-
 fs/proc/task_mmu.c                            |  27 ++-
 fs/userfaultfd.c                              |   6 +-
 include/dt-bindings/riscv/physical-memory.h   |  45 ++++
 include/linux/huge_mm.h                       |   8 +-
 include/linux/mm.h                            |  14 +-
 include/linux/pgtable.h                       | 112 ++++-----
 kernel/events/core.c                          |   8 +-
 mm/damon/vaddr.c                              |   2 +-
 mm/debug_vm_pgtable.c                         |   4 +-
 mm/filemap.c                                  |   6 +-
 mm/gup.c                                      |  37 +--
 mm/hmm.c                                      |   2 +-
 mm/huge_memory.c                              |  90 +++----
 mm/hugetlb.c                                  |  10 +-
 mm/hugetlb_vmemmap.c                          |   4 +-
 mm/kasan/init.c                               |  39 +--
 mm/kasan/shadow.c                             |  12 +-
 mm/khugepaged.c                               |  10 +-
 mm/ksm.c                                      |   2 +-
 mm/madvise.c                                  |   8 +-
 mm/mapping_dirty_helpers.c                    |   2 +-
 mm/memory-failure.c                           |  14 +-
 mm/memory.c                                   |  80 +++---
 mm/mempolicy.c                                |   4 +-
 mm/migrate.c                                  |   4 +-
 mm/migrate_device.c                           |  10 +-
 mm/mlock.c                                    |   6 +-
 mm/mprotect.c                                 |   4 +-
 mm/mremap.c                                   |  30 +--
 mm/page_table_check.c                         |   7 +-
 mm/page_vma_mapped.c                          |   6 +-
 mm/pagewalk.c                                 |  14 +-
 mm/percpu.c                                   |   8 +-
 mm/pgalloc-track.h                            |   8 +-
 mm/pgtable-generic.c                          |  25 +-
 mm/ptdump.c                                   |  10 +-
 mm/rmap.c                                     |   8 +-
 mm/sparse-vmemmap.c                           |  10 +-
 mm/userfaultfd.c                              |  10 +-
 mm/vmalloc.c                                  |  49 ++--
 mm/vmscan.c                                   |  16 +-
 scripts/checkpatch.pl                         |   7 +
 67 files changed, 1129 insertions(+), 615 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/riscv/physical-memory.yaml
 create mode 100644 arch/riscv/mm/memory-alias.S
 create mode 100644 include/dt-bindings/riscv/physical-memory.h
Signature · 4 lines
2.47.2

base-commit: 24172e0d79900908cf5ebf366600616d29c9b417
branch: up/dma-alias
#1 lore raw

PATCH v3 1/22 mm/ptdump: replace READ_ONCE() with standard page table accessors

From: Anshuman Khandual <[email protected]>

Replace READ_ONCE() with standard page table accessors i.e pxdp_get() which anyways default into READ_ONCE() in cases where platform does not override. Also convert ptep_get_lockless() into ptep_get() as well.

---

Changes in v3:
- Replace patch with cherry-pick from linux-next

Changes in v2:
- New patch for v2 (taken from LKML)

 mm/ptdump.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
mm/ptdump.c +5 -5
index b600c7f864b8..973020000096 100644
@@ -31,7 +31,7 @@ static int ptdump_pgd_entry(pgd_t *pgd, unsigned long addr,
 			    unsigned long next, struct mm_walk *walk)
 {
 	struct ptdump_state *st = walk->private;
-	pgd_t val = READ_ONCE(*pgd);
+	pgd_t val = pgdp_get(pgd);
 
 #if CONFIG_PGTABLE_LEVELS > 4 && \
 		(defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS))
@@ -54,7 +54,7 @@ static int ptdump_p4d_entry(p4d_t *p4d, unsigned long addr,
 			    unsigned long next, struct mm_walk *walk)
 {
 	struct ptdump_state *st = walk->private;
-	p4d_t val = READ_ONCE(*p4d);
+	p4d_t val = p4dp_get(p4d);
 
 #if CONFIG_PGTABLE_LEVELS > 3 && \
 		(defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS))
@@ -77,7 +77,7 @@ static int ptdump_pud_entry(pud_t *pud, unsigned long addr,
 			    unsigned long next, struct mm_walk *walk)
 {
 	struct ptdump_state *st = walk->private;
-	pud_t val = READ_ONCE(*pud);
+	pud_t val = pudp_get(pud);
 
 #if CONFIG_PGTABLE_LEVELS > 2 && \
 		(defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS))
@@ -100,7 +100,7 @@ static int ptdump_pmd_entry(pmd_t *pmd, unsigned long addr,
 			    unsigned long next, struct mm_walk *walk)
 {
 	struct ptdump_state *st = walk->private;
-	pmd_t val = READ_ONCE(*pmd);
+	pmd_t val = pmdp_get(pmd);
 
 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
 	if (pmd_page(val) == virt_to_page(lm_alias(kasan_early_shadow_pte)))
@@ -121,7 +121,7 @@ static int ptdump_pte_entry(pte_t *pte, unsigned long addr,
 			    unsigned long next, struct mm_walk *walk)
 {
 	struct ptdump_state *st = walk->private;
-	pte_t val = ptep_get_lockless(pte);
+	pte_t val = ptep_get(pte);
 
 	if (st->effective_prot_pte)
 		st->effective_prot_pte(st, val);
Signature · 1 line
2.47.2
#2 lore raw

PATCH v3 2/22 mm: replace READ_ONCE() with standard page table accessors

In reply to Samuel Holland

From: Anshuman Khandual <[email protected]>

Replace all READ_ONCE() with a standard page table accessors i.e pxdp_get() that defaults into READ_ONCE() in cases where platform does not override.

---

Changes in v3:
- New patch for v3 (cherry-picked from linux-next)

 mm/gup.c            | 10 +++++-----
 mm/hmm.c            |  2 +-
 mm/memory.c         |  4 ++--
 mm/mprotect.c       |  2 +-
 mm/sparse-vmemmap.c |  2 +-
 mm/vmscan.c         |  2 +-
 6 files changed, 11 insertions(+), 11 deletions(-)
mm/gup.c +5 -5
index a8ba5112e4d0..b46112d36f7e 100644
@@ -950,7 +950,7 @@ static struct page *follow_pud_mask(struct vm_area_struct *vma,
 	struct mm_struct *mm = vma->vm_mm;
 
 	pudp = pud_offset(p4dp, address);
-	pud = READ_ONCE(*pudp);
+	pud = pudp_get(pudp);
 	if (!pud_present(pud))
 		return no_page_table(vma, flags, address);
 	if (pud_leaf(pud)) {
@@ -975,7 +975,7 @@ static struct page *follow_p4d_mask(struct vm_area_struct *vma,
 	p4d_t *p4dp, p4d;
 
 	p4dp = p4d_offset(pgdp, address);
-	p4d = READ_ONCE(*p4dp);
+	p4d = p4dp_get(p4dp);
 	BUILD_BUG_ON(p4d_leaf(p4d));
 
 	if (!p4d_present(p4d) || p4d_bad(p4d))
@@ -3060,7 +3060,7 @@ static int gup_fast_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr,
 
 	pudp = pud_offset_lockless(p4dp, p4d, addr);
 	do {
-		pud_t pud = READ_ONCE(*pudp);
+		pud_t pud = pudp_get(pudp);
 
 		next = pud_addr_end(addr, end);
 		if (unlikely(!pud_present(pud)))
@@ -3086,7 +3086,7 @@ static int gup_fast_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr,
 
 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
 	do {
-		p4d_t p4d = READ_ONCE(*p4dp);
+		p4d_t p4d = p4dp_get(p4dp);
 
 		next = p4d_addr_end(addr, end);
 		if (!p4d_present(p4d))
@@ -3108,7 +3108,7 @@ static void gup_fast_pgd_range(unsigned long addr, unsigned long end,
 
 	pgdp = pgd_offset(current->mm, addr);
 	do {
-		pgd_t pgd = READ_ONCE(*pgdp);
+		pgd_t pgd = pgdp_get(pgdp);
 
 		next = pgd_addr_end(addr, end);
 		if (pgd_none(pgd))
mm/hmm.c +1 -1
index 87562914670a..a56081d67ad6 100644
@@ -491,7 +491,7 @@ static int hmm_vma_walk_pud(pud_t *pudp, unsigned long start, unsigned long end,
 	/* Normally we don't want to split the huge page */
 	walk->action = ACTION_CONTINUE;
 
-	pud = READ_ONCE(*pudp);
+	pud = pudp_get(pudp);
 	if (!pud_present(pud)) {
 		spin_unlock(ptl);
 		return hmm_vma_walk_hole(start, end, -1, walk);
mm/memory.c +2 -2
index b59ae7ce42eb..0c295e2fe8e8 100644
@@ -6690,12 +6690,12 @@ int follow_pfnmap_start(struct follow_pfnmap_args *args)
 		goto out;
 
 	p4dp = p4d_offset(pgdp, address);
-	p4d = READ_ONCE(*p4dp);
+	p4d = p4dp_get(p4dp);
 	if (p4d_none(p4d) || unlikely(p4d_bad(p4d)))
 		goto out;
 
 	pudp = pud_offset(p4dp, address);
-	pud = READ_ONCE(*pudp);
+	pud = pudp_get(pudp);
 	if (pud_none(pud))
 		goto out;
 	if (pud_leaf(pud)) {
mm/mprotect.c +1 -1
index 113b48985834..988c366137d5 100644
@@ -599,7 +599,7 @@ static inline long change_pud_range(struct mmu_gather *tlb,
 			break;
 		}
 
-		pud = READ_ONCE(*pudp);
+		pud = pudp_get(pudp);
 		if (pud_none(pud))
 			continue;
 
mm/sparse-vmemmap.c +1 -1
index dbd8daccade2..37522d6cb398 100644
@@ -439,7 +439,7 @@ int __meminit vmemmap_populate_hugepages(unsigned long start, unsigned long end,
 			return -ENOMEM;
 
 		pmd = pmd_offset(pud, addr);
-		if (pmd_none(READ_ONCE(*pmd))) {
+		if (pmd_none(pmdp_get(pmd))) {
 			void *p;
 
 			p = vmemmap_alloc_block_buf(PMD_SIZE, node, altmap);
mm/vmscan.c +1 -1
index b2fc8b626d3d..2239de111fa6 100644
@@ -3773,7 +3773,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 	pud = pud_offset(p4d, start & P4D_MASK);
 restart:
 	for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
-		pud_t val = READ_ONCE(pud[i]);
+		pud_t val = pudp_get(pud + i);
 
 		next = pud_addr_end(addr, end);
 
Signature · 1 line
2.47.2
reviewer Reviewed-by on v3 2/22
#3 lore raw

Re: [PATCH v3 02/22] mm: replace READ_ONCE() with standard page table accessors

Quoted 14 lines · Samuel Holland

From: Anshuman Khandual <[email protected]>

Replace all READ_ONCE() with a standard page table accessors i.e pxdp_get() that defaults into READ_ONCE() in cases where platform does not override.

Quoted 3 lines

---

#4 lore raw

PATCH v3 3/22 mm/dirty: replace READ_ONCE() with pudp_get()

In reply to Samuel Holland

From: Anshuman Khandual <[email protected]>

Replace READ_ONCE() with a standard page table accessor i.e pudp_get() that anyways defaults into READ_ONCE() in cases where platform does not override

---

Changes in v3:
- New patch for v3 (cherry-picked from linux-next)

 mm/mapping_dirty_helpers.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mapping_dirty_helpers.c +1 -1
index c193de6cb23a..737c407f4081 100644
@@ -149,7 +149,7 @@ static int wp_clean_pud_entry(pud_t *pud, unsigned long addr, unsigned long end,
 			      struct mm_walk *walk)
 {
 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
-	pud_t pudval = READ_ONCE(*pud);
+	pud_t pudval = pudp_get(pud);
 
 	/* Do not split a huge pud */
 	if (pud_trans_huge(pudval)) {
Signature · 1 line
2.47.2
#5 lore raw

PATCH v3 4/22 perf/events: replace READ_ONCE() with standard page table accessors

In reply to Samuel Holland

From: Anshuman Khandual <[email protected]>

Replace READ_ONCE() with standard page table accessors i.e pxdp_get() which anyways default into READ_ONCE() in cases where platform does not override.

---

Changes in v3:
- Replace my patch with Anshuman Khandual's patch from LKML

Changes in v2:
- New patch for v2

 kernel/events/core.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
kernel/events/core.c +3 -3
index 1fd347da9026..fa4f9165bd94 100644
@@ -8122,7 +8122,7 @@ static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
 	pte_t *ptep, pte;
 
 	pgdp = pgd_offset(mm, addr);
-	pgd = READ_ONCE(*pgdp);
+	pgd = pgdp_get(pgdp);
 	if (pgd_none(pgd))
 		return 0;
 
@@ -8130,7 +8130,7 @@ static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
 		return pgd_leaf_size(pgd);
 
 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
-	p4d = READ_ONCE(*p4dp);
+	p4d = p4dp_get(p4dp);
 	if (!p4d_present(p4d))
 		return 0;
 
@@ -8138,7 +8138,7 @@ static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
 		return p4d_leaf_size(p4d);
 
 	pudp = pud_offset_lockless(p4dp, p4d, addr);
-	pud = READ_ONCE(*pudp);
+	pud = pudp_get(pudp);
 	if (!pud_present(pud))
 		return 0;
 
Signature · 1 line
2.47.2
maintainer Acked-by on v3 4/22
#6 lore raw

Re: [PATCH v3 04/22] perf/events: replace READ_ONCE() with standard page table accessors

Quoted 14 lines · Samuel Holland

From: Anshuman Khandual <[email protected]>

Replace READ_ONCE() with standard page table accessors i.e pxdp_get() which anyways default into READ_ONCE() in cases where platform does not override.

Quoted 1 line

---

Signature · 3 lines
Cheers

David
#7 lore raw

PATCH v3 5/22 mm: Move the fallback definitions of pXXp_get()

In reply to Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Move these definitions up by a few lines, so they will be in scope everywhere that currently dereferences a pXX_t pointer.

---

(no changes since v2)

Changes in v2:
- New patch for v2

 include/linux/pgtable.h | 70 ++++++++++++++++++++---------------------
 1 file changed, 35 insertions(+), 35 deletions(-)
include/linux/pgtable.h +35 -35
index 32e8457ad535..ca8c99cdc1cc 100644
@@ -90,6 +90,41 @@ static inline unsigned long pud_index(unsigned long address)
 #define pgd_index(a)  (((a) >> PGDIR_SHIFT) & (PTRS_PER_PGD - 1))
 #endif
 
+#ifndef ptep_get
+static inline pte_t ptep_get(pte_t *ptep)
+{
+	return READ_ONCE(*ptep);
+}
+#endif
+
+#ifndef pmdp_get
+static inline pmd_t pmdp_get(pmd_t *pmdp)
+{
+	return READ_ONCE(*pmdp);
+}
+#endif
+
+#ifndef pudp_get
+static inline pud_t pudp_get(pud_t *pudp)
+{
+	return READ_ONCE(*pudp);
+}
+#endif
+
+#ifndef p4dp_get
+static inline p4d_t p4dp_get(p4d_t *p4dp)
+{
+	return READ_ONCE(*p4dp);
+}
+#endif
+
+#ifndef pgdp_get
+static inline pgd_t pgdp_get(pgd_t *pgdp)
+{
+	return READ_ONCE(*pgdp);
+}
+#endif
+
 #ifndef kernel_pte_init
 static inline void kernel_pte_init(void *addr)
 {
@@ -334,41 +369,6 @@ static inline int pudp_set_access_flags(struct vm_area_struct *vma,
 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
 #endif
 
-#ifndef ptep_get
-static inline pte_t ptep_get(pte_t *ptep)
-{
-	return READ_ONCE(*ptep);
-}
-#endif
-
-#ifndef pmdp_get
-static inline pmd_t pmdp_get(pmd_t *pmdp)
-{
-	return READ_ONCE(*pmdp);
-}
-#endif
-
-#ifndef pudp_get
-static inline pud_t pudp_get(pud_t *pudp)
-{
-	return READ_ONCE(*pudp);
-}
-#endif
-
-#ifndef p4dp_get
-static inline p4d_t p4dp_get(p4d_t *p4dp)
-{
-	return READ_ONCE(*p4dp);
-}
-#endif
-
-#ifndef pgdp_get
-static inline pgd_t pgdp_get(pgd_t *pgdp)
-{
-	return READ_ONCE(*pgdp);
-}
-#endif
-
 #ifndef __HAVE_ARCH_PTEP_TEST_AND_CLEAR_YOUNG
 static inline int ptep_test_and_clear_young(struct vm_area_struct *vma,
 					    unsigned long address,
Signature · 1 line
2.47.2
maintainer Acked-by on v3 5/22
#8 lore raw

Re: [PATCH v3 05/22] mm: Move the fallback definitions of pXXp_get()

Quoted 9 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Move these definitions up by a few lines, so they will be in scope everywhere that currently dereferences a pXX_t pointer.

---

Signature · 3 lines
Cheers

David
#9 lore raw

PATCH v3 6/22 mm: Always use page table accessor functions

In reply to Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

@@
pte_t *P;
expression I;
@@
(
&P[I]
|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Changes in v3:
- Rebased on top of torvalds/master (v6.18-rc5+)

Changes in v2:
- New patch for v2

 fs/dax.c                |  4 +-
 fs/proc/task_mmu.c      | 27 +++++++------
 fs/userfaultfd.c        |  6 +--
 include/linux/huge_mm.h |  8 ++--
 include/linux/mm.h      | 14 +++----
 include/linux/pgtable.h | 42 +++++++++----------
 mm/damon/vaddr.c        |  2 +-
 mm/debug_vm_pgtable.c   |  4 +-
 mm/filemap.c            |  6 +--
 mm/gup.c                | 24 +++++------
 mm/huge_memory.c        | 90 ++++++++++++++++++++---------------------
 mm/hugetlb.c            | 10 ++---
 mm/hugetlb_vmemmap.c    |  4 +-
 mm/kasan/init.c         | 39 +++++++++---------
 mm/kasan/shadow.c       | 12 +++---
 mm/khugepaged.c         |  4 +-
 mm/ksm.c                |  2 +-
 mm/madvise.c            |  8 ++--
 mm/memory-failure.c     | 14 +++----
 mm/memory.c             | 76 +++++++++++++++++-----------------
 mm/mempolicy.c          |  4 +-
 mm/migrate.c            |  4 +-
 mm/migrate_device.c     | 10 ++---
 mm/mlock.c              |  6 +--
 mm/mprotect.c           |  2 +-
 mm/mremap.c             | 30 +++++++-------
 mm/page_table_check.c   |  4 +-
 mm/page_vma_mapped.c    |  6 +--
 mm/pagewalk.c           | 14 +++----
 mm/percpu.c             |  8 ++--
 mm/pgalloc-track.h      |  8 ++--
 mm/pgtable-generic.c    | 23 ++++++-----
 mm/rmap.c               |  8 ++--
 mm/sparse-vmemmap.c     |  8 ++--
 mm/userfaultfd.c        | 10 ++---
 mm/vmalloc.c            | 49 +++++++++++-----------
 mm/vmscan.c             | 14 +++----
 37 files changed, 304 insertions(+), 300 deletions(-)
fs/dax.c +2 -2
index 516f995a988c..e09a80ee44a0 100644
@@ -1900,7 +1900,7 @@ static vm_fault_t dax_iomap_pte_fault(struct vm_fault *vmf, unsigned long *pfnp,
 	 * the PTE we need to set up.  If so just return and the fault will be
 	 * retried.
 	 */
-	if (pmd_trans_huge(*vmf->pmd)) {
+	if (pmd_trans_huge(pmdp_get(vmf->pmd))) {
 		ret = VM_FAULT_NOPAGE;
 		goto unlock_entry;
 	}
@@ -2023,7 +2023,7 @@ static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp,
 	 * the PMD we need to set up.  If so just return and the fault will be
 	 * retried.
 	 */
-	if (!pmd_none(*vmf->pmd) && !pmd_trans_huge(*vmf->pmd)) {
+	if (!pmd_none(pmdp_get(vmf->pmd)) && !pmd_trans_huge(pmdp_get(vmf->pmd))) {
 		ret = 0;
 		goto unlock_entry;
 	}
fs/proc/task_mmu.c +14 -13
index fc35a0543f01..4f80704b78af 100644
@@ -1060,11 +1060,11 @@ static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
 	bool present = false;
 	struct folio *folio;
 
-	if (pmd_present(*pmd)) {
-		page = vm_normal_page_pmd(vma, addr, *pmd);
+	if (pmd_present(pmdp_get(pmd))) {
+		page = vm_normal_page_pmd(vma, addr, pmdp_get(pmd));
 		present = true;
-	} else if (unlikely(thp_migration_supported() && is_swap_pmd(*pmd))) {
-		swp_entry_t entry = pmd_to_swp_entry(*pmd);
+	} else if (unlikely(thp_migration_supported() && is_swap_pmd(pmdp_get(pmd)))) {
+		swp_entry_t entry = pmd_to_swp_entry(pmdp_get(pmd));
 
 		if (is_pfn_swap_entry(entry))
 			page = pfn_swap_entry_to_page(entry);
@@ -1081,7 +1081,8 @@ static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
 	else
 		mss->file_thp += HPAGE_PMD_SIZE;
 
-	smaps_account(mss, page, true, pmd_young(*pmd), pmd_dirty(*pmd),
+	smaps_account(mss, page, true, pmd_young(pmdp_get(pmd)),
+		      pmd_dirty(pmdp_get(pmd)),
 		      locked, present);
 }
 #else
@@ -1636,7 +1637,7 @@ static inline void clear_soft_dirty(struct vm_area_struct *vma,
 static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
 		unsigned long addr, pmd_t *pmdp)
 {
-	pmd_t old, pmd = *pmdp;
+	pmd_t old, pmd = pmdp_get(pmdp);
 
 	if (pmd_present(pmd)) {
 		/* See comment in change_huge_pmd() */
@@ -1678,10 +1679,10 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
 			goto out;
 		}
 
-		if (!pmd_present(*pmd))
+		if (!pmd_present(pmdp_get(pmd)))
 			goto out;
 
-		folio = pmd_folio(*pmd);
+		folio = pmd_folio(pmdp_get(pmd));
 
 		/* Clear accessed and referenced bits. */
 		pmdp_test_and_clear_young(vma, addr, pmd);
@@ -1989,7 +1990,7 @@ static int pagemap_pmd_range(pmd_t *pmdp, unsigned long addr, unsigned long end,
 	if (ptl) {
 		unsigned int idx = (addr & ~PMD_MASK) >> PAGE_SHIFT;
 		u64 flags = 0, frame = 0;
-		pmd_t pmd = *pmdp;
+		pmd_t pmd = pmdp_get(pmdp);
 		struct page *page = NULL;
 		struct folio *folio = NULL;
 
@@ -2416,7 +2417,7 @@ static unsigned long pagemap_thp_category(struct pagemap_scan_private *p,
 static void make_uffd_wp_pmd(struct vm_area_struct *vma,
 			     unsigned long addr, pmd_t *pmdp)
 {
-	pmd_t old, pmd = *pmdp;
+	pmd_t old, pmd = pmdp_get(pmdp);
 
 	if (pmd_present(pmd)) {
 		old = pmdp_invalidate_ad(vma, addr, pmdp);
@@ -2646,7 +2647,7 @@ static int pagemap_scan_thp_entry(pmd_t *pmd, unsigned long start,
 		return -ENOENT;
 
 	categories = p->cur_vma_category |
-		     pagemap_thp_category(p, vma, start, *pmd);
+		     pagemap_thp_category(p, vma, start, pmdp_get(pmd));
 
 	if (!pagemap_scan_is_interesting_page(categories, p))
 		goto out_unlock;
@@ -3181,9 +3182,9 @@ static int gather_pte_stats(pmd_t *pmd, unsigned long addr,
 	if (ptl) {
 		struct page *page;
 
-		page = can_gather_numa_stats_pmd(*pmd, vma, addr);
+		page = can_gather_numa_stats_pmd(pmdp_get(pmd), vma, addr);
 		if (page)
-			gather_stats(page, md, pmd_dirty(*pmd),
+			gather_stats(page, md, pmd_dirty(pmdp_get(pmd)),
 				     HPAGE_PMD_SIZE/PAGE_SIZE);
 		spin_unlock(ptl);
 		return 0;
fs/userfaultfd.c +3 -3
index 54c6cc7fe9c6..2e2a6b326c2f 100644
@@ -289,13 +289,13 @@ static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
 	assert_fault_locked(vmf);
 
 	pgd = pgd_offset(mm, address);
-	if (!pgd_present(*pgd))
+	if (!pgd_present(pgdp_get(pgd)))
 		goto out;
 	p4d = p4d_offset(pgd, address);
-	if (!p4d_present(*p4d))
+	if (!p4d_present(p4dp_get(p4d)))
 		goto out;
 	pud = pud_offset(p4d, address);
-	if (!pud_present(*pud))
+	if (!pud_present(pudp_get(pud)))
 		goto out;
 	pmd = pmd_offset(pud, address);
 again:
include/linux/huge_mm.h +4 -4
index 71ac78b9f834..d2840221e7cd 100644
@@ -409,7 +409,7 @@ void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
 #define split_huge_pmd(__vma, __pmd, __address)				\
 	do {								\
 		pmd_t *____pmd = (__pmd);				\
-		if (is_swap_pmd(*____pmd) || pmd_trans_huge(*____pmd))	\
+		if (is_swap_pmd(pmdp_get(____pmd)) || pmd_trans_huge(pmdp_get(____pmd)))	\
 			__split_huge_pmd(__vma, __pmd, __address,	\
 					 false);			\
 	}  while (0)
@@ -434,7 +434,7 @@ change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
 #define split_huge_pud(__vma, __pud, __address)				\
 	do {								\
 		pud_t *____pud = (__pud);				\
-		if (pud_trans_huge(*____pud))				\
+		if (pud_trans_huge(pudp_get(____pud)))				\
 			__split_huge_pud(__vma, __pud, __address);	\
 	}  while (0)
 
@@ -456,7 +456,7 @@ static inline int is_swap_pmd(pmd_t pmd)
 static inline spinlock_t *pmd_trans_huge_lock(pmd_t *pmd,
 		struct vm_area_struct *vma)
 {
-	if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd))
+	if (is_swap_pmd(pmdp_get(pmd)) || pmd_trans_huge(pmdp_get(pmd)))
 		return __pmd_trans_huge_lock(pmd, vma);
 	else
 		return NULL;
@@ -464,7 +464,7 @@ static inline spinlock_t *pmd_trans_huge_lock(pmd_t *pmd,
 static inline spinlock_t *pud_trans_huge_lock(pud_t *pud,
 		struct vm_area_struct *vma)
 {
-	if (pud_trans_huge(*pud))
+	if (pud_trans_huge(pudp_get(pud)))
 		return __pud_trans_huge_lock(pud, vma);
 	else
 		return NULL;
include/linux/mm.h +7 -7
index d16b33bacc32..fdc333384190 100644
@@ -2921,20 +2921,20 @@ int __pte_alloc_kernel(pmd_t *pmd);
 static inline p4d_t *p4d_alloc(struct mm_struct *mm, pgd_t *pgd,
 		unsigned long address)
 {
-	return (unlikely(pgd_none(*pgd)) && __p4d_alloc(mm, pgd, address)) ?
+	return (unlikely(pgd_none(pgdp_get(pgd))) && __p4d_alloc(mm, pgd, address)) ?
 		NULL : p4d_offset(pgd, address);
 }
 
 static inline pud_t *pud_alloc(struct mm_struct *mm, p4d_t *p4d,
 		unsigned long address)
 {
-	return (unlikely(p4d_none(*p4d)) && __pud_alloc(mm, p4d, address)) ?
+	return (unlikely(p4d_none(p4dp_get(p4d))) && __pud_alloc(mm, p4d, address)) ?
 		NULL : pud_offset(p4d, address);
 }
 
 static inline pmd_t *pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
 {
-	return (unlikely(pud_none(*pud)) && __pmd_alloc(mm, pud, address))?
+	return (unlikely(pud_none(pudp_get(pud))) && __pmd_alloc(mm, pud, address)) ?
 		NULL: pmd_offset(pud, address);
 }
 #endif /* CONFIG_MMU */
@@ -3027,9 +3027,9 @@ static inline spinlock_t *ptlock_ptr(struct ptdesc *ptdesc)
 }
 #endif /* ALLOC_SPLIT_PTLOCKS */
 
-static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmd)
+static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmdvalp)
 {
-	return ptlock_ptr(page_ptdesc(pmd_page(*pmd)));
+	return ptlock_ptr(page_ptdesc(pmd_page(*pmdvalp)));
 }
 
 static inline spinlock_t *ptep_lockptr(struct mm_struct *mm, pte_t *pte)
@@ -3146,7 +3146,7 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd,
 	pte_unmap(pte);					\
 } while (0)
 
-#define pte_alloc(mm, pmd) (unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, pmd))
+#define pte_alloc(mm, pmd) (unlikely(pmd_none(pmdp_get(pmd))) && __pte_alloc(mm, pmd))
 
 #define pte_alloc_map(mm, pmd, address)			\
 	(pte_alloc(mm, pmd) ? NULL : pte_offset_map(pmd, address))
@@ -3156,7 +3156,7 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd,
 		 NULL : pte_offset_map_lock(mm, pmd, address, ptlp))
 
 #define pte_alloc_kernel(pmd, address)			\
-	((unlikely(pmd_none(*(pmd))) && __pte_alloc_kernel(pmd))? \
+	((unlikely(pmd_none(pmdp_get(pmd))) && __pte_alloc_kernel(pmd)) ? \
 		NULL: pte_offset_kernel(pmd, address))
 
 #if defined(CONFIG_SPLIT_PMD_PTLOCKS)
include/linux/pgtable.h +21 -21

148 lines not on this page · raw message

mm/damon/vaddr.c +1 -1
index 7e834467b2d8..b750cbe56bc6 100644
@@ -910,7 +910,7 @@ static int damos_va_stat_pmd_entry(pmd_t *pmd, unsigned long addr,
 	int nr;
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
-	if (pmd_trans_huge(*pmd)) {
+	if (pmd_trans_huge(pmdp_get(pmd))) {
 		pmd_t pmde;
 
 		ptl = pmd_trans_huge_lock(pmd, vma);
mm/debug_vm_pgtable.c +2 -2
index 830107b6dd08..fb5596e2e426 100644
@@ -431,7 +431,7 @@ static void __init pmd_huge_tests(struct pgtable_debug_args *args)
 	 * X86 defined pmd_set_huge() verifies that the given
 	 * PMD is not a populated non-leaf entry.
 	 */
-	WRITE_ONCE(*args->pmdp, __pmd(0));
+	set_pmd(args->pmdp, __pmd(0));
 	WARN_ON(!pmd_set_huge(args->pmdp, __pfn_to_phys(args->fixed_pmd_pfn), args->page_prot));
 	WARN_ON(!pmd_clear_huge(args->pmdp));
 	pmd = pmdp_get(args->pmdp);
@@ -451,7 +451,7 @@ static void __init pud_huge_tests(struct pgtable_debug_args *args)
 	 * X86 defined pud_set_huge() verifies that the given
 	 * PUD is not a populated non-leaf entry.
 	 */
-	WRITE_ONCE(*args->pudp, __pud(0));
+	set_pud(args->pudp, __pud(0));
 	WARN_ON(!pud_set_huge(args->pudp, __pfn_to_phys(args->fixed_pud_pfn), args->page_prot));
 	WARN_ON(!pud_clear_huge(args->pudp));
 	pud = pudp_get(args->pudp);
mm/filemap.c +3 -3
index 2f1e7e283a51..76027cf534c9 100644
@@ -3611,13 +3611,13 @@ static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio,
 	struct mm_struct *mm = vmf->vma->vm_mm;
 
 	/* Huge page is mapped? No need to proceed. */
-	if (pmd_trans_huge(*vmf->pmd)) {
+	if (pmd_trans_huge(pmdp_get(vmf->pmd))) {
 		folio_unlock(folio);
 		folio_put(folio);
 		return true;
 	}
 
-	if (pmd_none(*vmf->pmd) && folio_test_pmd_mappable(folio)) {
+	if (pmd_none(pmdp_get(vmf->pmd)) && folio_test_pmd_mappable(folio)) {
 		struct page *page = folio_file_page(folio, start);
 		vm_fault_t ret = do_set_pmd(vmf, folio, page);
 		if (!ret) {
@@ -3627,7 +3627,7 @@ static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio,
 		}
 	}
 
-	if (pmd_none(*vmf->pmd) && vmf->prealloc_pte)
+	if (pmd_none(pmdp_get(vmf->pmd)) && vmf->prealloc_pte)
 		pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
 
 	return false;
mm/gup.c +12 -12
index b46112d36f7e..549f9e868311 100644
@@ -652,7 +652,7 @@ static struct page *follow_huge_pud(struct vm_area_struct *vma,
 {
 	struct mm_struct *mm = vma->vm_mm;
 	struct page *page;
-	pud_t pud = *pudp;
+	pud_t pud = pudp_get(pudp);
 	unsigned long pfn = pud_pfn(pud);
 	int ret;
 
@@ -704,7 +704,7 @@ static struct page *follow_huge_pmd(struct vm_area_struct *vma,
 				    unsigned long *page_mask)
 {
 	struct mm_struct *mm = vma->vm_mm;
-	pmd_t pmdval = *pmd;
+	pmd_t pmdval = pmdp_get(pmd);
 	struct page *page;
 	int ret;
 
@@ -719,7 +719,7 @@ static struct page *follow_huge_pmd(struct vm_area_struct *vma,
 	if ((flags & FOLL_DUMP) && is_huge_zero_pmd(pmdval))
 		return ERR_PTR(-EFAULT);
 
-	if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags))
+	if (pmd_protnone(pmdp_get(pmd)) && !gup_can_follow_protnone(vma, flags))
 		return NULL;
 
 	if (!pmd_write(pmdval) && gup_must_unshare(vma, flags, page))
@@ -918,7 +918,7 @@ static struct page *follow_pmd_mask(struct vm_area_struct *vma,
 		return no_page_table(vma, flags, address);
 
 	ptl = pmd_lock(mm, pmd);
-	pmdval = *pmd;
+	pmdval = pmdp_get(pmd);
 	if (unlikely(!pmd_present(pmdval))) {
 		spin_unlock(ptl);
 		return no_page_table(vma, flags, address);
@@ -1017,7 +1017,7 @@ static struct page *follow_page_mask(struct vm_area_struct *vma,
 	*page_mask = 0;
 	pgd = pgd_offset(mm, address);
 
-	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
+	if (pgd_none(pgdp_get(pgd)) || unlikely(pgd_bad(pgdp_get(pgd))))
 		page = no_page_table(vma, flags, address);
 	else
 		page = follow_p4d_mask(vma, address, pgd, flags, page_mask);
@@ -1043,16 +1043,16 @@ static int get_gate_page(struct mm_struct *mm, unsigned long address,
 	if (gup_flags & FOLL_WRITE)
 		return -EFAULT;
 	pgd = pgd_offset(mm, address);
-	if (pgd_none(*pgd))
+	if (pgd_none(pgdp_get(pgd)))
 		return -EFAULT;
 	p4d = p4d_offset(pgd, address);
-	if (p4d_none(*p4d))
+	if (p4d_none(p4dp_get(p4d)))
 		return -EFAULT;
 	pud = pud_offset(p4d, address);
-	if (pud_none(*pud))
+	if (pud_none(pudp_get(pud)))
 		return -EFAULT;
 	pmd = pmd_offset(pud, address);
-	if (!pmd_present(*pmd))
+	if (!pmd_present(pmdp_get(pmd)))
 		return -EFAULT;
 	pte = pte_offset_map(pmd, address);
 	if (!pte)
@@ -2876,7 +2876,7 @@ static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
 		if (!folio)
 			goto pte_unmap;
 
-		if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
+		if (unlikely(pmd_val(pmd) != pmd_val(pmdp_get(pmdp))) ||
 		    unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
 			gup_put_folio(folio, 1, flags);
 			goto pte_unmap;
@@ -2953,7 +2953,7 @@ static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
 	if (!folio)
 		return 0;
 
-	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
+	if (unlikely(pmd_val(orig) != pmd_val(pmdp_get(pmdp)))) {
 		gup_put_folio(folio, refs, flags);
 		return 0;
 	}
@@ -2996,7 +2996,7 @@ static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
 	if (!folio)
 		return 0;
 
-	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
+	if (unlikely(pud_val(orig) != pud_val(pudp_get(pudp)))) {
 		gup_put_folio(folio, refs, flags);
 		return 0;
 	}
mm/huge_memory.c +45 -45

300 lines not on this page · raw message

mm/hugetlb.c +5 -5
index 0455119716ec..41cbc85b5051 100644
@@ -7584,7 +7584,7 @@ pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
 		goto out;
 
 	spin_lock(&mm->page_table_lock);
-	if (pud_none(*pud)) {
+	if (pud_none(pudp_get(pud))) {
 		pud_populate(mm, pud,
 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
 		mm_inc_nr_pmds(mm);
@@ -7677,7 +7677,7 @@ pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
 			pte = (pte_t *)pud;
 		} else {
 			BUG_ON(sz != PMD_SIZE);
-			if (want_pmd_share(vma, addr) && pud_none(*pud))
+			if (want_pmd_share(vma, addr) && pud_none(pudp_get(pud)))
 				pte = huge_pmd_share(mm, vma, addr, pud);
 			else
 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
@@ -7711,17 +7711,17 @@ pte_t *huge_pte_offset(struct mm_struct *mm,
 	pmd_t *pmd;
 
 	pgd = pgd_offset(mm, addr);
-	if (!pgd_present(*pgd))
+	if (!pgd_present(pgdp_get(pgd)))
 		return NULL;
 	p4d = p4d_offset(pgd, addr);
-	if (!p4d_present(*p4d))
+	if (!p4d_present(p4dp_get(p4d)))
 		return NULL;
 
 	pud = pud_offset(p4d, addr);
 	if (sz == PUD_SIZE)
 		/* must be pud huge, non-present or none */
 		return (pte_t *)pud;
-	if (!pud_present(*pud))
+	if (!pud_present(pudp_get(pud)))
 		return NULL;
 	/* must have a valid entry and size to go further */
 
mm/hugetlb_vmemmap.c +2 -2
index ba0fb1b6a5a8..059eb78480f5 100644
@@ -72,7 +72,7 @@ static int vmemmap_split_pmd(pmd_t *pmd, struct page *head, unsigned long start,
 	}
 
 	spin_lock(&init_mm.page_table_lock);
-	if (likely(pmd_leaf(*pmd))) {
+	if (likely(pmd_leaf(pmdp_get(pmd)))) {
 		/*
 		 * Higher order allocations from buddy allocator must be able to
 		 * be treated as indepdenent small pages (as they can be freed
@@ -106,7 +106,7 @@ static int vmemmap_pmd_entry(pmd_t *pmd, unsigned long addr,
 		walk->action = ACTION_CONTINUE;
 
 	spin_lock(&init_mm.page_table_lock);
-	head = pmd_leaf(*pmd) ? pmd_page(*pmd) : NULL;
+	head = pmd_leaf(pmdp_get(pmd)) ? pmd_page(pmdp_get(pmd)) : NULL;
 	/*
 	 * Due to HugeTLB alignment requirements and the vmemmap
 	 * pages being at the start of the hotplugged memory
mm/kasan/init.c +20 -19
index f084e7a5df1e..8e0fc4d0cd1e 100644
@@ -121,7 +121,7 @@ static int __ref zero_pmd_populate(pud_t *pud, unsigned long addr,
 			continue;
 		}
 
-		if (pmd_none(*pmd)) {
+		if (pmd_none(pmdp_get(pmd))) {
 			pte_t *p;
 
 			if (slab_is_available())
@@ -160,7 +160,7 @@ static int __ref zero_pud_populate(p4d_t *p4d, unsigned long addr,
 			continue;
 		}
 
-		if (pud_none(*pud)) {
+		if (pud_none(pudp_get(pud))) {
 			pmd_t *p;
 
 			if (slab_is_available()) {
@@ -202,7 +202,7 @@ static int __ref zero_p4d_populate(pgd_t *pgd, unsigned long addr,
 			continue;
 		}
 
-		if (p4d_none(*p4d)) {
+		if (p4d_none(p4dp_get(p4d))) {
 			pud_t *p;
 
 			if (slab_is_available()) {
@@ -265,7 +265,7 @@ int __ref kasan_populate_early_shadow(const void *shadow_start,
 			continue;
 		}
 
-		if (pgd_none(*pgd)) {
+		if (pgd_none(pgdp_get(pgd))) {
 
 			if (slab_is_available()) {
 				if (!p4d_alloc(&init_mm, pgd, addr))
@@ -292,7 +292,8 @@ static void kasan_free_pte(pte_t *pte_start, pmd_t *pmd)
 			return;
 	}
 
-	pte_free_kernel(&init_mm, (pte_t *)page_to_virt(pmd_page(*pmd)));
+	pte_free_kernel(&init_mm,
+			(pte_t *)page_to_virt(pmd_page(pmdp_get(pmd))));
 	pmd_clear(pmd);
 }
 
@@ -303,11 +304,11 @@ static void kasan_free_pmd(pmd_t *pmd_start, pud_t *pud)
 
 	for (i = 0; i < PTRS_PER_PMD; i++) {
 		pmd = pmd_start + i;
-		if (!pmd_none(*pmd))
+		if (!pmd_none(pmdp_get(pmd)))
 			return;
 	}
 
-	pmd_free(&init_mm, (pmd_t *)page_to_virt(pud_page(*pud)));
+	pmd_free(&init_mm, (pmd_t *)page_to_virt(pud_page(pudp_get(pud))));
 	pud_clear(pud);
 }
 
@@ -318,11 +319,11 @@ static void kasan_free_pud(pud_t *pud_start, p4d_t *p4d)
 
 	for (i = 0; i < PTRS_PER_PUD; i++) {
 		pud = pud_start + i;
-		if (!pud_none(*pud))
+		if (!pud_none(pudp_get(pud)))
 			return;
 	}
 
-	pud_free(&init_mm, (pud_t *)page_to_virt(p4d_page(*p4d)));
+	pud_free(&init_mm, (pud_t *)page_to_virt(p4d_page(p4dp_get(p4d))));
 	p4d_clear(p4d);
 }
 
@@ -333,11 +334,11 @@ static void kasan_free_p4d(p4d_t *p4d_start, pgd_t *pgd)
 
 	for (i = 0; i < PTRS_PER_P4D; i++) {
 		p4d = p4d_start + i;
-		if (!p4d_none(*p4d))
+		if (!p4d_none(p4dp_get(p4d)))
 			return;
 	}
 
-	p4d_free(&init_mm, (p4d_t *)page_to_virt(pgd_page(*pgd)));
+	p4d_free(&init_mm, (p4d_t *)page_to_virt(pgd_page(pgdp_get(pgd))));
 	pgd_clear(pgd);
 }
 
@@ -373,10 +374,10 @@ static void kasan_remove_pmd_table(pmd_t *pmd, unsigned long addr,
 
 		next = pmd_addr_end(addr, end);
 
-		if (!pmd_present(*pmd))
+		if (!pmd_present(pmdp_get(pmd)))
 			continue;
 
-		if (kasan_pte_table(*pmd)) {
+		if (kasan_pte_table(pmdp_get(pmd))) {
 			if (IS_ALIGNED(addr, PMD_SIZE) &&
 			    IS_ALIGNED(next, PMD_SIZE)) {
 				pmd_clear(pmd);
@@ -399,10 +400,10 @@ static void kasan_remove_pud_table(pud_t *pud, unsigned long addr,
 
 		next = pud_addr_end(addr, end);
 
-		if (!pud_present(*pud))
+		if (!pud_present(pudp_get(pud)))
 			continue;
 
-		if (kasan_pmd_table(*pud)) {
+		if (kasan_pmd_table(pudp_get(pud))) {
 			if (IS_ALIGNED(addr, PUD_SIZE) &&
 			    IS_ALIGNED(next, PUD_SIZE)) {
 				pud_clear(pud);
@@ -426,10 +427,10 @@ static void kasan_remove_p4d_table(p4d_t *p4d, unsigned long addr,
 
 		next = p4d_addr_end(addr, end);
 
-		if (!p4d_present(*p4d))
+		if (!p4d_present(p4dp_get(p4d)))
 			continue;
 
-		if (kasan_pud_table(*p4d)) {
+		if (kasan_pud_table(p4dp_get(p4d))) {
 			if (IS_ALIGNED(addr, P4D_SIZE) &&
 			    IS_ALIGNED(next, P4D_SIZE)) {
 				p4d_clear(p4d);
@@ -460,10 +461,10 @@ void kasan_remove_zero_shadow(void *start, unsigned long size)
 		next = pgd_addr_end(addr, end);
 
 		pgd = pgd_offset_k(addr);
-		if (!pgd_present(*pgd))
+		if (!pgd_present(pgdp_get(pgd)))
 			continue;
 
-		if (kasan_p4d_table(*pgd)) {
+		if (kasan_p4d_table(pgdp_get(pgd))) {
 			if (IS_ALIGNED(addr, PGDIR_SIZE) &&
 			    IS_ALIGNED(next, PGDIR_SIZE)) {
 				pgd_clear(pgd);
mm/kasan/shadow.c +6 -6
index 5d2a876035d6..331bbb7ff025 100644
@@ -191,20 +191,20 @@ static bool shadow_mapped(unsigned long addr)
 	pmd_t *pmd;
 	pte_t *pte;
 
-	if (pgd_none(*pgd))
+	if (pgd_none(pgdp_get(pgd)))
 		return false;
 	p4d = p4d_offset(pgd, addr);
-	if (p4d_none(*p4d))
+	if (p4d_none(p4dp_get(p4d)))
 		return false;
 	pud = pud_offset(p4d, addr);
-	if (pud_none(*pud))
+	if (pud_none(pudp_get(pud)))
 		return false;
-	if (pud_leaf(*pud))
+	if (pud_leaf(pudp_get(pud)))
 		return true;
 	pmd = pmd_offset(pud, addr);
-	if (pmd_none(*pmd))
+	if (pmd_none(pmdp_get(pmd)))
 		return false;
-	if (pmd_leaf(*pmd))
+	if (pmd_leaf(pmdp_get(pmd)))
 		return true;
 	pte = pte_offset_kernel(pmd, addr);
 	return !pte_none(ptep_get(pte));
mm/khugepaged.c +2 -2
index abe54f0043c7..1bff8ade751a 100644
@@ -1191,7 +1191,7 @@ static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
 		if (pte)
 			pte_unmap(pte);
 		spin_lock(pmd_ptl);
-		BUG_ON(!pmd_none(*pmd));
+		BUG_ON(!pmd_none(pmdp_get(pmd)));
 		/*
 		 * We can only use set_pmd_at when establishing
 		 * hugepmds and never for establishing regular pmds that
@@ -1228,7 +1228,7 @@ static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
 
 	spin_lock(pmd_ptl);
-	BUG_ON(!pmd_none(*pmd));
+	BUG_ON(!pmd_none(pmdp_get(pmd)));
 	folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
 	folio_add_lru_vma(folio, vma);
 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
mm/ksm.c +1 -1
index c4e730409949..0a0eeb667fe6 100644
@@ -1322,7 +1322,7 @@ static int write_protect_page(struct vm_area_struct *vma, struct folio *folio,
 
 		set_pte_at(mm, pvmw.address, pvmw.pte, entry);
 	}
-	*orig_pte = entry;
+	set_pte(orig_pte, entry);
 	err = 0;
 
 out_unlock:
mm/madvise.c +4 -4
index fb1c86e630b6..53e60565f3e5 100644
@@ -377,7 +377,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 					!can_do_file_pageout(vma);
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
-	if (pmd_trans_huge(*pmd)) {
+	if (pmd_trans_huge(pmdp_get(pmd))) {
 		pmd_t orig_pmd;
 		unsigned long next = pmd_addr_end(addr, end);
 
@@ -386,7 +386,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 		if (!ptl)
 			return 0;
 
-		orig_pmd = *pmd;
+		orig_pmd = pmdp_get(pmd);
 		if (is_huge_zero_pmd(orig_pmd))
 			goto huge_unlock;
 
@@ -668,7 +668,7 @@ static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
 	int nr, max_nr;
 
 	next = pmd_addr_end(addr, end);
-	if (pmd_trans_huge(*pmd))
+	if (pmd_trans_huge(pmdp_get(pmd)))
 		if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
 			return 0;
 
@@ -1116,7 +1116,7 @@ static int guard_install_set_pte(unsigned long addr, unsigned long next,
 	unsigned long *nr_pages = (unsigned long *)walk->private;
 
 	/* Simply install a PTE marker, this causes segfault on access. */
-	*ptep = make_pte_marker(PTE_MARKER_GUARD);
+	set_pte(ptep, make_pte_marker(PTE_MARKER_GUARD));
 	(*nr_pages)++;
 
 	return 0;
mm/memory-failure.c +7 -7
index 3edebb0cda30..5231febc6345 100644
@@ -339,20 +339,20 @@ static unsigned long dev_pagemap_mapping_shift(struct vm_area_struct *vma,
 
 	VM_BUG_ON_VMA(address == -EFAULT, vma);
 	pgd = pgd_offset(vma->vm_mm, address);
-	if (!pgd_present(*pgd))
+	if (!pgd_present(pgdp_get(pgd)))
 		return 0;
 	p4d = p4d_offset(pgd, address);
-	if (!p4d_present(*p4d))
+	if (!p4d_present(p4dp_get(p4d)))
 		return 0;
 	pud = pud_offset(p4d, address);
-	if (!pud_present(*pud))
+	if (!pud_present(pudp_get(pud)))
 		return 0;
-	if (pud_trans_huge(*pud))
+	if (pud_trans_huge(pudp_get(pud)))
 		return PUD_SHIFT;
 	pmd = pmd_offset(pud, address);
-	if (!pmd_present(*pmd))
+	if (!pmd_present(pmdp_get(pmd)))
 		return 0;
-	if (pmd_trans_huge(*pmd))
+	if (pmd_trans_huge(pmdp_get(pmd)))
 		return PMD_SHIFT;
 	pte = pte_offset_map(pmd, address);
 	if (!pte)
@@ -705,7 +705,7 @@ static int check_hwpoisoned_entry(pte_t pte, unsigned long addr, short shift,
 static int check_hwpoisoned_pmd_entry(pmd_t *pmdp, unsigned long addr,
 				      struct hwpoison_walk *hwp)
 {
-	pmd_t pmd = *pmdp;
+	pmd_t pmd = pmdp_get(pmdp);
 	unsigned long pfn;
 	unsigned long hwpoison_vaddr;
 
mm/memory.c +38 -38

260 lines not on this page · raw message

mm/mempolicy.c +2 -2
index eb83cff7db8c..8eef680d0f0e 100644
@@ -645,11 +645,11 @@ static void queue_folios_pmd(pmd_t *pmd, struct mm_walk *walk)
 	struct folio *folio;
 	struct queue_pages *qp = walk->private;
 
-	if (unlikely(is_pmd_migration_entry(*pmd))) {
+	if (unlikely(is_pmd_migration_entry(pmdp_get(pmd)))) {
 		qp->nr_failed++;
 		return;
 	}
-	folio = pmd_folio(*pmd);
+	folio = pmd_folio(pmdp_get(pmd));
 	if (is_huge_zero_folio(folio)) {
 		walk->action = ACTION_CONTINUE;
 		return;
mm/migrate.c +2 -2
index c0e9f15be2a2..98b5fe2a8994 100644
@@ -542,9 +542,9 @@ void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
 	spinlock_t *ptl;
 
 	ptl = pmd_lock(mm, pmd);
-	if (!is_pmd_migration_entry(*pmd))
+	if (!is_pmd_migration_entry(pmdp_get(pmd)))
 		goto unlock;
-	migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), ptl);
+	migration_entry_wait_on_locked(pmd_to_swp_entry(pmdp_get(pmd)), ptl);
 	return;
 unlock:
 	spin_unlock(ptl);
mm/migrate_device.c +5 -5
index abd9f6850db6..9714448eb97d 100644
@@ -69,19 +69,19 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp,
 	pte_t *ptep;
 
 again:
-	if (pmd_none(*pmdp))
+	if (pmd_none(pmdp_get(pmdp)))
 		return migrate_vma_collect_hole(start, end, -1, walk);
 
-	if (pmd_trans_huge(*pmdp)) {
+	if (pmd_trans_huge(pmdp_get(pmdp))) {
 		struct folio *folio;
 
 		ptl = pmd_lock(mm, pmdp);
-		if (unlikely(!pmd_trans_huge(*pmdp))) {
+		if (unlikely(!pmd_trans_huge(pmdp_get(pmdp)))) {
 			spin_unlock(ptl);
 			goto again;
 		}
 
-		folio = pmd_folio(*pmdp);
+		folio = pmd_folio(pmdp_get(pmdp));
 		if (is_huge_zero_folio(folio)) {
 			spin_unlock(ptl);
 			split_huge_pmd(vma, pmdp, addr);
@@ -615,7 +615,7 @@ static void migrate_vma_insert_page(struct migrate_vma *migrate,
 	pmdp = pmd_alloc(mm, pudp, addr);
 	if (!pmdp)
 		goto abort;
-	if (pmd_trans_huge(*pmdp))
+	if (pmd_trans_huge(pmdp_get(pmdp)))
 		goto abort;
 	if (pte_alloc(mm, pmdp))
 		goto abort;
mm/mlock.c +3 -3
index bb0776f5ef7c..c55ab38656d0 100644
@@ -361,11 +361,11 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,
 
 	ptl = pmd_trans_huge_lock(pmd, vma);
 	if (ptl) {
-		if (!pmd_present(*pmd))
+		if (!pmd_present(pmdp_get(pmd)))
 			goto out;
-		if (is_huge_zero_pmd(*pmd))
+		if (is_huge_zero_pmd(pmdp_get(pmd)))
 			goto out;
-		folio = pmd_folio(*pmd);
+		folio = pmd_folio(pmdp_get(pmd));
 		if (folio_is_zone_device(folio))
 			goto out;
 		if (vma->vm_flags & VM_LOCKED)
mm/mprotect.c +1 -1
index 988c366137d5..912a5847a4f3 100644
@@ -530,7 +530,7 @@ static inline long change_pmd_range(struct mmu_gather *tlb,
 			break;
 		}
 
-		if (pmd_none(*pmd))
+		if (pmd_none(pmdp_get(pmd)))
 			goto next;
 
 		_pmd = pmdp_get_lockless(pmd);
mm/mremap.c +15 -15
index 419a0ea0a870..5b43ef4ff547 100644
@@ -103,7 +103,7 @@ static pmd_t *get_old_pmd(struct mm_struct *mm, unsigned long addr)
 		return NULL;
 
 	pmd = pmd_offset(pud, addr);
-	if (pmd_none(*pmd))
+	if (pmd_none(pmdp_get(pmd)))
 		return NULL;
 
 	return pmd;
@@ -135,7 +135,7 @@ static pmd_t *alloc_new_pmd(struct mm_struct *mm, unsigned long addr)
 	if (!pmd)
 		return NULL;
 
-	VM_BUG_ON(pmd_trans_huge(*pmd));
+	VM_BUG_ON(pmd_trans_huge(pmdp_get(pmd)));
 
 	return pmd;
 }
@@ -260,7 +260,7 @@ static int move_ptes(struct pagetable_move_control *pmc,
 
 	for (; old_addr < old_end; old_ptep += nr_ptes, old_addr += nr_ptes * PAGE_SIZE,
 		new_ptep += nr_ptes, new_addr += nr_ptes * PAGE_SIZE) {
-		VM_WARN_ON_ONCE(!pte_none(*new_ptep));
+		VM_WARN_ON_ONCE(!pte_none(ptep_get(new_ptep)));
 
 		nr_ptes = 1;
 		max_nr_ptes = (old_end - old_addr) >> PAGE_SHIFT;
@@ -379,7 +379,7 @@ static bool move_normal_pmd(struct pagetable_move_control *pmc,
 	 * One alternative might be to just unmap the target pmd at
 	 * this point, and verify that it really is empty. We'll see.
 	 */
-	if (WARN_ON_ONCE(!pmd_none(*new_pmd)))
+	if (WARN_ON_ONCE(!pmd_none(pmdp_get(new_pmd))))
 		return false;
 
 	/*
@@ -391,7 +391,7 @@ static bool move_normal_pmd(struct pagetable_move_control *pmc,
 	if (new_ptl != old_ptl)
 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
 
-	pmd = *old_pmd;
+	pmd = pmdp_get(old_pmd);
 
 	/* Racing with collapse? */
 	if (unlikely(!pmd_present(pmd) || pmd_leaf(pmd)))
@@ -400,7 +400,7 @@ static bool move_normal_pmd(struct pagetable_move_control *pmc,
 	pmd_clear(old_pmd);
 	res = true;
 
-	VM_BUG_ON(!pmd_none(*new_pmd));
+	VM_BUG_ON(!pmd_none(pmdp_get(new_pmd)));
 
 	pmd_populate(mm, new_pmd, pmd_pgtable(pmd));
 	flush_tlb_range(vma, pmc->old_addr, pmc->old_addr + PMD_SIZE);
@@ -436,7 +436,7 @@ static bool move_normal_pud(struct pagetable_move_control *pmc,
 	 * The destination pud shouldn't be established, free_pgtables()
 	 * should have released it.
 	 */
-	if (WARN_ON_ONCE(!pud_none(*new_pud)))
+	if (WARN_ON_ONCE(!pud_none(pudp_get(new_pud))))
 		return false;
 
 	/*
@@ -449,10 +449,10 @@ static bool move_normal_pud(struct pagetable_move_control *pmc,
 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
 
 	/* Clear the pud */
-	pud = *old_pud;
+	pud = pudp_get(old_pud);
 	pud_clear(old_pud);
 
-	VM_BUG_ON(!pud_none(*new_pud));
+	VM_BUG_ON(!pud_none(pudp_get(new_pud)));
 
 	pud_populate(mm, new_pud, pud_pgtable(pud));
 	flush_tlb_range(vma, pmc->old_addr, pmc->old_addr + PUD_SIZE);
@@ -483,7 +483,7 @@ static bool move_huge_pud(struct pagetable_move_control *pmc,
 	 * The destination pud shouldn't be established, free_pgtables()
 	 * should have released it.
 	 */
-	if (WARN_ON_ONCE(!pud_none(*new_pud)))
+	if (WARN_ON_ONCE(!pud_none(pudp_get(new_pud))))
 		return false;
 
 	/*
@@ -496,10 +496,10 @@ static bool move_huge_pud(struct pagetable_move_control *pmc,
 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
 
 	/* Clear the pud */
-	pud = *old_pud;
+	pud = pudp_get(old_pud);
 	pud_clear(old_pud);
 
-	VM_BUG_ON(!pud_none(*new_pud));
+	VM_BUG_ON(!pud_none(pudp_get(new_pud)));
 
 	/* Set the new pud */
 	/* mark soft_ditry when we add pud level soft dirty support */
@@ -828,7 +828,7 @@ unsigned long move_page_tables(struct pagetable_move_control *pmc)
 		new_pud = alloc_new_pud(mm, pmc->new_addr);
 		if (!new_pud)
 			break;
-		if (pud_trans_huge(*old_pud)) {
+		if (pud_trans_huge(pudp_get(old_pud))) {
 			if (extent == HPAGE_PUD_SIZE) {
 				move_pgt_entry(pmc, HPAGE_PUD, old_pud, new_pud);
 				/* We ignore and continue on error? */
@@ -847,7 +847,7 @@ unsigned long move_page_tables(struct pagetable_move_control *pmc)
 		if (!new_pmd)
 			break;
 again:
-		if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {
+		if (is_swap_pmd(pmdp_get(old_pmd)) || pmd_trans_huge(pmdp_get(old_pmd))) {
 			if (extent == HPAGE_PMD_SIZE &&
 			    move_pgt_entry(pmc, HPAGE_PMD, old_pmd, new_pmd))
 				continue;
@@ -861,7 +861,7 @@ unsigned long move_page_tables(struct pagetable_move_control *pmc)
 			if (move_pgt_entry(pmc, NORMAL_PMD, old_pmd, new_pmd))
 				continue;
 		}
-		if (pmd_none(*old_pmd))
+		if (pmd_none(pmdp_get(old_pmd)))
 			continue;
 		if (pte_alloc(pmc->new->vm_mm, new_pmd))
 			break;
mm/page_table_check.c +2 -2
index 4eeca782b888..31f4c39d20ef 100644
@@ -230,7 +230,7 @@ void __page_table_check_pmds_set(struct mm_struct *mm, pmd_t *pmdp, pmd_t pmd,
 	page_table_check_pmd_flags(pmd);
 
 	for (i = 0; i < nr; i++)
-		__page_table_check_pmd_clear(mm, *(pmdp + i));
+		__page_table_check_pmd_clear(mm, pmdp_get(pmdp + i));
 	if (pmd_user_accessible_page(pmd))
 		page_table_check_set(pmd_pfn(pmd), stride * nr, pmd_write(pmd));
 }
@@ -246,7 +246,7 @@ void __page_table_check_puds_set(struct mm_struct *mm, pud_t *pudp, pud_t pud,
 		return;
 
 	for (i = 0; i < nr; i++)
-		__page_table_check_pud_clear(mm, *(pudp + i));
+		__page_table_check_pud_clear(mm, pudp_get((pudp + i)));
 	if (pud_user_accessible_page(pud))
 		page_table_check_set(pud_pfn(pud), stride * nr, pud_write(pud));
 }
mm/page_vma_mapped.c +3 -3
index c498a91b6706..6c08d0215308 100644
@@ -223,17 +223,17 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 restart:
 	do {
 		pgd = pgd_offset(mm, pvmw->address);
-		if (!pgd_present(*pgd)) {
+		if (!pgd_present(pgdp_get(pgd))) {
 			step_forward(pvmw, PGDIR_SIZE);
 			continue;
 		}
 		p4d = p4d_offset(pgd, pvmw->address);
-		if (!p4d_present(*p4d)) {
+		if (!p4d_present(p4dp_get(p4d))) {
 			step_forward(pvmw, P4D_SIZE);
 			continue;
 		}
 		pud = pud_offset(p4d, pvmw->address);
-		if (!pud_present(*pud)) {
+		if (!pud_present(pudp_get(pud))) {
 			step_forward(pvmw, PUD_SIZE);
 			continue;
 		}
mm/pagewalk.c +7 -7
index 9f91cf85a5be..269ba20b63cf 100644
@@ -109,7 +109,7 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
 	do {
 again:
 		next = pmd_addr_end(addr, end);
-		if (pmd_none(*pmd)) {
+		if (pmd_none(pmdp_get(pmd))) {
 			if (has_install)
 				err = __pte_alloc(walk->mm, pmd);
 			else if (ops->pte_hole)
@@ -143,13 +143,13 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
 			 * We are ONLY installing, so avoid unnecessarily
 			 * splitting a present huge page.
 			 */
-			if (pmd_present(*pmd) && pmd_trans_huge(*pmd))
+			if (pmd_present(pmdp_get(pmd)) && pmd_trans_huge(pmdp_get(pmd)))
 				continue;
 		}
 
 		if (walk->vma)
 			split_huge_pmd(walk->vma, pmd, addr);
-		else if (pmd_leaf(*pmd) || !pmd_present(*pmd))
+		else if (pmd_leaf(pmdp_get(pmd)) || !pmd_present(pmdp_get(pmd)))
 			continue; /* Nothing to do. */
 
 		err = walk_pte_range(pmd, addr, next, walk);
@@ -179,7 +179,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
 	do {
  again:
 		next = pud_addr_end(addr, end);
-		if (pud_none(*pud)) {
+		if (pud_none(pudp_get(pud))) {
 			if (has_install)
 				err = __pmd_alloc(walk->mm, pud, addr);
 			else if (ops->pte_hole)
@@ -209,16 +209,16 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
 			 * We are ONLY installing, so avoid unnecessarily
 			 * splitting a present huge page.
 			 */
-			if (pud_present(*pud) && pud_trans_huge(*pud))
+			if (pud_present(pudp_get(pud)) && pud_trans_huge(pudp_get(pud)))
 				continue;
 		}
 
 		if (walk->vma)
 			split_huge_pud(walk->vma, pud, addr);
-		else if (pud_leaf(*pud) || !pud_present(*pud))
+		else if (pud_leaf(pudp_get(pud)) || !pud_present(pudp_get(pud)))
 			continue; /* Nothing to do. */
 
-		if (pud_none(*pud))
+		if (pud_none(pudp_get(pud)))
 			goto again;
 
 		err = walk_pmd_range(pud, addr, next, walk);
mm/percpu.c +4 -4
index 81462ce5866e..1652beb28917 100644
@@ -3136,25 +3136,25 @@ void __init __weak pcpu_populate_pte(unsigned long addr)
 	pud_t *pud;
 	pmd_t *pmd;
 
-	if (pgd_none(*pgd)) {
+	if (pgd_none(pgdp_get(pgd))) {
 		p4d = memblock_alloc_or_panic(P4D_TABLE_SIZE, P4D_TABLE_SIZE);
 		pgd_populate_kernel(addr, pgd, p4d);
 	}
 
 	p4d = p4d_offset(pgd, addr);
-	if (p4d_none(*p4d)) {
+	if (p4d_none(p4dp_get(p4d))) {
 		pud = memblock_alloc_or_panic(PUD_TABLE_SIZE, PUD_TABLE_SIZE);
 		p4d_populate_kernel(addr, p4d, pud);
 	}
 
 	pud = pud_offset(p4d, addr);
-	if (pud_none(*pud)) {
+	if (pud_none(pudp_get(pud))) {
 		pmd = memblock_alloc_or_panic(PMD_TABLE_SIZE, PMD_TABLE_SIZE);
 		pud_populate(&init_mm, pud, pmd);
 	}
 
 	pmd = pmd_offset(pud, addr);
-	if (!pmd_present(*pmd)) {
+	if (!pmd_present(pmdp_get(pmd))) {
 		pte_t *new;
 
 		new = memblock_alloc_or_panic(PTE_TABLE_SIZE, PTE_TABLE_SIZE);
mm/pgalloc-track.h +4 -4
index e9e879de8649..c5bb948416f0 100644
@@ -7,7 +7,7 @@ static inline p4d_t *p4d_alloc_track(struct mm_struct *mm, pgd_t *pgd,
 				     unsigned long address,
 				     pgtbl_mod_mask *mod_mask)
 {
-	if (unlikely(pgd_none(*pgd))) {
+	if (unlikely(pgd_none(pgdp_get(pgd)))) {
 		if (__p4d_alloc(mm, pgd, address))
 			return NULL;
 		*mod_mask |= PGTBL_PGD_MODIFIED;
@@ -20,7 +20,7 @@ static inline pud_t *pud_alloc_track(struct mm_struct *mm, p4d_t *p4d,
 				     unsigned long address,
 				     pgtbl_mod_mask *mod_mask)
 {
-	if (unlikely(p4d_none(*p4d))) {
+	if (unlikely(p4d_none(p4dp_get(p4d)))) {
 		if (__pud_alloc(mm, p4d, address))
 			return NULL;
 		*mod_mask |= PGTBL_P4D_MODIFIED;
@@ -33,7 +33,7 @@ static inline pmd_t *pmd_alloc_track(struct mm_struct *mm, pud_t *pud,
 				     unsigned long address,
 				     pgtbl_mod_mask *mod_mask)
 {
-	if (unlikely(pud_none(*pud))) {
+	if (unlikely(pud_none(pudp_get(pud)))) {
 		if (__pmd_alloc(mm, pud, address))
 			return NULL;
 		*mod_mask |= PGTBL_PUD_MODIFIED;
@@ -44,7 +44,7 @@ static inline pmd_t *pmd_alloc_track(struct mm_struct *mm, pud_t *pud,
 #endif /* CONFIG_MMU */
 
 #define pte_alloc_kernel_track(pmd, address, mask)			\
-	((unlikely(pmd_none(*(pmd))) &&					\
+	((unlikely(pmd_none(pmdp_get(pmd))) &&				\
 	  (__pte_alloc_kernel(pmd) || ({*(mask)|=PGTBL_PMD_MODIFIED;0;})))?\
 		NULL: pte_offset_kernel(pmd, address))
 
mm/pgtable-generic.c +12 -11
index 567e2d084071..63a573306bfa 100644
@@ -24,14 +24,14 @@
 
 void pgd_clear_bad(pgd_t *pgd)
 {
-	pgd_ERROR(*pgd);
+	pgd_ERROR(pgdp_get(pgd));
 	pgd_clear(pgd);
 }
 
 #ifndef __PAGETABLE_P4D_FOLDED
 void p4d_clear_bad(p4d_t *p4d)
 {
-	p4d_ERROR(*p4d);
+	p4d_ERROR(p4dp_get(p4d));
 	p4d_clear(p4d);
 }
 #endif
@@ -39,7 +39,7 @@ void p4d_clear_bad(p4d_t *p4d)
 #ifndef __PAGETABLE_PUD_FOLDED
 void pud_clear_bad(pud_t *pud)
 {
-	pud_ERROR(*pud);
+	pud_ERROR(pudp_get(pud));
 	pud_clear(pud);
 }
 #endif
@@ -51,7 +51,7 @@ void pud_clear_bad(pud_t *pud)
  */
 void pmd_clear_bad(pmd_t *pmd)
 {
-	pmd_ERROR(*pmd);
+	pmd_ERROR(pmdp_get(pmd));
 	pmd_clear(pmd);
 }
 
@@ -110,7 +110,7 @@ int pmdp_set_access_flags(struct vm_area_struct *vma,
 			  unsigned long address, pmd_t *pmdp,
 			  pmd_t entry, int dirty)
 {
-	int changed = !pmd_same(*pmdp, entry);
+	int changed = !pmd_same(pmdp_get(pmdp), entry);
 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
 	if (changed) {
 		set_pmd_at(vma->vm_mm, address, pmdp, entry);
@@ -139,7 +139,7 @@ pmd_t pmdp_huge_clear_flush(struct vm_area_struct *vma, unsigned long address,
 {
 	pmd_t pmd;
 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
-	VM_BUG_ON(pmd_present(*pmdp) && !pmd_trans_huge(*pmdp));
+	VM_BUG_ON(pmd_present(pmdp_get(pmdp)) && !pmd_trans_huge(pmdp_get(pmdp)));
 	pmd = pmdp_huge_get_and_clear(vma->vm_mm, address, pmdp);
 	flush_pmd_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
 	return pmd;
@@ -152,7 +152,7 @@ pud_t pudp_huge_clear_flush(struct vm_area_struct *vma, unsigned long address,
 	pud_t pud;
 
 	VM_BUG_ON(address & ~HPAGE_PUD_MASK);
-	VM_BUG_ON(!pud_trans_huge(*pudp));
+	VM_BUG_ON(!pud_trans_huge(pudp_get(pudp)));
 	pud = pudp_huge_get_and_clear(vma->vm_mm, address, pudp);
 	flush_pud_tlb_range(vma, address, address + HPAGE_PUD_SIZE);
 	return pud;
@@ -197,8 +197,9 @@ pgtable_t pgtable_trans_huge_withdraw(struct mm_struct *mm, pmd_t *pmdp)
 pmd_t pmdp_invalidate(struct vm_area_struct *vma, unsigned long address,
 		     pmd_t *pmdp)
 {
-	VM_WARN_ON_ONCE(!pmd_present(*pmdp));
-	pmd_t old = pmdp_establish(vma, address, pmdp, pmd_mkinvalid(*pmdp));
+	VM_WARN_ON_ONCE(!pmd_present(pmdp_get(pmdp)));
+	pmd_t old = pmdp_establish(vma, address, pmdp,
+				   pmd_mkinvalid(pmdp_get(pmdp)));
 	flush_pmd_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
 	return old;
 }
@@ -208,7 +209,7 @@ pmd_t pmdp_invalidate(struct vm_area_struct *vma, unsigned long address,
 pmd_t pmdp_invalidate_ad(struct vm_area_struct *vma, unsigned long address,
 			 pmd_t *pmdp)
 {
-	VM_WARN_ON_ONCE(!pmd_present(*pmdp));
+	VM_WARN_ON_ONCE(!pmd_present(pmdp_get(pmdp)));
 	return pmdp_invalidate(vma, address, pmdp);
 }
 #endif
@@ -224,7 +225,7 @@ pmd_t pmdp_collapse_flush(struct vm_area_struct *vma, unsigned long address,
 	pmd_t pmd;
 
 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
-	VM_BUG_ON(pmd_trans_huge(*pmdp));
+	VM_BUG_ON(pmd_trans_huge(pmdp_get(pmdp)));
 	pmd = pmdp_huge_get_and_clear(vma->vm_mm, address, pmdp);
 
 	/* collapse entails shooting down ptes not pmd */
mm/rmap.c +4 -4
index ac4f783d6ec2..aafefc1d7955 100644
@@ -819,15 +819,15 @@ pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
 	pmd_t *pmd = NULL;
 
 	pgd = pgd_offset(mm, address);
-	if (!pgd_present(*pgd))
+	if (!pgd_present(pgdp_get(pgd)))
 		goto out;
 
 	p4d = p4d_offset(pgd, address);
-	if (!p4d_present(*p4d))
+	if (!p4d_present(p4dp_get(p4d)))
 		goto out;
 
 	pud = pud_offset(p4d, address);
-	if (!pud_present(*pud))
+	if (!pud_present(pudp_get(pud)))
 		goto out;
 
 	pmd = pmd_offset(pud, address);
@@ -1048,7 +1048,7 @@ static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
 			pmd_t *pmd = pvmw->pmd;
 			pmd_t entry;
 
-			if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
+			if (!pmd_dirty(pmdp_get(pmd)) && !pmd_write(pmdp_get(pmd)))
 				continue;
 
 			flush_cache_range(vma, address,
mm/sparse-vmemmap.c +4 -4
index 37522d6cb398..be065c57611d 100644
@@ -198,7 +198,7 @@ static void * __meminit vmemmap_alloc_block_zero(unsigned long size, int node)
 pmd_t * __meminit vmemmap_pmd_populate(pud_t *pud, unsigned long addr, int node)
 {
 	pmd_t *pmd = pmd_offset(pud, addr);
-	if (pmd_none(*pmd)) {
+	if (pmd_none(pmdp_get(pmd))) {
 		void *p = vmemmap_alloc_block_zero(PAGE_SIZE, node);
 		if (!p)
 			return NULL;
@@ -211,7 +211,7 @@ pmd_t * __meminit vmemmap_pmd_populate(pud_t *pud, unsigned long addr, int node)
 pud_t * __meminit vmemmap_pud_populate(p4d_t *p4d, unsigned long addr, int node)
 {
 	pud_t *pud = pud_offset(p4d, addr);
-	if (pud_none(*pud)) {
+	if (pud_none(pudp_get(pud))) {
 		void *p = vmemmap_alloc_block_zero(PAGE_SIZE, node);
 		if (!p)
 			return NULL;
@@ -224,7 +224,7 @@ pud_t * __meminit vmemmap_pud_populate(p4d_t *p4d, unsigned long addr, int node)
 p4d_t * __meminit vmemmap_p4d_populate(pgd_t *pgd, unsigned long addr, int node)
 {
 	p4d_t *p4d = p4d_offset(pgd, addr);
-	if (p4d_none(*p4d)) {
+	if (p4d_none(p4dp_get(p4d))) {
 		void *p = vmemmap_alloc_block_zero(PAGE_SIZE, node);
 		if (!p)
 			return NULL;
@@ -237,7 +237,7 @@ p4d_t * __meminit vmemmap_p4d_populate(pgd_t *pgd, unsigned long addr, int node)
 pgd_t * __meminit vmemmap_pgd_populate(unsigned long addr, int node)
 {
 	pgd_t *pgd = pgd_offset_k(addr);
-	if (pgd_none(*pgd)) {
+	if (pgd_none(pgdp_get(pgd))) {
 		void *p = vmemmap_alloc_block_zero(PAGE_SIZE, node);
 		if (!p)
 			return NULL;
mm/userfaultfd.c +5 -5
index af61b95c89e4..931c26914ef5 100644
@@ -1306,8 +1306,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd
 	}
 
 	/* Sanity checks before the operation */
-	if (pmd_none(*dst_pmd) || pmd_none(*src_pmd) ||
-	    pmd_trans_huge(*dst_pmd) || pmd_trans_huge(*src_pmd)) {
+	if (pmd_none(pmdp_get(dst_pmd)) || pmd_none(pmdp_get(src_pmd)) ||
+	    pmd_trans_huge(pmdp_get(dst_pmd)) || pmd_trans_huge(pmdp_get(src_pmd))) {
 		ret = -EINVAL;
 		goto out;
 	}
@@ -1897,8 +1897,8 @@ ssize_t move_pages(struct userfaultfd_ctx *ctx, unsigned long dst_start,
 			if (move_splits_huge_pmd(dst_addr, src_addr, src_start + len) ||
 			    !pmd_none(dst_pmdval)) {
 				/* Can be a migration entry */
-				if (pmd_present(*src_pmd)) {
-					struct folio *folio = pmd_folio(*src_pmd);
+				if (pmd_present(pmdp_get(src_pmd))) {
+					struct folio *folio = pmd_folio(pmdp_get(src_pmd));
 
 					if (!is_huge_zero_folio(folio) &&
 					    !PageAnonExclusive(&folio->page)) {
@@ -1921,7 +1921,7 @@ ssize_t move_pages(struct userfaultfd_ctx *ctx, unsigned long dst_start,
 		} else {
 			long ret;
 
-			if (pmd_none(*src_pmd)) {
+			if (pmd_none(pmdp_get(src_pmd))) {
 				if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
 					err = -ENOENT;
 					break;
mm/vmalloc.c +25 -24

123 lines not on this page · raw message

mm/vmscan.c +7 -7
index 2239de111fa6..4401d20548e0 100644
@@ -3612,7 +3612,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area
 	DEFINE_MAX_SEQ(walk->lruvec);
 	int gen = lru_gen_from_seq(max_seq);
 
-	VM_WARN_ON_ONCE(pud_leaf(*pud));
+	VM_WARN_ON_ONCE(pud_leaf(pudp_get(pud)));
 
 	/* try to batch at most 1+MIN_LRU_BATCH+1 entries */
 	if (*first == -1) {
@@ -3642,17 +3642,17 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area
 		/* don't round down the first address */
 		addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
 
-		if (!pmd_present(pmd[i]))
+		if (!pmd_present(pmdp_get(pmd + i)))
 			goto next;
 
-		if (!pmd_trans_huge(pmd[i])) {
+		if (!pmd_trans_huge(pmdp_get(pmd + i))) {
 			if (!walk->force_scan && should_clear_pmd_young() &&
 			    !mm_has_notifiers(args->mm))
 				pmdp_test_and_clear_young(vma, addr, pmd + i);
 			goto next;
 		}
 
-		pfn = get_pmd_pfn(pmd[i], vma, addr, pgdat);
+		pfn = get_pmd_pfn(pmdp_get(pmd + i), vma, addr, pgdat);
 		if (pfn == -1)
 			goto next;
 
@@ -3670,7 +3670,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area
 			dirty = false;
 		}
 
-		if (pmd_dirty(pmd[i]))
+		if (pmd_dirty(pmdp_get(pmd + i)))
 			dirty = true;
 
 		walk->mm_stats[MM_LEAF_YOUNG]++;
@@ -3699,7 +3699,7 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 	struct lru_gen_mm_walk *walk = args->private;
 	struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
 
-	VM_WARN_ON_ONCE(pud_leaf(*pud));
+	VM_WARN_ON_ONCE(pud_leaf(pudp_get(pud)));
 
 	/*
 	 * Finish an entire PMD in two passes: the first only reaches to PTE
@@ -3768,7 +3768,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 	unsigned long next;
 	struct lru_gen_mm_walk *walk = args->private;
 
-	VM_WARN_ON_ONCE(p4d_leaf(*p4d));
+	VM_WARN_ON_ONCE(p4d_leaf(p4dp_get(p4d)));
 
 	pud = pud_offset(p4d, start & P4D_MASK);
 restart:
Signature · 1 line
2.47.2
#10 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

kernel test robot noticed the following build errors:

Hi Samuel,

kernel test robot noticed the following build errors:

[auto build test ERROR on 24172e0d79900908cf5ebf366600616d29c9b417]

url:    https://github.com/intel-lab-lkp/linux/commits/Samuel-Holland/mm-ptdump-replace-READ_ONCE-with-standard-page-table-accessors/20251113-095117
base:   24172e0d79900908cf5ebf366600616d29c9b417
patch link:    https://lore.kernel.org/r/20251113014656.2605447-7-samuel.holland%40sifive.com
patch subject: [PATCH v3 06/22] mm: Always use page table accessor functions
config: x86_64-allnoconfig (https://download.01.org/0day-ci/archive/20251113/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251113/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> mm/pgtable-generic.c:27:2: error: cannot take the address of an rvalue of type 'pgd_t'
      27 |         pgd_ERROR(pgdp_get(pgd));
         |         ^         ~~~~~~~~~~~~~
   arch/x86/include/asm/pgtable_64.h:50:29: note: expanded from macro 'pgd_ERROR'
      50 |                __FILE__, __LINE__, &(e), pgd_val(e))
         |                                    ^ ~
   include/linux/printk.h:555:33: note: expanded from macro 'pr_err'
     555 |         printk(KERN_ERR pr_fmt(fmt), ##__VA_ARGS__)
         |                                        ^~~~~~~~~~~
   include/linux/printk.h:512:60: note: expanded from macro 'printk'
     512 | #define printk(fmt, ...) printk_index_wrap(_printk, fmt, ##__VA_ARGS__)
         |                                                            ^~~~~~~~~~~
   include/linux/printk.h:484:19: note: expanded from macro 'printk_index_wrap'
     484 |                 _p_func(_fmt, ##__VA_ARGS__);                           \
         |                                 ^~~~~~~~~~~
>> mm/pgtable-generic.c:34:2: error: cannot take the address of an rvalue of type 'p4d_t'
      34 |         p4d_ERROR(p4dp_get(p4d));
         |         ^         ~~~~~~~~~~~~~
   arch/x86/include/asm/pgtable_64.h:46:29: note: expanded from macro 'p4d_ERROR'
      46 |                __FILE__, __LINE__, &(e), p4d_val(e))
         |                                    ^ ~
   include/linux/printk.h:555:33: note: expanded from macro 'pr_err'
     555 |         printk(KERN_ERR pr_fmt(fmt), ##__VA_ARGS__)
         |                                        ^~~~~~~~~~~
   include/linux/printk.h:512:60: note: expanded from macro 'printk'
     512 | #define printk(fmt, ...) printk_index_wrap(_printk, fmt, ##__VA_ARGS__)
         |                                                            ^~~~~~~~~~~
   include/linux/printk.h:484:19: note: expanded from macro 'printk_index_wrap'
     484 |                 _p_func(_fmt, ##__VA_ARGS__);                           \
         |                                 ^~~~~~~~~~~
>> mm/pgtable-generic.c:42:2: error: cannot take the address of an rvalue of type 'pud_t'
      42 |         pud_ERROR(pudp_get(pud));
         |         ^         ~~~~~~~~~~~~~
   arch/x86/include/asm/pgtable_64.h:42:29: note: expanded from macro 'pud_ERROR'
      42 |                __FILE__, __LINE__, &(e), pud_val(e))
         |                                    ^ ~
   include/linux/printk.h:555:33: note: expanded from macro 'pr_err'
     555 |         printk(KERN_ERR pr_fmt(fmt), ##__VA_ARGS__)
         |                                        ^~~~~~~~~~~
   include/linux/printk.h:512:60: note: expanded from macro 'printk'
     512 | #define printk(fmt, ...) printk_index_wrap(_printk, fmt, ##__VA_ARGS__)
         |                                                            ^~~~~~~~~~~
   include/linux/printk.h:484:19: note: expanded from macro 'printk_index_wrap'
     484 |                 _p_func(_fmt, ##__VA_ARGS__);                           \
         |                                 ^~~~~~~~~~~
>> mm/pgtable-generic.c:54:2: error: cannot take the address of an rvalue of type 'pmd_t'
      54 |         pmd_ERROR(pmdp_get(pmd));
         |         ^         ~~~~~~~~~~~~~
   arch/x86/include/asm/pgtable_64.h:39:29: note: expanded from macro 'pmd_ERROR'
      39 |                __FILE__, __LINE__, &(e), pmd_val(e))
         |                                    ^ ~
   include/linux/printk.h:555:33: note: expanded from macro 'pr_err'
     555 |         printk(KERN_ERR pr_fmt(fmt), ##__VA_ARGS__)
         |                                        ^~~~~~~~~~~
   include/linux/printk.h:512:60: note: expanded from macro 'printk'
     512 | #define printk(fmt, ...) printk_index_wrap(_printk, fmt, ##__VA_ARGS__)
         |                                                            ^~~~~~~~~~~
   include/linux/printk.h:484:19: note: expanded from macro 'printk_index_wrap'
     484 |                 _p_func(_fmt, ##__VA_ARGS__);                           \
         |                                 ^~~~~~~~~~~

4 errors generated.

vim +/pgd_t +27 mm/pgtable-generic.c

    18	
    19	/*
    20	 * If a p?d_bad entry is found while walking page tables, report
    21	 * the error, before resetting entry to p?d_none.  Usually (but
    22	 * very seldom) called out from the p?d_none_or_clear_bad macros.
    23	 */
    24	
    25	void pgd_clear_bad(pgd_t *pgd)
    26	{
  > 27		pgd_ERROR(pgdp_get(pgd));
    28		pgd_clear(pgd);
    29	}
    30	
    31	#ifndef __PAGETABLE_P4D_FOLDED
    32	void p4d_clear_bad(p4d_t *p4d)
    33	{
  > 34		p4d_ERROR(p4dp_get(p4d));
    35		p4d_clear(p4d);
    36	}
    37	#endif
    38	
    39	#ifndef __PAGETABLE_PUD_FOLDED
    40	void pud_clear_bad(pud_t *pud)
    41	{
  > 42		pud_ERROR(pudp_get(pud));
    43		pud_clear(pud);
    44	}
    45	#endif
    46	
    47	/*
    48	 * Note that the pmd variant below can't be stub'ed out just as for p4d/pud
    49	 * above. pmd folding is special and typically pmd_* macros refer to upper
    50	 * level even when folded
    51	 */
    52	void pmd_clear_bad(pmd_t *pmd)
    53	{
  > 54		pmd_ERROR(pmdp_get(pmd));
    55		pmd_clear(pmd);
    56	}
    57	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#11 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Samuel Holland
kernel test robot noticed the following build errors:

Hi Samuel,

kernel test robot noticed the following build errors:

[auto build test ERROR on 24172e0d79900908cf5ebf366600616d29c9b417]

url:    https://github.com/intel-lab-lkp/linux/commits/Samuel-Holland/mm-ptdump-replace-READ_ONCE-with-standard-page-table-accessors/20251113-095117
base:   24172e0d79900908cf5ebf366600616d29c9b417
patch link:    https://lore.kernel.org/r/20251113014656.2605447-7-samuel.holland%40sifive.com
patch subject: [PATCH v3 06/22] mm: Always use page table accessor functions
config: powerpc-allnoconfig (https://download.01.org/0day-ci/archive/20251113/[email protected]/config)
compiler: powerpc-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251113/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

mm/madvise.c: In function 'guard_install_set_pte':

>> mm/madvise.c:1119:9: error: implicit declaration of function 'set_pte'; did you mean 'set_ptes'? [-Wimplicit-function-declaration]
    1119 |         set_pte(ptep, make_pte_marker(PTE_MARKER_GUARD));
         |         ^~~~~~~
         |         set_ptes

vim +1119 mm/madvise.c

1112
1113 static int guard_install_set_pte(unsigned long addr, unsigned long next,
1114 pte_t *ptep, struct mm_walk *walk)
1115 {
1116 unsigned long *nr_pages = (unsigned long *)walk->private;
1117
1118 /* Simply install a PTE marker, this causes segfault on access. */

> 1119		set_pte(ptep, make_pte_marker(PTE_MARKER_GUARD));

1120 (*nr_pages)++;
1121
1122 return 0;
1123 }
1124

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#12 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Samuel Holland

Le 13/11/2025 à 02:45, Samuel Holland a écrit :

Quoted 16 lines

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

...

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

And this commit has the same problem as the series from Anshuman, see [2]:

Before the patch, as an exemple on powerpc/32 mm_find_pmd() was:

00001860 <mm_find_pmd>:

    1860:       80 63 00 18     lwz     r3,24(r3)
    1864:       54 84 65 3a     rlwinm  r4,r4,12,20,29
    1868:       7c 63 22 14     add     r3,r3,r4
    186c:       4e 80 00 20     blr

Now it is:

00001860 <mm_find_pmd>:

    1860:       81 23 00 18     lwz     r9,24(r3)
    1864:       54 84 65 3a     rlwinm  r4,r4,12,20,29
    1868:       7d 49 20 2e     lwzx    r10,r9,r4  <== Pointless read
    186c:       7c 69 22 14     add     r3,r9,r4
    1870:       7d 49 20 2e     lwzx    r10,r9,r4  <== Pointless read
    1874:       7d 29 20 2e     lwzx    r9,r9,r4   <== Pointless read
    1878:       4e 80 00 20     blr

To avoid it you need something like:

mm/rmap.c +3 -3
index aafefc1d7955..0c61153f4ea9 100644
@@ -819,15 +819,15 @@ pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
 	pmd_t *pmd = NULL;
 
 	pgd = pgd_offset(mm, address);
-	if (!pgd_present(pgdp_get(pgd)))
+	if (!mm_p4d_folded(mm) && !pgd_present(pgdp_get(pgd)))
 		goto out;
 
 	p4d = p4d_offset(pgd, address);
-	if (!p4d_present(p4dp_get(p4d)))
+	if (!mm_pud_folded(mm) && !p4d_present(p4dp_get(p4d)))
 		goto out;
 
 	pud = pud_offset(p4d, address);
-	if (!pud_present(pudp_get(pud)))
+	if (!mm_pmd_folded(mm) && !pud_present(pudp_get(pud)))
 		goto out;
 
 	pmd = pmd_offset(pud, address);

[2] https://lore.kernel.org/linux-mm/[email protected]/

Quoted 3 lines

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Christophe

reviewer
#13 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Samuel Holland
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(
&P[I]
|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 28 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

The main issue is that the compiler was unable to optimize away the READ_ONCE()s for the case where certain levels of the pgtable are folded. But it can optimize the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant) loads.

Were you able to solve this problem?

I think it stems from there really being 2 types of access; READ_ONCE() and plain C dereference. The existing READ_ONCE() accesses require the single-copy-atomic guarantees but the plain c dereferences don't actually need that; they are usually just checking "is the value the same as a value I previously read?", "is the pXd none?", etc. so it doesn't matter if they get torn.

It would be nice to have only a single flavour of accessor, but in that case it obviously needs to be the strongest (READ_ONCE()). Perhaps we should settle for 2 flavours, and the compiler should then be able to continue to optimize out the c dereferences. There are already 2 flavours for pte (which never gets folded); ptep_get() and ptep_get_lockless(), but the semantics don't quite match.

Perhaps:

pXdp_get() -> READ_ONCE()
pXdp_get_weak() -> c dereference?

or pXdp_deref()? I'm not great with names...

The other problem is that there is nothing preventing new code from introducing new direct dereferences or READ_ONCE()s. One possible solution to this is to use an opaque handle type (similar to what I described above with pte_handle_t). But that introduces a lot more code churn. I think that's a nice-to-have/incremental improvement that could be done later.

Quoted 46 lines

Changes in v3:
- Rebased on top of torvalds/master (v6.18-rc5+)

Changes in v2:
- New patch for v2

 fs/dax.c                |  4 +-
 fs/proc/task_mmu.c      | 27 +++++++------
 fs/userfaultfd.c        |  6 +--
 include/linux/huge_mm.h |  8 ++--
 include/linux/mm.h      | 14 +++----
 include/linux/pgtable.h | 42 +++++++++----------
 mm/damon/vaddr.c        |  2 +-
 mm/debug_vm_pgtable.c   |  4 +-
 mm/filemap.c            |  6 +--
 mm/gup.c                | 24 +++++------
 mm/huge_memory.c        | 90 ++++++++++++++++++++---------------------
 mm/hugetlb.c            | 10 ++---
 mm/hugetlb_vmemmap.c    |  4 +-
 mm/kasan/init.c         | 39 +++++++++---------
 mm/kasan/shadow.c       | 12 +++---
 mm/khugepaged.c         |  4 +-
 mm/ksm.c                |  2 +-
 mm/madvise.c            |  8 ++--
 mm/memory-failure.c     | 14 +++----
 mm/memory.c             | 76 +++++++++++++++++-----------------
 mm/mempolicy.c          |  4 +-
 mm/migrate.c            |  4 +-
 mm/migrate_device.c     | 10 ++---
 mm/mlock.c              |  6 +--
 mm/mprotect.c           |  2 +-
 mm/mremap.c             | 30 +++++++-------
 mm/page_table_check.c   |  4 +-
 mm/page_vma_mapped.c    |  6 +--
 mm/pagewalk.c           | 14 +++----
 mm/percpu.c             |  8 ++--
 mm/pgalloc-track.h      |  8 ++--
 mm/pgtable-generic.c    | 23 ++++++-----
 mm/rmap.c               |  8 ++--
 mm/sparse-vmemmap.c     |  8 ++--
 mm/userfaultfd.c        | 10 ++---
 mm/vmalloc.c            | 49 +++++++++++-----------
 mm/vmscan.c             | 14 +++----
 37 files changed, 304 insertions(+), 300 deletions(-)

[...]

mm/ksm.c static int write_protect_page(struct vm_area_struct *vma, struct folio *folio, · line 1325

Quoted 8 lines
mm/ksm.c +1 -1
@@ -1322,7 +1322,7 @@ static int write_protect_page(struct vm_area_struct *vma, struct folio *folio,
 
 		set_pte_at(mm, pvmw.address, pvmw.pte, entry);
 	}
-	*orig_pte = entry;
+	set_pte(orig_pte, entry);

This is incorrect. orig_pte points to a location on stack. Please revert.

Quoted 3 lines
mm/ksm.c +0 -0
 	err = 0;
 
 out_unlock:

[...]

mm/ksm.c static int guard_install_set_pte(unsigned long addr, unsigned long next, · line 1119

Quoted 6 lines
mm/ksm.c +1 -1
@@ -1116,7 +1116,7 @@ static int guard_install_set_pte(unsigned long addr, unsigned long next,
 	unsigned long *nr_pages = (unsigned long *)walk->private;
 
 	/* Simply install a PTE marker, this causes segfault on access. */
-	*ptep = make_pte_marker(PTE_MARKER_GUARD);
+	set_pte(ptep, make_pte_marker(PTE_MARKER_GUARD));

I tried "fixing" this before. But it's correct as is. ptep is pointing to a value on the stack. See [2].

https://lore.kernel.org/linux-mm/[email protected]/

mm/ksm.c static int guard_install_set_pte(unsigned long addr, unsigned long next, · line 1120

Quoted 1 line
mm/ksm.c +0 -0
 	(*nr_pages)++;

[...]

It's all very difficult to review at the moment since it is so big. Any chance of at least splitting by level in future versions?

Thanks,
Ryan

#14 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 129 lines · Ryan Roberts
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(
&P[I]
|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 28 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 6 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s for the case where certain levels of the pgtable are folded. But it can optimize the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant) loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Signature · 3 lines
Cheers

David
#15 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 137 lines · David Hildenbrand (Red Hat)
Quoted 129 lines · Ryan Roberts
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(

    &P[I]

|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 28 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 6 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s for the case where certain levels of the pgtable are folded. But it can optimize the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant) loads.

Quoted 3 lines

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Signature · 3 lines
Cheers

David
#16 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 142 lines · David Hildenbrand (Red Hat)
Quoted 137 lines · David Hildenbrand (Red Hat)
Quoted 129 lines · Ryan Roberts
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(

    &P[I]

|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 28 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 6 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s for the case where certain levels of the pgtable are folded. But it can optimize the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant) loads.

Quoted 3 lines

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

And we're now modifying how we do things for ppc32 specifically? Or are there arches with fewer cobwebs on them that are actually impacted here?

Is it really necessary to do this?

And obv. that doesn't address the READ_ONCE() vs. not READ_ONCE() stuff, plus then we have to do it for every arch no?

Quoted 5 lines

--
Cheers

David

Cheers, Lorenzo

#17 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 143 lines · Lorenzo Stoakes
Quoted 142 lines · David Hildenbrand (Red Hat)
Quoted 140 lines · David Hildenbrand (Red Hat)
Quoted 129 lines · Ryan Roberts
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(

     &P[I]

|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 28 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

Quoted 8 lines

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 6 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s for the case where certain levels of the pgtable are folded. But it can optimize the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant) loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 8 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

If we could adjust generic pgdp_get() and friends to not do a READ_ONCE() once folded we might not have to think about that in the callers.

Just an idea, though, not sure if that would fly the way I envision it.

Signature · 3 lines
Cheers

David
reviewer
#18 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 154 lines · David Hildenbrand (Red Hat)
Quoted 153 lines · Lorenzo Stoakes
Quoted 152 lines · David Hildenbrand (Red Hat)
Quoted 150 lines · David Hildenbrand (Red Hat)
Quoted 136 lines · Ryan Roberts
Quoted 24 lines · Samuel Holland

Some platforms need to fix up the values when reading or writing page tables. Because of this, the accessors must always be used; it is not valid to simply dereference a pXX_t pointer.

Fix all of the instances of this pattern in generic code, mostly by applying the below coccinelle semantic patch, repeated for each page table level. Some additional fixes were applied manually, mostly to macros where type information is unavailable.

In a few places, a pte_t * or pmd_t * is actually a pointer to a PTE or PMDE value stored on the stack, not a pointer to a page table. In those cases, it is not appropriate to use the accessors, because the value is not globally visible, and any transformation from pXXp_get() has already been applied. Those places are marked by naming the pointer ptentp or pmdvalp, as opposed to ptep or pmdp.

@@
pte_t *P;
expression E;
expression I;
@@
- P[I] = E
+ set_pte(P + I, E)

Quoted 11 lines

@@
pte_t *P;
expression E;
@@
(
- WRITE_ONCE(*P, E)
+ set_pte(P, E)
|
- *P = E
+ set_pte(P, E)
)

There should absolutely never be any instances of core code directly setting an
entry at any level. This *must* always go via the arch code helpers. Did you find any instances of this? If so, I would consider these bugs and suggest sending as a separate bugfix patch. Bad things could happen on arm64 because we
may need to break a contiguous mapping, which would not happen if the value is set directly.

Quoted 15 lines

@@
pte_t *P;
expression I;
@@
(
     &P[I]
|
- READ_ONCE(P[I])
+ ptep_get(P + I)
|
- P[I]
+ ptep_get(P + I)
)

Quoted 10 lines

@@
pte_t *P;
@@
(
- READ_ONCE(*P)
+ ptep_get(P)
|
- *P
+ ptep_get(P)
)

For reading the *PTE*, conversion over to ptep_get() should have already been done (I did this a few years back when implementing support for arm64 contiguous
mappings). If you find any cases where direct dereference or READ_ONCE() is being done in generic code for PTE, then that's a bug and should also be sent as
a separate patch.

FYI, my experience was that Coccinelle didn't find everything when I was converting to ptep_get() - although it could have been that my Cochinelle skills
were not up to scratch! I ended up using an additional method where I did a find/replace to convert "pte_t *" to "ptep_handle_t" and declared pte_handle_t as a void* which causes a compiler error on dereference. Then in a few key places I did a manual case from pte_handle_t to (pte_t *) and compiled allyesconfig.

I'm assuming the above Cocchinelle template was also used for pmd_t, pud_t, p4d_t and pgd_t?

Quoted 35 lines

Additionally, the following semantic patch was used to convert PMD and PUD references inside struct vm_fault:

@@
struct vm_fault vmf;
@@
(
- *vmf.pmd
+ pmdp_get(vmf.pmd)
|
- *vmf.pud
+ pudp_get(vmf.pud)
)

@@
struct vm_fault *vmf;
@@
(
- *vmf->pmd
+ pmdp_get(vmf->pmd)
|
- *vmf->pud
+ pudp_get(vmf->pud)
)

---
This commit covers some of the same changes as an existing series from Anshuman Khandual[1]. Unlike that series, this commit is a purely mechanical conversion to demonstrate the RISC-V changes, so it does not insert local variables to avoid redundant calls to the accessors. A manual conversion like in that series could improve performance.

Quoted 2 lines

[1]: https://lore.kernel.org/linux-mm/20240917073117.1531207-1-
[email protected]/

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

Quoted 3 lines
Quoted 3 lines

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

Agreed, but if we can put it inside the default helper implementation, that solves it, I think? An arch has to be careful if they are overriding the defaults, but it's still well contained.

Quoted 5 lines

If we could adjust generic pgdp_get() and friends to not do a READ_ONCE() once folded we might not have to think about that in the callers.

Just an idea, though, not sure if that would fly the way I envision it.

#19 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Quoted 15 lines
Quoted 3 lines
Quoted 3 lines

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

Agreed, but if we can put it inside the default helper implementation, that solves it, I think? An arch has to be careful if they are overriding the defaults, but it's still well contained.

Quoted 5 lines

If we could adjust generic pgdp_get() and friends to not do a READ_ONCE() once folded we might not have to think about that in the callers.

Just an idea, though, not sure if that would fly the way I envision it.

Signature · 2 lines
Wei Yang
Help you, Help me
reviewer
#20 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Yes. But I'm not convinced it's correct.

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

So I don't think it works.

Probably we either have to live with the extra loads or have 2 types of helper.

Quoted 17 lines
Quoted 16 lines
Quoted 4 lines
Quoted 4 lines

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

Agreed, but if we can put it inside the default helper implementation, that solves it, I think? An arch has to be careful if they are overriding the defaults, but it's still well contained.

Quoted 5 lines

If we could adjust generic pgdp_get() and friends to not do a READ_ONCE() once folded we might not have to think about that in the callers.

Just an idea, though, not sure if that would fly the way I envision it.

#21 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 53 lines · Ryan Roberts
Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Yes. But I'm not convinced it's correct.

Quoted 8 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

Yeah, it kinda sucks to bake that assumption in too even if we can prove it currently _is_ correct, and it becomes tricky because to somebody observing this they might well think 'oh so we don't need to think about tearing here' but in reality we are just assuming somebody already thought about it for us :)

Quoted 4 lines

So I don't think it works.

Probably we either have to live with the extra loads or have 2 types of helper.

RoI on arches where we fold PMD maybe make it not such a big problem?

If not then 2 function solution seems the right way.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 5 lines
Quoted 5 lines

I find that kind of gross to be honest. Isn't the whole point of folding that we don't have to think about it...

Agreed, but if we can put it inside the default helper implementation, that solves it, I think? An arch has to be careful if they are overriding the defaults, but it's still well contained.

Quoted 1 line
Quoted 8 lines
Quoted 7 lines
Quoted 6 lines
Quoted 4 lines

If we could adjust generic pgdp_get() and friends to not do a READ_ONCE() once folded we might not have to think about that in the callers.

Just an idea, though, not sure if that would fly the way I envision it.

Yup obviously if we _could_ find a way to bury this down then sure. But having actual page table walkers have to think about this is a no-go IMO.

Cheers, Lorenzo

#22 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 63 lines · Lorenzo Stoakes
Quoted 53 lines · Ryan Roberts
Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Yes. But I'm not convinced it's correct.

Quoted 8 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

Quoted 4 lines

Yeah, it kinda sucks to bake that assumption in too even if we can prove it currently _is_ correct, and it becomes tricky because to somebody observing this they might well think 'oh so we don't need to think about tearing here' but in reality we are just assuming somebody already thought about it for us :)

Looking at include/asm-generic/pgtable-nopmd.h, PUD entries there are

* always present (pud_present() == 1)
* always a page table (pud_leaf() == 0)

And pmd_offset() is just a typecast.

So I wonder if that means that we can make pudp_get() be a simple load (!READ_ONCE) because nobody should possibly do something with that value as we must perform the pmd_present() checks etc. later and obtain the PMD through a READ_ONCE().

So far my thinking, maybe it's flawed :)

Signature · 3 lines
Cheers

David
#23 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Ryan Roberts
Quoted 51 lines · Ryan Roberts
Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Quoted 1 line

Yes. But I'm not convinced it's correct.

Yeah, I'm also still trying to understand how it could work.

Quoted 9 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

With __PAGETABLE_PMD_FOLDED we treat the PUD to be fake-present, like

static inline int pud_present(pud_t pud) { return 1; }

And obtaining the pmd_t* is essentially cast of the pud_t*

static inline pmd_t * pmd_offset(pud_t * pud, unsigned long address)

{
	return (pmd_t *)pud;
}

So in that case we might want to have the READ_ONCE() remove from the pudp_get(), not the pmdp_get()?

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Signature · 3 lines
Cheers

David
#24 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 71 lines · David Hildenbrand (Red Hat)
Quoted 51 lines · Ryan Roberts
Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Quoted 1 line

Yes. But I'm not convinced it's correct.

Yeah, I'm also still trying to understand how it could work.

Quoted 9 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

With __PAGETABLE_PMD_FOLDED we treat the PUD to be fake-present, like

static inline int pud_present(pud_t pud) { return 1; }

And obtaining the pmd_t* is essentially cast of the pud_t*

Quoted 7 lines

static inline pmd_t * pmd_offset(pud_t * pud, unsigned long address)

{
	return (pmd_t *)pud;
}

So in that case we might want to have the READ_ONCE() remove from the pudp_get(), not the pmdp_get()?

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

Quoted 6 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

I'd rather we kept it as stupid/obvious as possible...

Quoted 5 lines

--
Cheers

David

#25 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 77 lines · Lorenzo Stoakes
Quoted 76 lines · David Hildenbrand (Red Hat)
Quoted 51 lines · Ryan Roberts
Quoted 41 lines · Wei Yang
Quoted 1 line · Ryan Roberts

On 26/11/2025 12:35, David Hildenbrand (Red Hat) wrote:

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://lkml.kernel.org/r/[email protected]

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Quoted 1 line

Yes. But I'm not convinced it's correct.

Yeah, I'm also still trying to understand how it could work.

Quoted 9 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

With __PAGETABLE_PMD_FOLDED we treat the PUD to be fake-present, like

static inline int pud_present(pud_t pud) { return 1; }

And obtaining the pmd_t* is essentially cast of the pud_t*

static inline pmd_t * pmd_offset(pud_t * pud, unsigned long address)

{
	return (pmd_t *)pud;
}
Quoted 5 lines
Quoted 2 lines

So in that case we might want to have the READ_ONCE() remove from the pudp_get(), not the pmdp_get()?

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

Quoted 6 lines
Quoted 6 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

Quoted 6 lines
Quoted 1 line

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

I'd rather we kept it as stupid/obvious as possible...

Looking at include/asm-generic/pgtable-nopmd.h I am not sure we are talking about implicit assumptions here. It's kind-of the design that the pud_t values are dummies, so why shoul the pudp_get() give you any guarantees.

At least that's my current understanding, which might be very flawed :)

Signature · 3 lines
Cheers

David
#26 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Anyway. I am now designating you the expert at this ;)

Quoted 12 lines
Quoted 12 lines
Quoted 8 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

Quoted 7 lines
Quoted 1 line

I'd rather we kept it as stupid/obvious as possible...

Looking at include/asm-generic/pgtable-nopmd.h I am not sure we are talking about implicit assumptions here. It's kind-of the design that the pud_t values are dummies, so why shoul the pudp_get() give you any guarantees.

At least that's my current understanding, which might be very flawed :)

I mean I'm waving my hands around like I'm working on an aircraft carrier here so if you're _sure_ it's _absolutely_ safe then fine :)

In other words - well volunteered, sir ;)

Quoted 10 lines

--
Cheers

David

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

Cheers, Lorenzo

#27 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

Quoted 2 lines

Anyway. I am now designating you the expert at this ;)

Oh no. :)

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines
Quoted 9 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

I'd rather we kept it as stupid/obvious as possible...

Quoted 8 lines
Quoted 5 lines

Looking at include/asm-generic/pgtable-nopmd.h I am not sure we are talking about implicit assumptions here. It's kind-of the design that the pud_t values are dummies, so why shoul the pudp_get() give you any guarantees.

At least that's my current understanding, which might be very flawed :)

I mean I'm waving my hands around like I'm working on an aircraft carrier here so if you're _sure_ it's _absolutely_ safe then fine :)

Well, not yet ... :)

Signature · 3 lines
Cheers

David
reviewer
#28 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

Quoted 32 lines
Quoted 3 lines

Anyway. I am now designating you the expert at this ;)

Oh no. :)

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines
Quoted 9 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

I'd rather we kept it as stupid/obvious as possible...

Quoted 8 lines
Quoted 5 lines

Looking at include/asm-generic/pgtable-nopmd.h I am not sure we are talking about implicit assumptions here. It's kind-of the design that the pud_t values are dummies, so why shoul the pudp_get() give you any guarantees.

At least that's my current understanding, which might be very flawed :)

I mean I'm waving my hands around like I'm working on an aircraft carrier here so if you're _sure_ it's _absolutely_ safe then fine :)

Well, not yet ... :)

reviewer
#29 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 45 lines · Ryan Roberts
Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 5 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud) { return 1; }

And we will change it to this:

if (!pud_present(pudp_get(pud)))

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

#define pud_present(pud) 1

Then the compiler will never even see the pudp_get().

Thanks,
Ryan

Quoted 34 lines
Quoted 33 lines
Quoted 4 lines

Anyway. I am now designating you the expert at this ;)

Oh no. :)

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines
Quoted 9 lines

IOW, push the READ_ONCE() down to the lowest level so the previous ones (that will get essentially ignore?) will get folded into the last READ_ONCE()?

But my head still hurts and I am focusing on something else concurrently :)

Even if we could make this work, I don't love that there's some implicit assumption there that could easily break later on.

I'd rather we kept it as stupid/obvious as possible...

Quoted 8 lines
Quoted 5 lines

Looking at include/asm-generic/pgtable-nopmd.h I am not sure we are talking about implicit assumptions here. It's kind-of the design that the pud_t values are dummies, so why shoul the pudp_get() give you any guarantees.

At least that's my current understanding, which might be very flawed :)

I mean I'm waving my hands around like I'm working on an aircraft carrier here so if you're _sure_ it's _absolutely_ safe then fine :)

Well, not yet ... :)

#30 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 70 lines · Ryan Roberts
Quoted 45 lines · Ryan Roberts
Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 5 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud) { return 1; }

And we will change it to this:

Quoted 9 lines

if (!pud_present(pudp_get(pud)))

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

#define pud_present(pud) 1

Let's take a step back and realize that with __PAGETABLE_PMD_FOLDED

(a) *pudp does not make any sense

For a folded PMD, *pudp == *pmdp and consequently we would actually get a PMD, not a PUD.

For this reason all these pud_* helpers ignore the passed value completely. It would be wrong.

(b) pmd_offset() does *not* consume a pud but instead a pudp.

That makes sense, just imagine what would happen if someone would pass *pudp to that helper (we'd dereference twice ...).

So I wonder if we can just teach get_pudp() and friends to ... return true garbage instead of dereferencing something that does not make sense?

include/linux/pgtable.h +6 -0
index 32e8457ad5352..c95d0d89ab3f1 100644
@@ -351,7 +351,13 @@ static inline pmd_t pmdp_get(pmd_t *pmdp)
 #ifndef pudp_get
 static inline pud_t pudp_get(pud_t *pudp)
 {
+#ifdef __PAGETABLE_PMD_FOLDED
+       pud_t dummy = { 0 };
+
+       return dummy;
+#else
        return READ_ONCE(*pudp);
+#endif
 }
 #endif
 

set_pud/pud_page/pud_pgtable helper are confusing, I would assume they are essentially unused (like documented for set_put) and only required to keep compilers happy.

Signature · 3 lines
Cheers

David
#31 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 118 lines · David Hildenbrand (Red Hat)
Quoted 70 lines · Ryan Roberts
Quoted 45 lines · Ryan Roberts
Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 5 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud) { return 1; }

And we will change it to this:

Quoted 9 lines

if (!pud_present(pudp_get(pud)))

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

#define pud_present(pud) 1

Let's take a step back and realize that with __PAGETABLE_PMD_FOLDED

(a) *pudp does not make any sense

For a folded PMD, *pudp == *pmdp and consequently we would actually get a PMD, not a PUD.

For this reason all these pud_* helpers ignore the passed value completely. It would be wrong.

(b) pmd_offset() does *not* consume a pud but instead a pudp.

That makes sense, just imagine what would happen if someone would pass *pudp to that helper (we'd dereference twice ...).

So I wonder if we can just teach get_pudp() and friends to ... return true garbage instead of dereferencing something that does not make sense?

include/linux/pgtable.h +6 -0
index 32e8457ad5352..c95d0d89ab3f1 100644
@@ -351,7 +351,13 @@ static inline pmd_t pmdp_get(pmd_t *pmdp)
   #ifndef pudp_get
   static inline pud_t pudp_get(pud_t *pudp)
   {
+#ifdef __PAGETABLE_PMD_FOLDED
+       pud_t dummy = { 0 };
+
+       return dummy;
+#else
          return READ_ONCE(*pudp);
+#endif
   }
   #endif
 
Quoted 3 lines

set_pud/pud_page/pud_pgtable helper are confusing, I would assume they are essentially unused (like documented for set_put) and only required to keep compilers happy.

Staring at GUP-fast and perf_get_pgtable_size()---which should better be converted to pudp_get() etc--I guess we might have to rework p4d_offset_lockless() to do something that doesn't rely on passing variables of local variables.

We might have to enlighten these walkers (and only these) about folded page tables such that they don't depend on the result of pudp_get() and friends.

Signature · 3 lines
Cheers

David
#32 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 128 lines · David Hildenbrand (Red Hat)
Quoted 118 lines · David Hildenbrand (Red Hat)
Quoted 70 lines · Ryan Roberts
Quoted 45 lines · Ryan Roberts
Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 11 lines · Lorenzo Stoakes
Quoted 7 lines · David Hildenbrand (Red Hat)
Quoted 3 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 5 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud) { return 1; }

And we will change it to this:

Quoted 9 lines

if (!pud_present(pudp_get(pud)))

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

#define pud_present(pud) 1

Let's take a step back and realize that with __PAGETABLE_PMD_FOLDED

(a) *pudp does not make any sense

For a folded PMD, *pudp == *pmdp and consequently we would actually get a PMD, not a PUD.

For this reason all these pud_* helpers ignore the passed value completely. It would be wrong.

(b) pmd_offset() does *not* consume a pud but instead a pudp.

That makes sense, just imagine what would happen if someone would pass *pudp to that helper (we'd dereference twice ...).

So I wonder if we can just teach get_pudp() and friends to ... return true garbage instead of dereferencing something that does not make sense?

include/linux/pgtable.h +6 -0
index 32e8457ad5352..c95d0d89ab3f1 100644
@@ -351,7 +351,13 @@ static inline pmd_t pmdp_get(pmd_t *pmdp)
    #ifndef pudp_get
    static inline pud_t pudp_get(pud_t *pudp)
    {
+#ifdef __PAGETABLE_PMD_FOLDED
+       pud_t dummy = { 0 };
+
+       return dummy;
+#else
           return READ_ONCE(*pudp);
+#endif
    }
    #endif
 
Quoted 3 lines

set_pud/pud_page/pud_pgtable helper are confusing, I would assume they are essentially unused (like documented for set_put) and only required to keep compilers happy.

Staring at GUP-fast and perf_get_pgtable_size()---which should better be converted to pudp_get() etc--I guess we might have to rework p4d_offset_lockless() to do something that doesn't rely on passing variables of local variables.

Quoted 3 lines

We might have to enlighten these walkers (and only these) about folded page tables such that they don't depend on the result of pudp_get() and friends.

Talking to myself (I know), handling this might be as simple as having

include/asm-generic/pgtable-nopmd.h +7 -0
index 8ffd64e7a24cb..60e5ba02bcf06 100644
@@ -49,6 +49,13 @@ static inline pmd_t * pmd_offset(pud_t * pud, unsigned long address)
 }
 #define pmd_offset pmd_offset
 
+static inline pmd_t * pmd_offset_lockless(pud_t *pud, puf_t pud, unsigned long address)
+{
+       return (pmd_t *)pud;
+}
+#define pmd_offset_lcokless pmd_offset_lockless
+
+
 #define pmd_val(x)                             (pud_val((x).pud))
 #define __pmd(x)                               ((pmd_t) { __pud(x) } )
 

IOW, just like for pmd_offset() we cast the pointer and don't ever touch the pud.

As a reminder, the default is

#ifndef pmd_offset_lockless
#define pmd_offset_lockless(pudp, pud, address) pmd_offset(&(pud), address) #endif

(isn't that nasty? :) )

Signature · 3 lines
Cheers

David
reviewer
#33 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 90 lines · David Hildenbrand (Red Hat)
Quoted 89 lines · David Hildenbrand (Red Hat)
Quoted 88 lines · David Hildenbrand (Red Hat)
Quoted 87 lines · Ryan Roberts
Quoted 50 lines · Ryan Roberts
Quoted 14 lines · David Hildenbrand (Red Hat)
Quoted 7 lines · Lorenzo Stoakes
Quoted 6 lines · David Hildenbrand (Red Hat)
Quoted 4 lines · Lorenzo Stoakes

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up
requiring a READ_ONCE() further up the stack?

Quoted 5 lines
Quoted 2 lines

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 8 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to
see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

    - It guarrantees that a load will be issued, *even if output is unused*
    - It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we
only care about:

    - It guarrantees that a load will be issued, *if output is used*
    - It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler
will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it
otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 7 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which
is stronger) and arches could opt in to providing a weaker asm version. Then the
default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non- volatile
asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with
a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something
like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud)    { return 1; }

And we will change it to this:

if (!pud_present(pudp_get(pud)))

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 2 lines

#define pud_present(pud)    1

Let's take a step back and realize that with __PAGETABLE_PMD_FOLDED

(a) *pudp does not make any sense

I'm struggling with this statement. The PMD is folded, not the PUD. So the PMD table consists of a single entry, which overlays the entry in the PUD, right? So the PUD exists and *pudp must be valid?

Now, pgtable-nopmd.h includes pgtable-nopud.h so actually the PUD is also folded into the P4D and the P4D is also folded into the PGD. But the PGD exists and is not folded.

So what you are saying is true in practice, I guess. But it's not true if you replace PMD with P4D and PUD with PGD.

Does what I'm saying matter or have any impact on your assessment below? I have no idea. My head hurts.

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

For a folded PMD, *pudp == *pmdp and consequently we would actually get a PMD, not a PUD.

Well based on what I said above, the PMD is folded into the PUD, the PUD is folded into the P4D and the P4D is folded into the PGD. So all of those things are actually pointing to the PGD entry in the PGD table, right? And pmd_t, pud_t, p4d_t are all defined as containers holding the next thing up:

typedef struct { pud_t pud; } pmd_t;

So it all works out, and is safe, I think?

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

For this reason all these pud_* helpers ignore the passed value completely. It would be wrong.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

(b) pmd_offset() does *not* consume a pud but instead a pudp.

That makes sense, just imagine what would happen if someone would pass *pudp to that helper (we'd dereference twice ...).

So I wonder if we can just teach get_pudp() and friends to ... return true garbage instead of dereferencing something that does not make sense?

Sorry, I don't really understand why dereferencing does not make sense. the pud_t is a struct containing a single p4d_t and that is a struct containing a single pgd_t and it is pointing to the pgd entry. So why isn't it safe?

Quoted 13 lines
Quoted 13 lines

include/linux/pgtable.h static inline pmd_t pmdp_get(pmd_t *pmdp) · line 357

Quoted 13 lines
include/linux/pgtable.h +4 -0
index 32e8457ad5352..c95d0d89ab3f1 100644
@@ -351,7 +351,13 @@ static inline pmd_t pmdp_get(pmd_t *pmdp)
     #ifndef pudp_get
     static inline pud_t pudp_get(pud_t *pudp)
     {
+#ifdef __PAGETABLE_PMD_FOLDED
+       pud_t dummy = { 0 };
+
+       return dummy;

If you're confident that this is correct, then I believe you. But I can't follow your logic at the moment. But we have a fairly long history of you being right and me not understanding... :)

I don't think in general it is invalid for something to call the getter and do something with the result just because it's folded. e.g. log it's value. So I don't think returning a dummy value is ok.

See __print_bad_page_map_pgtable() for example?

Quoted 45 lines
Quoted 14 lines
Quoted 8 lines
include/linux/pgtable.h +2 -0
+#else
            return READ_ONCE(*pudp);
+#endif
     }
     #endif

    set_pud/pud_page/pud_pgtable helper are confusing, I would assume they are essentially unused (like documented for set_put) and only required to keep compilers happy.

Staring at GUP-fast and perf_get_pgtable_size()---which should better be converted to pudp_get() etc--I guess we might have to rework p4d_offset_lockless() to do something that doesn't rely on passing variables of local variables.

Quoted 3 lines

We might have to enlighten these walkers (and only these) about folded page tables such that they don't depend on the result of pudp_get() and friends.

Talking to myself (I know), handling this might be as simple as having

include/asm-generic/pgtable- renamed from include/asm-generic/pgtable-nopmd.h +0 -0

nopmd.h
index 8ffd64e7a24cb..60e5ba02bcf06 100644

include/asm-generic/pgtable-nopmd.h +0 -0
@@ -49,6 +49,13 @@ static inline pmd_t * pmd_offset(pud_t * pud, unsigned long
 address)
  }
  #define pmd_offset pmd_offset


+static inline pmd_t * pmd_offset_lockless(pud_t *pud, puf_t pud, unsigned long address)

include/asm-generic/pgtable-nopmd.h +6 -0
+{
+       return (pmd_t *)pud;
+}
+#define pmd_offset_lcokless pmd_offset_lockless
+
+

 #define pmd_val(x)                             (pud_val((x).pud)) #define __pmd(x)                               ((pmd_t) { __pud(x) } )

IOW, just like for pmd_offset() we cast the pointer and don't ever touch the pud.

Quoted 7 lines

As a reminder, the default is

#ifndef pmd_offset_lockless
#define pmd_offset_lockless(pudp, pud, address) pmd_offset(&(pud), address) #endif

(isn't that nasty? :) )

Just as a general comment; arm64 expects and requires today that any pte_t pointer passed to ptep_get(), set_ptes(), and all the other ptep helpers point to entries in the pgtable. We cannot tolerate being passed pointers to stack variables. We assume we can roam around in the pgtable for contpte purposes.

Extending this to the other levels, we would have the same requirements.

Thanks,
Ryan

Quoted 1 line
#34 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Ryan Roberts

Le 26/11/2025 à 17:34, Ryan Roberts a écrit :

Quoted 72 lines · Ryan Roberts
Quoted 45 lines · David Hildenbrand (Red Hat)
Quoted 13 lines · Lorenzo Stoakes
Quoted 11 lines · David Hildenbrand (Red Hat)
Quoted 7 lines · Lorenzo Stoakes
Quoted 3 lines

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

Quoted 5 lines

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

Another idea:

Given the main pattern where we are aiming to optimize out the read is something like:

if (!pud_present(*pud))

where for a folded pmd:

static inline int pud_present(pud_t pud) { return 1; }

And we will change it to this:

if (!pud_present(pudp_get(pud)))

Quoted 8 lines

...

perhaps we can just define the folded pXd_present(), pXd_none(), pXd_bad(), pXd_user() and pXd_leaf() as macros:

#define pud_present(pud) 1

Then the compiler will never even see the pudp_get().

Take care about macros with unused parameters, it can be a problem sometimes, see commit 05a4ab823983 ("powerpc/uaccess: fix warning/error with access_ok()")

Christophe

#35 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Ryan Roberts

Le 26/11/2025 à 17:34, Ryan Roberts a écrit :

Quoted 50 lines · Ryan Roberts
Quoted 49 lines · David Hildenbrand (Red Hat)
Quoted 13 lines · Lorenzo Stoakes
Quoted 11 lines · David Hildenbrand (Red Hat)
Quoted 7 lines · Lorenzo Stoakes
Quoted 3 lines

Would the pmdp_get() never get invoked then? Or otherwise wouldn't that end up requiring a READ_ONCE() further up the stack?

See my other reply, I think the pmdp_get() is required because all pud_* functions are just simple stubs.

OK, thought you were saying we should push further down the stack? Or up depending on how you view these things :P as in READ_ONCE at leaf?

Quoted 7 lines

I think at leaf because I think the previous ones should essentially be only used by stubs.

But I haven't fully digested how this is all working. Or supposed to work.

I'm trying to chew through the arch/arm/include/asm/pgtable-2level.h example to see if I can make sense of it,

I wonder if we can think about this slightly differently;

READ_ONCE() has two important properties:

- It guarrantees that a load will be issued, *even if output is unused*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think for the existing places where READ_ONCE() is used for pagetable reads we only care about:

- It guarrantees that a load will be issued, *if output is used*
- It guarrantees that the read will be single-copy-atomic (no tearing)

I think if we can weaken to the "if output is used" property, then the compiler will optimize out all the unneccessary reads.

AIUI, a C dereference provides neither of the guarrantees so that's no good.

What about non-volatile asm? I'm told (thought need to verify) that for non-volatile asm, the compiler will emit it if the output is used and remove it otherwise. So if the asm contains the required single-copy-atomic, perhaps we are in business?

So we would need a new READ_SCA() macro that could default to READ_ONCE() (which is stronger) and arches could opt in to providing a weaker asm version. Then the default pXdp_get() could be READ_SCA(). And this should work for all cases.

Quoted 6 lines
Quoted 1 line

I think.

I'm not sure this works. It looks like the compiler is free to move non-volatile asm sections which might be problematic for places where we are currently using READ_ONCE() in lockless algorithms, (e.g. GUP?). We wouldn't want to end up with a stale value.

What about adding a memory clobber to the non-volatile asm ? Compiler shouldn't move the asm section in that case.

Christophe

#36 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

In reply to Ryan Roberts

Le 26/11/2025 à 15:22, Ryan Roberts a écrit :

Quoted 53 lines · Wei Yang
Quoted 41 lines · Ryan Roberts
Quoted 1 line · David Hildenbrand (Red Hat)

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Flkml.kernel.org%2Fr%2F0019d675-ce3d-4a5c-89ed-f126c45145c9%40kernel.org&data=05%7C02%7Cchristophe.leroy%40csgroup.eu%7C22d0a028b1ec4a8b678108de2cf73769%7C8b87af7d86474dc78df45f69a2011bb5%7C0%7C0%7C638997637481119954%7CUnknown%7CTWFpbGZsb3d8eyJFbXB0eU1hcGkiOnRydWUsIlYiOiIwLjAuMDAwMCIsIlAiOiJXaW4zMiIsIkFOIjoiTWFpbCIsIldUIjoyfQ%3D%3D%7C0%7C%7C%7C&sdata=ocR6usVgRHfue0MrtbQnDO8whINvy%2FDMAfNE3caiY8c%3D&reserved=0

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Yes. But I'm not convinced it's correct.

Quoted 8 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

I think you can't assume pgdp_get() was already called, because some parts of code will directly descend to PMD level using pmd_off() or pmd_off_k()

static inline pmd_t *pmd_off(struct mm_struct *mm, unsigned long va)

{
	return pmd_offset(pud_offset(p4d_offset(pgd_offset(mm, va), va), va), va);
}

static inline pmd_t *pmd_off_k(unsigned long va)

{
	return pmd_offset(pud_offset(p4d_offset(pgd_offset_k(va), va), va), va);
}

Christophe

#37 lore raw

Re: [PATCH v3 06/22] mm: Always use page table accessor functions

Quoted 70 lines · Christophe Leroy (CS GROUP)

Le 26/11/2025 à 15:22, Ryan Roberts a écrit :

Quoted 53 lines · Wei Yang
Quoted 41 lines · Ryan Roberts
Quoted 1 line · David Hildenbrand (Red Hat)

[...]

Quoted 26 lines
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 6 lines

Hi,

I've just come across this patch and wanted to mention that we could also benefit from this improved absraction for some features we are looking at for arm64. As you mention, Anshuman had a go but hit some roadblocks.

Quoted 9 lines

The main issue is that the compiler was unable to optimize away the READ_ONCE()s
for the case where certain levels of the pgtable are folded. But it can optimize
the plain C dereferences. There were complaints the the generated code for arm
(32) and powerpc was significantly impacted due to having many more (redundant)
loads.

We do have mm_pmd_folded()/p4d_folded() etc, could that help to sort this out internally?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

Just stumbled over the reply from Christope:

https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Flkml.kernel.org%2Fr%2F0019d675-ce3d-4a5c-89ed-f126c45145c9%40kernel.org&data=05%7C02%7Cchristophe.leroy%40csgroup.eu%7C22d0a028b1ec4a8b678108de2cf73769%7C8b87af7d86474dc78df45f69a2011bb5%7C0%7C0%7C638997637481119954%7CUnknown%7CTWFpbGZsb3d8eyJFbXB0eU1hcGkiOnRydWUsIlYiOiIwLjAuMDAwMCIsIlAiOiJXaW4zMiIsIkFOIjoiTWFpbCIsIldUIjoyfQ%3D%3D%7C0%7C%7C%7C&sdata=ocR6usVgRHfue0MrtbQnDO8whINvy%2FDMAfNE3caiY8c%3D&reserved=0

And wonder if we could handle that somehow directly in the pgdp_get() etc.

Quoted 9 lines

I certainly don't like the suggestion of doing the is_folded() test outside the helper, but if we can push that logic down into pXdp_get() that would be pretty neat. Anshuman and I did briefly play with the idea of doing a C dereference if the level is folded and a READ_ONCE() otherwise, all inside each pXdp_get() helper. Although we never proved it to be correct. I struggle with the model for folding. Do you want to optimize out all-but-the-highest level's access or all-but-the-lowest level's access? Makes my head hurt...

You mean sth like:

Quoted 8 lines

static inline pmd_t pmdp_get(pmd_t *pmdp)
{

#ifdef __PAGETABLE_PMD_FOLDED
	return *pmdp;
#else
	return READ_ONCE(*pmdp);

#endif
}

Yes. But I'm not convinced it's correct.

Quoted 8 lines

I *think* (but please correct me if I'm wrong) if the PMD is folded, the PUD and P4D must also be folded, and you effectively have a 2 level pgtable consisting of the PGD table and the PTE table. p4dp_get(), pudp_get() and pmdp_get() are all effectively duplicating the load of the pgd entry? So assuming pgdp_get() was already called and used READ_ONCE(), you might hope the compiler will just drop the other loads and just use the value returned by READ_ONCE(). But I doubt there is any guarantee of that and you might be in a situation where pgdp_get() never even got called (perhaps you already have the pmd pointer).

I think you can't assume pgdp_get() was already called, because some parts of code will directly descend to PMD level using pmd_off() or pmd_off_k()

static inline pmd_t *pmd_off(struct mm_struct *mm, unsigned long va)

Quoted 8 lines
{
	return pmd_offset(pud_offset(p4d_offset(pgd_offset(mm, va), va), va), va);
}

static inline pmd_t *pmd_off_k(unsigned long va)

{
	return pmd_offset(pud_offset(p4d_offset(pgd_offset_k(va), va), va), va);
}

I'll note that these (nesty) helpers only work when you know that you have folded page tables.

And that's why I am arguing that the pmdp_get() must actually be kept as is.

Signature · 3 lines
Cheers

David
#38 lore raw

PATCH v3 7/22 checkpatch: Warn on page table access without accessors

In reply to Samuel Holland

Architectures may have special rules for accessing the hardware page tables (for example, atomicity/ordering requirements), so the generic MM code provides the pXXp_get() and set_pXX() hooks for architectures to implement. These accessor functions are often omitted where a raw pointer dereference is believed to be safe (i.e. race-free). However, RISC-V needs to use these hooks to rewrite the page table values at read/write time on some platforms. A raw pointer dereference will no longer produce the correct value on those platforms, so the generic code must always use the accessor functions.

sparse can only report improper pointer dereferences if every page table pointer (variable, function argument, struct member) is individually marked with an attribute (similar to __user). So while this is possible, it would require invasive changes across all architectures. Instead, as an immediate first solution, add a checkpatch warning that will generally catch the prohibited pointer dereferences. Architecture code is ignored, as the raw dereferences may be safe on some architectures.

---

Changes in v3:
- New patch for v3

 scripts/checkpatch.pl | 7 +++++++
 1 file changed, 7 insertions(+)
scripts/checkpatch.pl +7 -0
index 92669904eecc..55984d7361ea 100755
@@ -7721,6 +7721,13 @@ sub process {
 				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
 			}
 		}
+
+# check for raw dereferences of hardware page table pointers
+		if ($realfile !~ m@^arch/@ &&
+		    $line =~ /(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b/) {
+			WARN("PAGE_TABLE_ACCESSORS",
+			     "Use $3p_get()/set_$3() instead of dereferencing page table pointers\n" . $herecurr);
+		}
 	}
 
 	# If we have no input at all, then there is nothing to report on
Signature · 1 line
2.47.2
maintainer
#39 lore raw

Re: [PATCH v3 07/22] checkpatch: Warn on page table access without accessors

Quoted 9 lines · Samuel Holland

Architectures may have special rules for accessing the hardware page tables (for example, atomicity/ordering requirements), so the generic MM code provides the pXXp_get() and set_pXX() hooks for architectures to implement. These accessor functions are often omitted where a raw pointer dereference is believed to be safe (i.e. race-free). However, RISC-V needs to use these hooks to rewrite the page table values at read/write time on some platforms. A raw pointer dereference will no longer produce the correct value on those platforms, so the generic code must always use the accessor functions.

[]

scripts/checkpatch.pl

Quoted 1 line
scripts/checkpatch.pl +0 -0

[]

scripts/checkpatch.pl sub process { · line 7731

Quoted 12 lines
scripts/checkpatch.pl +7 -0
@@ -7721,6 +7721,13 @@ sub process {
 				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
 			}
 		}
+
+# check for raw dereferences of hardware page table pointers
+		if ($realfile !~ m@^arch/@ &&
+		    $line =~ /(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b/) {
+			WARN("PAGE_TABLE_ACCESSORS",
+			     "Use $3p_get()/set_$3() instead of dereferencing page table pointers\n" . $herecurr);
+		}
 	}

Seems like a lot of matches

$ git grep -P '(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b' | \
  grep -v '^arch/' | wc -l
766

Is this really appropriate?

trivia:

izeof is really odd looking. I'd prefer sizeof.

#40 lore raw

Re: [PATCH v3 07/22] checkpatch: Warn on page table access without accessors

Quoted 28 lines · Joe Perches
Quoted 9 lines · Samuel Holland

Architectures may have special rules for accessing the hardware page tables (for example, atomicity/ordering requirements), so the generic MM code provides the pXXp_get() and set_pXX() hooks for architectures to implement. These accessor functions are often omitted where a raw pointer dereference is believed to be safe (i.e. race-free). However, RISC-V needs to use these hooks to rewrite the page table values at read/write time on some platforms. A raw pointer dereference will no longer produce the correct value on those platforms, so the generic code must always use the accessor functions.

[]

scripts/checkpatch.pl

Quoted 1 line
scripts/checkpatch.pl +0 -0

[]

scripts/checkpatch.pl sub process { · line 7731

Quoted 12 lines
scripts/checkpatch.pl +7 -0
@@ -7721,6 +7721,13 @@ sub process {
 				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
 			}
 		}
+
+# check for raw dereferences of hardware page table pointers
+		if ($realfile !~ m@^arch/@ &&
+		    $line =~ /(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b/) {
+			WARN("PAGE_TABLE_ACCESSORS",
+			     "Use $3p_get()/set_$3() instead of dereferencing page table pointers\n" . $herecurr);
+		}
 	}

Seems like a lot of matches

Quoted 5 lines
$ git grep -P '(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b' | \
  grep -v '^arch/' | wc -l
766

Is this really appropriate?

Other patches in this series remove 277 of these matches. But it looks like a couple of driver systems (iommu, dm) use variables that match this pattern as well. Limiting the check to include/ and mm/ avoids the false positives.

Quoted 3 lines

trivia:

izeof is really odd looking. I'd prefer sizeof.

I agree, but my perl complains "Variable length lookbehind not implemented in regex m/(?<!pte_t |p[mu4g]d_t |sizeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b/ at scripts/checkpatch.pl line 7727." I could split this into two patterns, which would also solve the false positives with multiple variable declarations.

Regards,
Samuel

#41 lore raw

Re: [PATCH v3 07/22] checkpatch: Warn on page table access without accessors

Quoted 29 lines · Samuel Holland
Quoted 28 lines · Joe Perches
Quoted 9 lines · Samuel Holland

Architectures may have special rules for accessing the hardware page tables (for example, atomicity/ordering requirements), so the generic MM code provides the pXXp_get() and set_pXX() hooks for architectures to implement. These accessor functions are often omitted where a raw pointer dereference is believed to be safe (i.e. race-free). However, RISC-V needs to use these hooks to rewrite the page table values at read/write time on some platforms. A raw pointer dereference will no longer produce the correct value on those platforms, so the generic code must always use the accessor functions.

[]

scripts/checkpatch.pl

Quoted 1 line
scripts/checkpatch.pl +0 -0

[]

scripts/checkpatch.pl sub process { · line 7731

Quoted 12 lines
scripts/checkpatch.pl +7 -0
@@ -7721,6 +7721,13 @@ sub process {
  				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
  			}
  		}
+
+# check for raw dereferences of hardware page table pointers
+		if ($realfile !~ m@^arch/@ &&
+		    $line =~ /(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b/) {
+			WARN("PAGE_TABLE_ACCESSORS",
+			     "Use $3p_get()/set_$3() instead of dereferencing page table pointers\n" . $herecurr);
+		}
  	}

Seems like a lot of matches

Quoted 3 lines
Quoted 3 lines
$ git grep -P '(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|p[mu4g]d)p?\b' | \
   grep -v '^arch/' | wc -l
766

That is indeed concerning.

I recall that we discussed an alternative approach with Ryan in the past: I don't remember all the details, but essentially it was about using separate types, such that dereferencing would not get you the type the other functions would be expecting. Such that the compiler will bark when you try to dereference.

Signature · 3 lines
Cheers

David
#42 lore raw

Re: [PATCH v3 07/22] checkpatch: Warn on page table access without accessors

Quoted 38 lines · David Hildenbrand (Red Hat)
Quoted 32 lines · Samuel Holland
Quoted 31 lines · Joe Perches
Quoted 9 lines · Samuel Holland

Architectures may have special rules for accessing the hardware page tables (for example, atomicity/ordering requirements), so the generic MM code provides the pXXp_get() and set_pXX() hooks for architectures to implement. These accessor functions are often omitted where a raw pointer dereference is believed to be safe (i.e. race-free). However, RISC-V needs to use these hooks to rewrite the page table values at read/write time on some platforms. A raw pointer dereference will no longer produce the correct value on those platforms, so the generic code must always use the accessor functions.

[]

scripts/checkpatch.pl

Quoted 1 line
scripts/checkpatch.pl +0 -0

[]

Quoted 9 lines
scripts/checkpatch.pl +0 -0
@@ -7721,6 +7721,13 @@ sub process {

                  ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
              }
          }

scripts/checkpatch.pl +4 -0
+
+# check for raw dereferences of hardware page table pointers
+        if ($realfile !~ m@^arch/@ &&
+            $line =~ /(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?
Quoted 6 lines

(pte|p[mu4g]d)p?\b/) {
+            WARN("PAGE_TABLE_ACCESSORS",
+                 "Use $3p_get()/set_$3() instead of dereferencing page table pointers\n" . $herecurr);
+        }
      }

Seems like a lot of matches

Quoted 4 lines
Quoted 4 lines
$ git grep -P '(?<!pte_t |p[mu4g]d_t |izeof\()\*\(?(vmf(\.|->))?(pte|
p[mu4g]d)p?\b' | \
   grep -v '^arch/' | wc -l
766
Quoted 6 lines

That is indeed concerning.

I recall that we discussed an alternative approach with Ryan in the past: I don't remember all the details, but essentially it was about using separate types, such that dereferencing would not get you the type the other functions would be expecting. Such that the compiler will bark when you try to dereference.

Even if some functions a new incompatible pointer type, don't we still have the problem that neither type would be safe to dereference?

A similar option to a new type would be to add a sparse annotation to the pointers that reference hardware page tables, similar to __user. I have prototyped a coccinelle script to add this annotation, and the sparse checking works. But I don't have the coccinelle expertise to automate the whole thing, so there's a lot of manual cleanup required. And this requires touching all architectures at once to avoid introducing erroneous sparse warnings. So I did not include this for v3 because it is quite a lot of churn. Is this something I should try to fully implement for v4?

Regards,
Samuel

#43 lore raw

PATCH v3 8/22 mm: Allow page table accessors to be non-idempotent

In reply to Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

---

(no changes since v2)

Changes in v2:
- New patch for v2

 kernel/events/core.c  | 2 ++
 mm/gup.c              | 3 +++
 mm/khugepaged.c       | 6 ++++--
 mm/page_table_check.c | 3 +++
 mm/pgtable-generic.c  | 2 ++
 5 files changed, 14 insertions(+), 2 deletions(-)
kernel/events/core.c +2 -0
index fa4f9165bd94..7969b060bf2d 100644
@@ -8154,6 +8154,8 @@ static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
 	if (pmd_leaf(pmd))
 		return pmd_leaf_size(pmd);
 
+	/* transform pmd as if &pmd pointed to a hardware page table */
+	set_pmd(&pmd, pmd);
 	ptep = pte_offset_map(&pmd, addr);
 	if (!ptep)
 		goto again;
mm/gup.c +3 -0
index 549f9e868311..aba61704049e 100644
@@ -2844,7 +2844,10 @@ static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
 	int ret = 0;
 	pte_t *ptep, *ptem;
 
+	/* transform pmd as if &pmd pointed to a hardware page table */
+	set_pmd(&pmd, pmd);
 	ptem = ptep = pte_offset_map(&pmd, addr);
+	pmd = pmdp_get(&pmd);
 	if (!ptep)
 		return 0;
 	do {
mm/khugepaged.c +4 -2
index 1bff8ade751a..ab1f68a7bc83 100644
@@ -1724,7 +1724,7 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
 		struct mmu_notifier_range range;
 		struct mm_struct *mm;
 		unsigned long addr;
-		pmd_t *pmd, pgt_pmd;
+		pmd_t *pmd, pgt_pmd, pmdval;
 		spinlock_t *pml;
 		spinlock_t *ptl;
 		bool success = false;
@@ -1777,7 +1777,9 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
 		 */
 		if (check_pmd_state(pmd) != SCAN_SUCCEED)
 			goto drop_pml;
-		ptl = pte_lockptr(mm, pmd);
+		/* pte_lockptr() needs a value, not a pointer to a page table */
+		pmdval = pmdp_get(pmd);
+		ptl = pte_lockptr(mm, &pmdval);
 		if (ptl != pml)
 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
 
mm/page_table_check.c +3 -0
index 31f4c39d20ef..77d6688db0de 100644
@@ -260,7 +260,10 @@ void __page_table_check_pte_clear_range(struct mm_struct *mm,
 		return;
 
 	if (!pmd_bad(pmd) && !pmd_leaf(pmd)) {
+		/* transform pmd as if &pmd pointed to a hardware page table */
+		set_pmd(&pmd, pmd);
 		pte_t *ptep = pte_offset_map(&pmd, addr);
+		pmd = pmdp_get(&pmd);
 		unsigned long i;
 
 		if (WARN_ON(!ptep))
mm/pgtable-generic.c +2 -0
index 63a573306bfa..6602deb002f1 100644
@@ -299,6 +299,8 @@ pte_t *___pte_offset_map(pmd_t *pmd, unsigned long addr, pmd_t *pmdvalp)
 		pmd_clear_bad(pmd);
 		goto nomap;
 	}
+	/* transform pmdval as if &pmdval pointed to a hardware page table */
+	set_pmd(&pmdval, pmdval);
 	return __pte_map(&pmdval, addr);
 nomap:
 	rcu_read_unlock();
Signature · 1 line
2.47.2
#44 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

kernel test robot noticed the following build errors:

Hi Samuel,

kernel test robot noticed the following build errors:

[auto build test ERROR on 24172e0d79900908cf5ebf366600616d29c9b417]

url:    https://github.com/intel-lab-lkp/linux/commits/Samuel-Holland/mm-ptdump-replace-READ_ONCE-with-standard-page-table-accessors/20251113-095117
base:   24172e0d79900908cf5ebf366600616d29c9b417
patch link:    https://lore.kernel.org/r/20251113014656.2605447-9-samuel.holland%40sifive.com
patch subject: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent
config: powerpc-allnoconfig (https://download.01.org/0day-ci/archive/20251113/[email protected]/config)
compiler: powerpc-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251113/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

mm/gup.c: In function 'gup_fast_pte_range':

>> mm/gup.c:2848:9: error: implicit declaration of function 'set_pmd'; did you mean 'set_p4d'? [-Wimplicit-function-declaration]
    2848 |         set_pmd(&pmd, pmd);
         |         ^~~~~~~
         |         set_p4d
--
   mm/pgtable-generic.c: In function '___pte_offset_map':
>> mm/pgtable-generic.c:303:9: error: implicit declaration of function 'set_pmd'; did you mean 'set_p4d'? [-Wimplicit-function-declaration]
     303 |         set_pmd(&pmdval, pmdval);
         |         ^~~~~~~
         |         set_p4d

vim +2848 mm/gup.c

2819
2820 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2821 /*
2822 * GUP-fast relies on pte change detection to avoid concurrent pgtable
2823 * operations.
2824 *
2825 * To pin the page, GUP-fast needs to do below in order:
2826 * (1) pin the page (by prefetching pte), then (2) check pte not changed.
2827 *
2828 * For the rest of pgtable operations where pgtable updates can be racy
2829 * with GUP-fast, we need to do (1) clear pte, then (2) check whether page
2830 * is pinned.
2831 *
2832 * Above will work for all pte-level operations, including THP split.
2833 *
2834 * For THP collapse, it's a bit more complicated because GUP-fast may be
2835 * walking a pgtable page that is being freed (pte is still valid but pmd
2836 * can be cleared already). To avoid race in such condition, we need to
2837 * also check pmd here to make sure pmd doesn't change (corresponds to
2838 * pmdp_collapse_flush() in the THP collapse code path).
2839 */
2840 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
2841 unsigned long end, unsigned int flags, struct page **pages,
2842 int *nr)
2843 {
2844 int ret = 0;
2845 pte_t *ptep, *ptem;
2846
2847 /* transform pmd as if &pmd pointed to a hardware page table */

> 2848		set_pmd(&pmd, pmd);

2849 ptem = ptep = pte_offset_map(&pmd, addr);
2850 pmd = pmdp_get(&pmd);
2851 if (!ptep)
2852 return 0;
2853 do {
2854 pte_t pte = ptep_get_lockless(ptep);
2855 struct page *page;
2856 struct folio *folio;
2857
2858 /*
2859 * Always fallback to ordinary GUP on PROT_NONE-mapped pages:
2860 * pte_access_permitted() better should reject these pages
2861 * either way: otherwise, GUP-fast might succeed in
2862 * cases where ordinary GUP would fail due to VMA access
2863 * permissions.
2864 */
2865 if (pte_protnone(pte))
2866 goto pte_unmap;
2867
2868 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2869 goto pte_unmap;
2870
2871 if (pte_special(pte))
2872 goto pte_unmap;
2873
2874 /* If it's not marked as special it must have a valid memmap. */
2875 VM_WARN_ON_ONCE(!pfn_valid(pte_pfn(pte)));
2876 page = pte_page(pte);
2877
2878 folio = try_grab_folio_fast(page, 1, flags);
2879 if (!folio)
2880 goto pte_unmap;
2881
2882 if (unlikely(pmd_val(pmd) != pmd_val(pmdp_get(pmdp))) ||
2883 unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
2884 gup_put_folio(folio, 1, flags);
2885 goto pte_unmap;
2886 }
2887
2888 if (!gup_fast_folio_allowed(folio, flags)) {
2889 gup_put_folio(folio, 1, flags);
2890 goto pte_unmap;
2891 }
2892
2893 if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
2894 gup_put_folio(folio, 1, flags);
2895 goto pte_unmap;
2896 }
2897
2898 /*
2899 * We need to make the page accessible if and only if we are
2900 * going to access its content (the FOLL_PIN case). Please
2901 * see Documentation/core-api/pin_user_pages.rst for
2902 * details.
2903 */
2904 if ((flags & FOLL_PIN) && arch_make_folio_accessible(folio)) {
2905 gup_put_folio(folio, 1, flags);
2906 goto pte_unmap;
2907 }
2908 folio_set_referenced(folio);
2909 pages[*nr] = page;
2910 (*nr)++;
2911 } while (ptep++, addr += PAGE_SIZE, addr != end);
2912
2913 ret = 1;
2914
2915 pte_unmap:
2916 pte_unmap(ptem);
2917 return ret;
2918 }
2919 #else
2920

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
reviewer
#45 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

In reply to Samuel Holland
Quoted 10 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

arm64, at least, expects and requires that only pointers to entries in pgtables are passed to the arch helpers (e.g. set_pte(), ptep_get(), etc). For PTEs, arm64 accesses adjacent entries within the page table to manage contiguous mappings. If it is passed a pointer to a stack variable, it may erroneously access other stuff on the stack thinking it is an entry in a page table.

I think we should formalize this as a clear requirement for all these functions; all pte/pmd/pud/p4d/pgd pointers passed to the arch pgtable helpers must always point to entries in pgtables.

arm64 will very likely take advantage of this in future in the pmd/pud/... helpers as it does today for the pte level. But even today, arm64's set_pmd() will emit barriers which are totally unnecessary when operating on a stack variable that the HW PTW will never see.

Thanks,
Ryan

Quoted 96 lines

---

(no changes since v2)

Changes in v2:
- New patch for v2

 kernel/events/core.c  | 2 ++
 mm/gup.c              | 3 +++
 mm/khugepaged.c       | 6 ++++--
 mm/page_table_check.c | 3 +++
 mm/pgtable-generic.c  | 2 ++
 5 files changed, 14 insertions(+), 2 deletions(-)
kernel/events/core.c +2 -0
index fa4f9165bd94..7969b060bf2d 100644
@@ -8154,6 +8154,8 @@ static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
 	if (pmd_leaf(pmd))
 		return pmd_leaf_size(pmd);
 
+	/* transform pmd as if &pmd pointed to a hardware page table */
+	set_pmd(&pmd, pmd);
 	ptep = pte_offset_map(&pmd, addr);
 	if (!ptep)
 		goto again;
mm/gup.c +3 -0
index 549f9e868311..aba61704049e 100644
@@ -2844,7 +2844,10 @@ static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
 	int ret = 0;
 	pte_t *ptep, *ptem;
 
+	/* transform pmd as if &pmd pointed to a hardware page table */
+	set_pmd(&pmd, pmd);
 	ptem = ptep = pte_offset_map(&pmd, addr);
+	pmd = pmdp_get(&pmd);
 	if (!ptep)
 		return 0;
 	do {
mm/khugepaged.c +4 -2
index 1bff8ade751a..ab1f68a7bc83 100644
@@ -1724,7 +1724,7 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
 		struct mmu_notifier_range range;
 		struct mm_struct *mm;
 		unsigned long addr;
-		pmd_t *pmd, pgt_pmd;
+		pmd_t *pmd, pgt_pmd, pmdval;
 		spinlock_t *pml;
 		spinlock_t *ptl;
 		bool success = false;
@@ -1777,7 +1777,9 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
 		 */
 		if (check_pmd_state(pmd) != SCAN_SUCCEED)
 			goto drop_pml;
-		ptl = pte_lockptr(mm, pmd);
+		/* pte_lockptr() needs a value, not a pointer to a page table */
+		pmdval = pmdp_get(pmd);
+		ptl = pte_lockptr(mm, &pmdval);
 		if (ptl != pml)
 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
 
mm/page_table_check.c +3 -0
index 31f4c39d20ef..77d6688db0de 100644
@@ -260,7 +260,10 @@ void __page_table_check_pte_clear_range(struct mm_struct *mm,
 		return;
 
 	if (!pmd_bad(pmd) && !pmd_leaf(pmd)) {
+		/* transform pmd as if &pmd pointed to a hardware page table */
+		set_pmd(&pmd, pmd);
 		pte_t *ptep = pte_offset_map(&pmd, addr);
+		pmd = pmdp_get(&pmd);
 		unsigned long i;
 
 		if (WARN_ON(!ptep))
mm/pgtable-generic.c +2 -0
index 63a573306bfa..6602deb002f1 100644
@@ -299,6 +299,8 @@ pte_t *___pte_offset_map(pmd_t *pmd, unsigned long addr, pmd_t *pmdvalp)
 		pmd_clear_bad(pmd);
 		goto nomap;
 	}
+	/* transform pmdval as if &pmdval pointed to a hardware page table */
+	set_pmd(&pmdval, pmdval);
 	return __pte_map(&pmdval, addr);
 nomap:
 	rcu_read_unlock();
#46 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

	set_pmd(&pmd, pmd);

is rather horrible.

Signature · 3 lines
Cheers

David
#47 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 13 lines · David Hildenbrand (Red Hat)
Quoted 12 lines · Ryan Roberts
Quoted 10 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

Quoted 7 lines
Quoted 1 line

I don't think this is a good solution.

Agreed,

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

Regards,
Samuel

reviewer
#48 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 18 lines · Samuel Holland
Quoted 17 lines · David Hildenbrand (Red Hat)
Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

Quoted 7 lines
Quoted 3 lines

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

From a quick look at the code, I think that some cases are solvable by refactoring to pass the value instead of the pointer, and leave it to the higher level decide how to read the value from the pointer - it knows if it is pointing to HW pgtable or if it's a (e.g) stack value.

But the more I look at the code, the more instances I find where pointers to stack variables are being passed to arch pgtable helpers as if they are HW pgtable entry pointers. (Mainly pmd level).

I wonder if we need to bite the bullet and explicitly separate the types? At each level, we have:

1. page table entry value
2. pointer to page table entry _value_ (e.g. pointer to pXX_t on stack)
3. pointer to page table entry in HW pgtable

Today, 1 is represented by pte_t, pmd_t, etc. 2 and 3 are represented by the same type; pte_t*, pmd_t*, etc.

If we create a new type for 3, it will both document and enforce when type 2 or type 3 is required.

e.g:

// pte_t: defined by arch.
typedef unsigned long pte_t;

// ptep_t: new opaque type that can't be dereferenced. struct __ptep_t;
typedef struct __ptep_t *ptep_t;

// getter/setter responsible for cast & deref as appropriate. pte_t ptep_get(ptep_t ptep)

{
	return READ_ONCE(*(pte_t *)ptep);
}

int do_stuff(void)

{
	// value on stack: ok
	pte_t mypte;

	// pointer to value on stack: ok
	pte_t *pmypte = &mypte;

	// handle to entry on stack: not allowed by compiler!
	ptep_t myptep = &mypte;

	// handle to entry in pgtable: ok
	ptep_t myptep = pte_offset_kernel(...);

	// read value of pgtable entry: ok
	pte_t val = ptep_get(myptep);

	// attempt to pass pointer to stack variable: not allowed by compiler!
	pte_t val = ptep_get(&mypte);

	// attempt to directly dereference ptep: not allowed by compiler!
	pte_t val = *myptep;
}

We could do this incrementally by initially typedefing ptep_t to be:
typedef pte_t *ptep_t;

Then we could flip the switch arch-by-arch to enable the stronger checking. We likely wouldn't need to convert arches that don't care.

I think by doing this, it will expose all the current issues and force us to fix them properly.

On the related subject of conversion to pXXp_get(); I've been looking into this and personally, I think we should have 2 helper flavours at each level:

- pXXd_get() optimizable by compiler; defaults to C dereference
- pXXd_get_once() single-copy-atomic and unmovable by compiler

It simplifies the converstion process, and reduces the risk of bugs significantly (go read about the arm32 issues discussed in Anshuman's series if you haven't done already).

I appreciate this is all probably a lot more work than you would prefer to sign up for, I'd be happy to collaborate if we get concensus that this approach makes sense. What do you think?

Thanks,
Ryan

#49 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 27 lines · Ryan Roberts
Quoted 18 lines · Samuel Holland
Quoted 17 lines · David Hildenbrand (Red Hat)
Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

Quoted 7 lines
Quoted 3 lines

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

Quoted 8 lines

From a quick look at the code, I think that some cases are solvable by refactoring to pass the value instead of the pointer, and leave it to the higher level decide how to read the value from the pointer - it knows if it is pointing to HW pgtable or if it's a (e.g) stack value.

But the more I look at the code, the more instances I find where pointers to stack variables are being passed to arch pgtable helpers as if they are HW pgtable entry pointers. (Mainly pmd level).

Ugh. We do need to nip this in the bud I think!

Quoted 23 lines

I wonder if we need to bite the bullet and explicitly separate the types? At each level, we have:

1. page table entry value
2. pointer to page table entry _value_ (e.g. pointer to pXX_t on stack)
3. pointer to page table entry in HW pgtable

Today, 1 is represented by pte_t, pmd_t, etc. 2 and 3 are represented by the same type; pte_t*, pmd_t*, etc.

If we create a new type for 3, it will both document and enforce when type 2 or type 3 is required.

e.g:

// pte_t: defined by arch.
typedef unsigned long pte_t;

// ptep_t: new opaque type that can't be dereferenced. struct __ptep_t;
typedef struct __ptep_t *ptep_t;

Quoted 5 lines

// getter/setter responsible for cast & deref as appropriate. pte_t ptep_get(ptep_t ptep)

{
	return READ_ONCE(*(pte_t *)ptep);
}

I think we've got ourselves in a jumble with pte vs ptep vs pteval vs. etc. etc. and we aren't always consistent with it.

So I think we ought to put 'hw' somewhere in the name.

And we can also now get away from the overly abbreviated names given we have the chance :)

So something like 'pte_hw_t' perhaps?

I like the general concept, though I think it's kinda gross to hide the fact that it's a pointer in the typedef _that_ directly.

So perhaps be less horrid if it was something like:

typedef struct {
	pte_t *ptr;
} pte_hw_t;

Perhaps?

Then could have:

pte_t hw_pte_get(pte_hw_t pte_hw)

{
	return READ_ONCE(*pte_hw.ptr);
}
Quoted 26 lines

int do_stuff(void)

{
	// value on stack: ok
	pte_t mypte;

	// pointer to value on stack: ok
	pte_t *pmypte = &mypte;

	// handle to entry on stack: not allowed by compiler!
	ptep_t myptep = &mypte;

	// handle to entry in pgtable: ok
	ptep_t myptep = pte_offset_kernel(...);

	// read value of pgtable entry: ok
	pte_t val = ptep_get(myptep);

	// attempt to pass pointer to stack variable: not allowed by compiler!
	pte_t val = ptep_get(&mypte);

	// attempt to directly dereference ptep: not allowed by compiler!
	pte_t val = *myptep;
}
Quoted 2 lines

We could do this incrementally by initially typedefing ptep_t to be:
typedef pte_t *ptep_t;

Hm yeah still hate the idea of typedef'ing this as a ptr so directly.

Obviously this would make an incremental thing a little harder, but could have this stuff on top of existing logic and make it incremental by changing logic bit-by-bit?

Quoted 6 lines

Then we could flip the switch arch-by-arch to enable the stronger checking. We likely wouldn't need to convert arches that don't care.

I think by doing this, it will expose all the current issues and force us to fix them properly.

Yeah this is nice.

Quoted 6 lines

On the related subject of conversion to pXXp_get(); I've been looking into this and personally, I think we should have 2 helper flavours at each level:

- pXXd_get() optimizable by compiler; defaults to C dereference
- pXXd_get_once() single-copy-atomic and unmovable by compiler

Yes!

There is some _real_ confusion about when and when we don't need to do this.

Though wouldn't having a typdef separating out a hw entry imply that hw entry -> get once, sw entry -> get?

Quoted 4 lines

It simplifies the converstion process, and reduces the risk of bugs significantly (go read about the arm32 issues discussed in Anshuman's series if you haven't done already).

Though I haven't read this series so can't remember actually if there were cases where even with hw entries we wanted to sometimes READ_ONCE() and sometimes not?

Quoted 8 lines

I appreciate this is all probably a lot more work than you would prefer to sign up for, I'd be happy to collaborate if we get concensus that this approach makes sense. What do you think?

Thanks,
Ryan

Thanks for this concept, overall very much in agreement!

Cheers, Lorenzo

reviewer
#50 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 68 lines · Lorenzo Stoakes
Quoted 27 lines · Ryan Roberts
Quoted 18 lines · Samuel Holland
Quoted 17 lines · David Hildenbrand (Red Hat)
Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

Quoted 7 lines
Quoted 3 lines

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

Quoted 8 lines

From a quick look at the code, I think that some cases are solvable by refactoring to pass the value instead of the pointer, and leave it to the higher level decide how to read the value from the pointer - it knows if it is pointing to HW pgtable or if it's a (e.g) stack value.

But the more I look at the code, the more instances I find where pointers to stack variables are being passed to arch pgtable helpers as if they are HW pgtable entry pointers. (Mainly pmd level).

Ugh. We do need to nip this in the bud I think!

Quoted 23 lines

I wonder if we need to bite the bullet and explicitly separate the types? At each level, we have:

1. page table entry value
2. pointer to page table entry _value_ (e.g. pointer to pXX_t on stack)
3. pointer to page table entry in HW pgtable

Today, 1 is represented by pte_t, pmd_t, etc. 2 and 3 are represented by the same type; pte_t*, pmd_t*, etc.

If we create a new type for 3, it will both document and enforce when type 2 or type 3 is required.

e.g:

// pte_t: defined by arch.
typedef unsigned long pte_t;

// ptep_t: new opaque type that can't be dereferenced. struct __ptep_t;
typedef struct __ptep_t *ptep_t;

Quoted 5 lines

// getter/setter responsible for cast & deref as appropriate. pte_t ptep_get(ptep_t ptep)

{
	return READ_ONCE(*(pte_t *)ptep);
}
Quoted 4 lines

I think we've got ourselves in a jumble with pte vs ptep vs pteval vs. etc. etc. and we aren't always consistent with it.

So I think we ought to put 'hw' somewhere in the name.

Yeah that would probably give the best end result. I was thinking that ptep/pXdp might reduce churn since we already use it in function names. Stack pointers are definitely a small minority so easier to change their convention.

But having an explicit "hw" would probably be best.

Quoted 5 lines

And we can also now get away from the overly abbreviated names given we have the chance :)

So something like 'pte_hw_t' perhaps?

sounds good. Or hw_pte_t? Then "pte_t" is still greppable and it better matches the hw_pte_get() that you have below.

Quoted 3 lines

I like the general concept, though I think it's kinda gross to hide the fact that it's a pointer in the typedef _that_ directly.

My aim was to have a type that you can't dereference, can't accidentally pass as a pte_t* and also can't increment/decrement/index.

This gives us a framework where the architecture can completely virtualize the pgtable if it likes; and the compiler can enforce that higher level code can't accidentally work around it.

I have a couple of use cases where these properties will come in handy; arm64 now defines 128-bit pgtables. We have a prototype adding it to the kernel, but at the moment it has to be a compile time descision so that all the generic code knows the size of the entries. It would be preferable to make it a boot time decision, based on the HW capabilities (or cmdline, ...). But for that, we need to better insulate the physical pgtables from the core-mm. This concept solves that.

Quoted 8 lines

So perhaps be less horrid if it was something like:

typedef struct {
	pte_t *ptr;
} pte_hw_t;

Perhaps?

I _think_ that works for the above, and it is certainly nicer.

pte_hw_t pte_table = pte_alloc(...);
for (i = 0; i < PTRS_PER_PTE; i++)

	hw_pte_get(pte_table[i]);

I think that would fail to compile, right? Which is what we want. Instead we need something like:

pte_hw_t hwpte = pte_alloc(...);
for (i = 0; i < PTRS_PER_PTE; i++, hwpte = hw_pte_next(hwpte))

	hw_pte_get(hwpte);
Quoted 34 lines

Then could have:

pte_t hw_pte_get(pte_hw_t pte_hw)

{
	return READ_ONCE(*pte_hw.ptr);
}
Quoted 26 lines

int do_stuff(void)

{
	// value on stack: ok
	pte_t mypte;

	// pointer to value on stack: ok
	pte_t *pmypte = &mypte;

	// handle to entry on stack: not allowed by compiler!
	ptep_t myptep = &mypte;

	// handle to entry in pgtable: ok
	ptep_t myptep = pte_offset_kernel(...);

	// read value of pgtable entry: ok
	pte_t val = ptep_get(myptep);

	// attempt to pass pointer to stack variable: not allowed by compiler!
	pte_t val = ptep_get(&mypte);

	// attempt to directly dereference ptep: not allowed by compiler!
	pte_t val = *myptep;
}
Quoted 4 lines
Quoted 2 lines

We could do this incrementally by initially typedefing ptep_t to be:
typedef pte_t *ptep_t;

Hm yeah still hate the idea of typedef'ing this as a ptr so directly.

What's the problem with it?

Quoted 4 lines

Obviously this would make an incremental thing a little harder, but could have this stuff on top of existing logic and make it incremental by changing logic bit-by-bit?

I'm not sure... sounds to me like we would need to convert absolutely everything including arches that are difficult for most people to test. With the "typedef pte_t *hw_pte_t;" approach, you can go bit-by-bit and leave those unloved arches alone entirely.

Quoted 14 lines
Quoted 7 lines

Then we could flip the switch arch-by-arch to enable the stronger checking. We likely wouldn't need to convert arches that don't care.

I think by doing this, it will expose all the current issues and force us to fix them properly.

Yeah this is nice.

Quoted 4 lines

On the related subject of conversion to pXXp_get(); I've been looking into this and personally, I think we should have 2 helper flavours at each level:

Quoted 6 lines
Quoted 2 lines

- pXXd_get() optimizable by compiler; defaults to C dereference
- pXXd_get_once() single-copy-atomic and unmovable by compiler

Yes!

There is some _real_ confusion about when and when we don't need to do this.

I think the requirements are basically this:

"_ONCE" gives 2 properties; single-copy-atomicity and compiler can't move/remove instructions.

SCA is important to prevent tearing if the HW can update the PTE concurrently with SW reading it (i.e. HW access/dirty) or if SW is reading without holding the PTL. But there are times when it doesn't matter if the PTE gets torn because you are only comparing the result using pte_none() or pte_same().

The "compiler can't move/remove" property (I'm sure there is a formal name for this?) is important for lockless walkers. Probably you could achieve similar results by using barrier()?

Quoted 3 lines

Though wouldn't having a typdef separating out a hw entry imply that hw entry -> get once, sw entry -> get?

No; you should never use the accessor methods for sw entries - they are just variables - read them normally. If all HW accesses use "once", then the compiler can't optimize away the accesses for the folded pgtable case.

Quoted 8 lines
Quoted 5 lines

It simplifies the converstion process, and reduces the risk of bugs significantly (go read about the arm32 issues discussed in Anshuman's series if you haven't done already).

Though I haven't read this series so can't remember actually if there were cases where even with hw entries we wanted to sometimes READ_ONCE() and sometimes not?

Yes exactly that.

Quoted 11 lines
Quoted 9 lines

I appreciate this is all probably a lot more work than you would prefer to sign up for, I'd be happy to collaborate if we get concensus that this approach makes sense. What do you think?

Thanks,
Ryan

Thanks for this concept, overall very much in agreement!

I think it would work but it's going to be a lot of churn. But if you think it's worth it and we'll be able to get it in, then I'm up for working on it in the background.

Quoted 2 lines

Cheers, Lorenzo

#51 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

Quoted 72 lines · Ryan Roberts
Quoted 71 lines · Lorenzo Stoakes
Quoted 27 lines · Ryan Roberts
Quoted 18 lines · Samuel Holland
Quoted 17 lines · David Hildenbrand (Red Hat)
Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

Quoted 7 lines
Quoted 3 lines

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

Quoted 8 lines

From a quick look at the code, I think that some cases are solvable by refactoring to pass the value instead of the pointer, and leave it to the higher level decide how to read the value from the pointer - it knows if it is pointing to HW pgtable or if it's a (e.g) stack value.

But the more I look at the code, the more instances I find where pointers to stack variables are being passed to arch pgtable helpers as if they are HW pgtable entry pointers. (Mainly pmd level).

Ugh. We do need to nip this in the bud I think!

Quoted 23 lines

I wonder if we need to bite the bullet and explicitly separate the types? At each level, we have:

1. page table entry value
2. pointer to page table entry _value_ (e.g. pointer to pXX_t on stack)
3. pointer to page table entry in HW pgtable

Today, 1 is represented by pte_t, pmd_t, etc. 2 and 3 are represented by the same type; pte_t*, pmd_t*, etc.

If we create a new type for 3, it will both document and enforce when type 2 or type 3 is required.

e.g:

// pte_t: defined by arch.
typedef unsigned long pte_t;

// ptep_t: new opaque type that can't be dereferenced. struct __ptep_t;
typedef struct __ptep_t *ptep_t;

Quoted 5 lines

// getter/setter responsible for cast & deref as appropriate. pte_t ptep_get(ptep_t ptep)

{
	return READ_ONCE(*(pte_t *)ptep);
}

I think we've got ourselves in a jumble with pte vs ptep vs pteval vs. etc. etc. and we aren't always consistent with it.

Quoted 7 lines
Quoted 1 line

So I think we ought to put 'hw' somewhere in the name.

Yeah that would probably give the best end result. I was thinking that ptep/pXdp might reduce churn since we already use it in function names. Stack pointers are definitely a small minority so easier to change their convention.

But having an explicit "hw" would probably be best.

Yeah, unfortunately I think the existing inconsistencies call for a clean break.

Quoted 9 lines
Quoted 6 lines

And we can also now get away from the overly abbreviated names given we have the chance :)

So something like 'pte_hw_t' perhaps?

sounds good. Or hw_pte_t? Then "pte_t" is still greppable and it better matches the hw_pte_get() that you have below.

Sure hw_pte_t works!

Quoted 7 lines
Quoted 4 lines

I like the general concept, though I think it's kinda gross to hide the fact that it's a pointer in the typedef _that_ directly.

My aim was to have a type that you can't dereference, can't accidentally pass as a pte_t* and also can't increment/decrement/index.

Right.

Quoted 4 lines

This gives us a framework where the architecture can completely virtualize the pgtable if it likes; and the compiler can enforce that higher level code can't accidentally work around it.

Yeah it's nice to be able to hide properties like this, I did think the use of an incomplete type pointer was quite nice there :)

Quoted 7 lines

I have a couple of use cases where these properties will come in handy; arm64 now defines 128-bit pgtables. We have a prototype adding it to the kernel, but at the moment it has to be a compile time descision so that all the generic code knows the size of the entries. It would be preferable to make it a boot time decision, based on the HW capabilities (or cmdline, ...). But for that, we need to better insulate the physical pgtables from the core-mm. This concept solves that.

NIce.

Quoted 10 lines
Quoted 9 lines

So perhaps be less horrid if it was something like:

typedef struct {
	pte_t *ptr;
} pte_hw_t;

Perhaps?

Quoted 8 lines

I _think_ that works for the above, and it is certainly nicer.

pte_hw_t pte_table = pte_alloc(...);
for (i = 0; i < PTRS_PER_PTE; i++)

	hw_pte_get(pte_table[i]);

I think that would fail to compile, right? Which is what we want. Instead we need something like:

Yeah that wouldn't work of course.

But wouldn't it also not work if you had an opaque type? As you'd then be dereferencing it? So it'd be something to solve for either approach right?

(An aside - this brings me back to the whole thing of differentiating between page _tables_ and _entries_, another thing we do badly at.)

Quoted 13 lines

pte_hw_t hwpte = pte_alloc(...);
for (i = 0; i < PTRS_PER_PTE; i++, hwpte = hw_pte_next(hwpte))

	hw_pte_get(hwpte);
Quoted 8 lines

Then could have:

pte_t hw_pte_get(pte_hw_t pte_hw)

{
	return READ_ONCE(*pte_hw.ptr);
}

Yeah could do something like that.

It might actually be nice to abstract the iterator-like behaviour too to the arch for e.g. your 128-bit entry stuff?

Quoted 26 lines
Quoted 26 lines
Quoted 26 lines

int do_stuff(void)

{
	// value on stack: ok
	pte_t mypte;

	// pointer to value on stack: ok
	pte_t *pmypte = &mypte;

	// handle to entry on stack: not allowed by compiler!
	ptep_t myptep = &mypte;

	// handle to entry in pgtable: ok
	ptep_t myptep = pte_offset_kernel(...);

	// read value of pgtable entry: ok
	pte_t val = ptep_get(myptep);

	// attempt to pass pointer to stack variable: not allowed by compiler!
	pte_t val = ptep_get(&mypte);

	// attempt to directly dereference ptep: not allowed by compiler!
	pte_t val = *myptep;
}
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

We could do this incrementally by initially typedefing ptep_t to be:
typedef pte_t *ptep_t;

Hm yeah still hate the idea of typedef'ing this as a ptr so directly.

What's the problem with it?

It's the fact you are making what looks like not-a-pointer into a pointer.

It's even more egregious for the non-opaque default thing of typedef pte_t *hw_pte_t - as then you truly are just making hw_pte_t not look like a pointer but behave like one.

Quoted 10 lines
Quoted 5 lines

Obviously this would make an incremental thing a little harder, but could have this stuff on top of existing logic and make it incremental by changing logic bit-by-bit?

I'm not sure... sounds to me like we would need to convert absolutely everything including arches that are difficult for most people to test. With the "typedef pte_t *hw_pte_t;" approach, you can go bit-by-bit and leave those unloved arches alone entirely.

Couldn't we have a generic thing for arches that don't yet use the type potentially? Might be a pain.

Quoted 27 lines
Quoted 15 lines
Quoted 8 lines

Then we could flip the switch arch-by-arch to enable the stronger checking. We likely wouldn't need to convert arches that don't care.

I think by doing this, it will expose all the current issues and force us to fix them properly.

Yeah this is nice.

Quoted 4 lines

On the related subject of conversion to pXXp_get(); I've been looking into this and personally, I think we should have 2 helper flavours at each level:

Quoted 6 lines
Quoted 2 lines

- pXXd_get() optimizable by compiler; defaults to C dereference
- pXXd_get_once() single-copy-atomic and unmovable by compiler

Yes!

There is some _real_ confusion about when and when we don't need to do this.

I think the requirements are basically this:

"_ONCE" gives 2 properties; single-copy-atomicity and compiler can't move/remove instructions.

Quoted 8 lines

SCA is important to prevent tearing if the HW can update the PTE concurrently with SW reading it (i.e. HW access/dirty) or if SW is reading without holding the PTL. But there are times when it doesn't matter if the PTE gets torn because you are only comparing the result using pte_none() or pte_same().

The "compiler can't move/remove" property (I'm sure there is a formal name for this?) is important for lockless walkers. Probably you could achieve similar results by using barrier()?

OK makes sense.

Quoted 8 lines
Quoted 4 lines

Though wouldn't having a typdef separating out a hw entry imply that hw entry -> get once, sw entry -> get?

No; you should never use the accessor methods for sw entries - they are just variables - read them normally. If all HW accesses use "once", then the compiler can't optimize away the accesses for the folded pgtable case.

Right, yes makes sense.

Quoted 11 lines
Quoted 9 lines
Quoted 6 lines

It simplifies the converstion process, and reduces the risk of bugs significantly (go read about the arm32 issues discussed in Anshuman's series if you haven't done already).

Though I haven't read this series so can't remember actually if there were cases where even with hw entries we wanted to sometimes READ_ONCE() and sometimes not?

Yes exactly that.

Yeah I guess based on whether the properties desired match the above or not.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

I appreciate this is all probably a lot more work than you would prefer to sign up for, I'd be happy to collaborate if we get concensus that this approach makes sense. What do you think?

Thanks,
Ryan

Quoted 5 lines
Quoted 1 line

Thanks for this concept, overall very much in agreement!

I think it would work but it's going to be a lot of churn. But if you think it's worth it and we'll be able to get it in, then I'm up for working on it in the background.

Well I am never averse to churn :)

I think at this point we have so much of a confusing mess of things going on in the page table logic that it makes sense to pay the churn price for this.

Quoted 4 lines
Quoted 3 lines

Cheers, Lorenzo

Thanks for looking into this,

Cheers, Lorenzo

#52 lore raw

Re: [PATCH v3 08/22] mm: Allow page table accessors to be non-idempotent

In reply to Ryan Roberts
Quoted 49 lines · Ryan Roberts
Quoted 18 lines · Samuel Holland
Quoted 17 lines · David Hildenbrand (Red Hat)
Quoted 9 lines · Ryan Roberts
Quoted 8 lines · Samuel Holland

Currently, some functions such as pte_offset_map() are passed both pointers to hardware page tables, and pointers to previously-read PMD entries on the stack. To ensure correctness in the first case, these functions must use the page table accessor function (pmdp_get()) to dereference the supplied pointer. However, this means pmdp_get() is called twice in the second case. This double call must be avoided if pmdp_get() applies some non-idempotent transformation to the value.

Quoted 4 lines
Quoted 2 lines

Avoid the double transformation by calling set_pmd() on the stack variables where necessary to keep set_pmd()/pmdp_get() calls balanced.

I don't think this is a good solution.

Agreed,

Quoted 7 lines
Quoted 3 lines

    set_pmd(&pmd, pmd);

is rather horrible.

I agree that this patch is ugly. The only way I see to avoid code like this is to refactor (or duplicate) the functions so no function takes pointers to both hardware page tables and on-stack page table entries. Is that sort of refactoring the right direction to go for v4?

From a quick look at the code, I think that some cases are solvable by
refactoring to pass the value instead of the pointer, and leave it to the higher level decide how to read the value from the pointer - it knows if it is pointing to HW pgtable or if it's a (e.g) stack value.

But the more I look at the code, the more instances I find where pointers to stack variables are being passed to arch pgtable helpers as if they are HW pgtable entry pointers. (Mainly pmd level).

I wonder if we need to bite the bullet and explicitly separate the types? At each level, we have:

1. page table entry value
2. pointer to page table entry _value_ (e.g. pointer to pXX_t on stack)
3. pointer to page table entry in HW pgtable

Today, 1 is represented by pte_t, pmd_t, etc. 2 and 3 are represented by the same type; pte_t*, pmd_t*, etc.

If we create a new type for 3, it will both document and enforce when type 2 or type 3 is required.

Quoted 8 lines

e.g:

// pte_t: defined by arch.
typedef unsigned long pte_t;

// ptep_t: new opaque type that can't be dereferenced. struct __ptep_t;
typedef struct __ptep_t *ptep_t;

This is what I had in mind when we last discussed this topic and I suggested a way forward to not play whack-a-mole with new users that do *ptep showing up.

Agreed that we ideally indicate that this is a HW PTE pointer that must be de-referenced through ptep_get() or similar. (maybe we'd find a new name for this set of functions).

I talked to Samuel at LPC, pointing him at the way XEN-pv implemented support for changing PFNs in ptes. We might not need all of that rework to move forward with the risc-v change.

Having that said, I also agree that this would be a cleanup worth having (which will result in quite a bit of churn :) ).

So if someone wants to bump up the patch count, speak now.

Signature · 3 lines
Cheers

David
#53 lore raw

PATCH v3 9/22 riscv: hibernate: Replace open-coded pXXp_get()

In reply to Samuel Holland

Use the semantically appropriate accessor function instead of open coding the implementation. This will become important once these functions start transforming the PTE value on some platforms.

---

(no changes since v2)

Changes in v2:
- New patch for v2

 arch/riscv/kernel/hibernate.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
arch/riscv/kernel/hibernate.c +9 -9
index 671b686c0158..2a9bc9d9e776 100644
@@ -171,7 +171,7 @@ static int temp_pgtable_map_pte(pmd_t *dst_pmdp, pmd_t *src_pmdp, unsigned long
 	pte_t *src_ptep;
 	pte_t *dst_ptep;
 
-	if (pmd_none(READ_ONCE(*dst_pmdp))) {
+	if (pmd_none(pmdp_get(dst_pmdp))) {
 		dst_ptep = (pte_t *)get_safe_page(GFP_ATOMIC);
 		if (!dst_ptep)
 			return -ENOMEM;
@@ -183,7 +183,7 @@ static int temp_pgtable_map_pte(pmd_t *dst_pmdp, pmd_t *src_pmdp, unsigned long
 	src_ptep = pte_offset_kernel(src_pmdp, start);
 
 	do {
-		pte_t pte = READ_ONCE(*src_ptep);
+		pte_t pte = ptep_get(src_ptep);
 
 		if (pte_present(pte))
 			set_pte(dst_ptep, __pte(pte_val(pte) | pgprot_val(prot)));
@@ -200,7 +200,7 @@ static int temp_pgtable_map_pmd(pud_t *dst_pudp, pud_t *src_pudp, unsigned long
 	pmd_t *src_pmdp;
 	pmd_t *dst_pmdp;
 
-	if (pud_none(READ_ONCE(*dst_pudp))) {
+	if (pud_none(pudp_get(dst_pudp))) {
 		dst_pmdp = (pmd_t *)get_safe_page(GFP_ATOMIC);
 		if (!dst_pmdp)
 			return -ENOMEM;
@@ -212,7 +212,7 @@ static int temp_pgtable_map_pmd(pud_t *dst_pudp, pud_t *src_pudp, unsigned long
 	src_pmdp = pmd_offset(src_pudp, start);
 
 	do {
-		pmd_t pmd = READ_ONCE(*src_pmdp);
+		pmd_t pmd = pmdp_get(src_pmdp);
 
 		next = pmd_addr_end(start, end);
 
@@ -239,7 +239,7 @@ static int temp_pgtable_map_pud(p4d_t *dst_p4dp, p4d_t *src_p4dp, unsigned long
 	pud_t *dst_pudp;
 	pud_t *src_pudp;
 
-	if (p4d_none(READ_ONCE(*dst_p4dp))) {
+	if (p4d_none(p4dp_get(dst_p4dp))) {
 		dst_pudp = (pud_t *)get_safe_page(GFP_ATOMIC);
 		if (!dst_pudp)
 			return -ENOMEM;
@@ -251,7 +251,7 @@ static int temp_pgtable_map_pud(p4d_t *dst_p4dp, p4d_t *src_p4dp, unsigned long
 	src_pudp = pud_offset(src_p4dp, start);
 
 	do {
-		pud_t pud = READ_ONCE(*src_pudp);
+		pud_t pud = pudp_get(src_pudp);
 
 		next = pud_addr_end(start, end);
 
@@ -278,7 +278,7 @@ static int temp_pgtable_map_p4d(pgd_t *dst_pgdp, pgd_t *src_pgdp, unsigned long
 	p4d_t *dst_p4dp;
 	p4d_t *src_p4dp;
 
-	if (pgd_none(READ_ONCE(*dst_pgdp))) {
+	if (pgd_none(pgdp_get(dst_pgdp))) {
 		dst_p4dp = (p4d_t *)get_safe_page(GFP_ATOMIC);
 		if (!dst_p4dp)
 			return -ENOMEM;
@@ -290,7 +290,7 @@ static int temp_pgtable_map_p4d(pgd_t *dst_pgdp, pgd_t *src_pgdp, unsigned long
 	src_p4dp = p4d_offset(src_pgdp, start);
 
 	do {
-		p4d_t p4d = READ_ONCE(*src_p4dp);
+		p4d_t p4d = p4dp_get(src_p4dp);
 
 		next = p4d_addr_end(start, end);
 
@@ -317,7 +317,7 @@ static int temp_pgtable_mapping(pgd_t *pgdp, unsigned long start, unsigned long
 	unsigned long ret;
 
 	do {
-		pgd_t pgd = READ_ONCE(*src_pgdp);
+		pgd_t pgd = pgdp_get(src_pgdp);
 
 		next = pgd_addr_end(start, end);
 
Signature · 1 line
2.47.2
#54 lore raw

PATCH v3 10/22 riscv: mm: Always use page table accessor functions

In reply to Samuel Holland

Use the semantically appropriate accessor function instead of a raw pointer dereference. This will become important once these functions start transforming the PTE value on some platforms.

---

(no changes since v2)

Changes in v2:
- New patch for v2

 arch/riscv/include/asm/pgtable.h |  8 ++--
 arch/riscv/kvm/gstage.c          |  6 +--
 arch/riscv/mm/init.c             | 68 +++++++++++++++++---------------
 arch/riscv/mm/pgtable.c          |  9 +++--
 4 files changed, 49 insertions(+), 42 deletions(-)
arch/riscv/include/asm/pgtable.h +5 -3
index 5a08eb5fe99f..acfd48f92010 100644
@@ -952,7 +952,7 @@ static inline pud_t pudp_huge_get_and_clear(struct mm_struct *mm,
 #ifdef CONFIG_SMP
 	pud_t pud = __pud(xchg(&pudp->pud, 0));
 #else
-	pud_t pud = *pudp;
+	pud_t pud = pudp_get(pudp);
 
 	pud_clear(pudp);
 #endif
@@ -1129,13 +1129,15 @@ extern unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)];
  */
 #define set_p4d_safe(p4dp, p4d) \
 ({ \
-	WARN_ON_ONCE(p4d_present(*p4dp) && !p4d_same(*p4dp, p4d)); \
+	p4d_t old = p4dp_get(p4dp); \
+	WARN_ON_ONCE(p4d_present(old) && !p4d_same(old, p4d)); \
 	set_p4d(p4dp, p4d); \
 })
 
 #define set_pgd_safe(pgdp, pgd) \
 ({ \
-	WARN_ON_ONCE(pgd_present(*pgdp) && !pgd_same(*pgdp, pgd)); \
+	pgd_t old = pgdp_get(pgdp); \
+	WARN_ON_ONCE(pgd_present(old) && !pgd_same(old, pgd)); \
 	set_pgd(pgdp, pgd); \
 })
 #endif /* !__ASSEMBLER__ */
arch/riscv/kvm/gstage.c +3 -3
index b67d60d722c2..297744e2ab5d 100644
@@ -154,7 +154,7 @@ int kvm_riscv_gstage_set_pte(struct kvm_gstage *gstage,
 		ptep = &next_ptep[gstage_pte_index(map->addr, current_level)];
 	}
 
-	if (pte_val(*ptep) != pte_val(map->pte)) {
+	if (pte_val(ptep_get(ptep)) != pte_val(map->pte)) {
 		set_pte(ptep, map->pte);
 		if (gstage_pte_leaf(ptep))
 			gstage_tlb_flush(gstage, current_level, map->addr);
@@ -241,12 +241,12 @@ void kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr,
 		if (op == GSTAGE_OP_CLEAR)
 			put_page(virt_to_page(next_ptep));
 	} else {
-		old_pte = *ptep;
+		old_pte = ptep_get(ptep);
 		if (op == GSTAGE_OP_CLEAR)
 			set_pte(ptep, __pte(0));
 		else if (op == GSTAGE_OP_WP)
 			set_pte(ptep, __pte(pte_val(ptep_get(ptep)) & ~_PAGE_WRITE));
-		if (pte_val(*ptep) != pte_val(old_pte))
+		if (pte_val(ptep_get(ptep)) != pte_val(old_pte))
 			gstage_tlb_flush(gstage, ptep_level, addr);
 	}
 }
arch/riscv/mm/init.c +36 -32

181 lines not on this page · raw message

arch/riscv/mm/pgtable.c +5 -4
index 8b6c0a112a8d..c4b85a828797 100644
@@ -95,8 +95,8 @@ int pud_free_pmd_page(pud_t *pud, unsigned long addr)
 	flush_tlb_kernel_range(addr, addr + PUD_SIZE);
 
 	for (i = 0; i < PTRS_PER_PMD; i++) {
-		if (!pmd_none(pmd[i])) {
-			pte_t *pte = (pte_t *)pmd_page_vaddr(pmd[i]);
+		if (!pmd_none(pmdp_get(pmd + i))) {
+			pte_t *pte = (pte_t *)pmd_page_vaddr(pmdp_get(pmd + i));
 
 			pte_free_kernel(NULL, pte);
 		}
@@ -158,8 +158,9 @@ pmd_t pmdp_collapse_flush(struct vm_area_struct *vma,
 pud_t pudp_invalidate(struct vm_area_struct *vma, unsigned long address,
 		      pud_t *pudp)
 {
-	VM_WARN_ON_ONCE(!pud_present(*pudp));
-	pud_t old = pudp_establish(vma, address, pudp, pud_mkinvalid(*pudp));
+	VM_WARN_ON_ONCE(!pud_present(pudp_get(pudp)));
+	pud_t old = pudp_establish(vma, address, pudp,
+				   pud_mkinvalid(pudp_get(pudp)));
 
 	flush_pud_tlb_range(vma, address, address + HPAGE_PUD_SIZE);
 	return old;
Signature · 1 line
2.47.2
#55 lore raw

PATCH v3 11/22 riscv: mm: Simplify set_p4d() and set_pgd()

In reply to Samuel Holland

RISC-V uses the same page table entry format and has the same atomicity requirements at all page table levels, so these setter functions use the same underlying implementation at all levels. Checking the translation mode to pick between two identical branches only serves to make these functions less efficient.

---

(no changes since v2)

Changes in v2:
- New patch for v2

 arch/riscv/include/asm/pgtable-64.h | 10 ++--------
 1 file changed, 2 insertions(+), 8 deletions(-)
arch/riscv/include/asm/pgtable-64.h +2 -8
index 6e789fa58514..5532f8515450 100644
@@ -275,10 +275,7 @@ static inline unsigned long _pmd_pfn(pmd_t pmd)
 
 static inline void set_p4d(p4d_t *p4dp, p4d_t p4d)
 {
-	if (pgtable_l4_enabled)
-		WRITE_ONCE(*p4dp, p4d);
-	else
-		set_pud((pud_t *)p4dp, (pud_t){ p4d_val(p4d) });
+	WRITE_ONCE(*p4dp, p4d);
 }
 
 static inline int p4d_none(p4d_t p4d)
@@ -342,10 +339,7 @@ pud_t *pud_offset(p4d_t *p4d, unsigned long address);
 
 static inline void set_pgd(pgd_t *pgdp, pgd_t pgd)
 {
-	if (pgtable_l5_enabled)
-		WRITE_ONCE(*pgdp, pgd);
-	else
-		set_p4d((p4d_t *)pgdp, (p4d_t){ pgd_val(pgd) });
+	WRITE_ONCE(*pgdp, pgd);
 }
 
 static inline int pgd_none(pgd_t pgd)
Signature · 1 line
2.47.2
#56 lore raw

PATCH v3 12/22 riscv: mm: Deduplicate _PAGE_CHG_MASK definition

In reply to Samuel Holland

The two existing definitions are equivalent because _PAGE_MTMASK is defined as 0 on riscv32.

---

(no changes since v1)

 arch/riscv/include/asm/pgtable-32.h | 5 -----
 arch/riscv/include/asm/pgtable-64.h | 7 -------
 arch/riscv/include/asm/pgtable.h    | 6 ++++++
 3 files changed, 6 insertions(+), 12 deletions(-)
arch/riscv/include/asm/pgtable-32.h +0 -5
index 00f3369570a8..fa6c87015c48 100644
@@ -28,11 +28,6 @@
 #define _PAGE_IO		0
 #define _PAGE_MTMASK		0
 
-/* Set of bits to preserve across pte_modify() */
-#define _PAGE_CHG_MASK  (~(unsigned long)(_PAGE_PRESENT | _PAGE_READ |	\
-					  _PAGE_WRITE | _PAGE_EXEC |	\
-					  _PAGE_USER | _PAGE_GLOBAL))
-
 static const __maybe_unused int pgtable_l4_enabled;
 static const __maybe_unused int pgtable_l5_enabled;
 
arch/riscv/include/asm/pgtable-64.h +0 -7
index 5532f8515450..093f0f41fd23 100644
@@ -66,7 +66,6 @@ typedef struct {
 
 #define pmd_val(x)      ((x).pmd)
 #define __pmd(x)        ((pmd_t) { (x) })
-
 #define PTRS_PER_PMD    (PAGE_SIZE / sizeof(pmd_t))
 
 #define MAX_POSSIBLE_PHYSMEM_BITS 56
@@ -168,12 +167,6 @@ static inline u64 riscv_page_io(void)
 #define _PAGE_IO		riscv_page_io()
 #define _PAGE_MTMASK		riscv_page_mtmask()
 
-/* Set of bits to preserve across pte_modify() */
-#define _PAGE_CHG_MASK  (~(unsigned long)(_PAGE_PRESENT | _PAGE_READ |	\
-					  _PAGE_WRITE | _PAGE_EXEC |	\
-					  _PAGE_USER | _PAGE_GLOBAL |	\
-					  _PAGE_MTMASK))
-
 static inline int pud_present(pud_t pud)
 {
 	return (pud_val(pud) & _PAGE_PRESENT);
arch/riscv/include/asm/pgtable.h +6 -0
index acfd48f92010..ba2fb1d475a3 100644
@@ -207,6 +207,12 @@ extern struct pt_alloc_ops pt_ops __meminitdata;
 #define _PAGE_IOREMAP	((_PAGE_KERNEL & ~_PAGE_MTMASK) | _PAGE_IO)
 #define PAGE_KERNEL_IO		__pgprot(_PAGE_IOREMAP)
 
+/* Set of bits to preserve across pte_modify() */
+#define _PAGE_CHG_MASK  (~(unsigned long)(_PAGE_PRESENT | _PAGE_READ |	\
+					  _PAGE_WRITE | _PAGE_EXEC |	\
+					  _PAGE_USER | _PAGE_GLOBAL |	\
+					  _PAGE_MTMASK))
+
 extern pgd_t swapper_pg_dir[];
 extern pgd_t trampoline_pg_dir[];
 extern pgd_t early_pg_dir[];
Signature · 1 line
2.47.2
#57 lore raw

PATCH v3 13/22 riscv: ptdump: Only show N and MT bits when enabled in the kernel

In reply to Samuel Holland

When the Svnapot or Svpbmt extension is not implemented, the corresponding page table bits are reserved, and must be zero. There is no need to show them in the ptdump output.

When the Kconfig option for an extension is disabled, we assume it is not implemented. In that case, the kernel may provide a fallback definition for the fields, like how _PAGE_MTMASK is defined on riscv32. Using those fallback definitions in ptdump would produce incorrect results. To avoid this, hide the fields from the ptdump output.

---

(no changes since v1)

 arch/riscv/mm/ptdump.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
arch/riscv/mm/ptdump.c +4 -2
index 34299c2b231f..0dd6ee282953 100644
@@ -134,11 +134,13 @@ struct prot_bits {
 
 static const struct prot_bits pte_bits[] = {
 	{
-#ifdef CONFIG_64BIT
+#ifdef CONFIG_RISCV_ISA_SVNAPOT
 		.mask = _PAGE_NAPOT,
 		.set = "N",
 		.clear = ".",
 	}, {
+#endif
+#ifdef CONFIG_RISCV_ISA_SVPBMT
 		.mask = _PAGE_MTMASK_SVPBMT,
 		.set = "MT(%s)",
 		.clear = "  ..  ",
@@ -214,7 +216,7 @@ static void dump_prot(struct pg_state *st)
 		if (val) {
 			if (pte_bits[i].mask == _PAGE_SOFT)
 				sprintf(s, pte_bits[i].set, val >> 8);
-#ifdef CONFIG_64BIT
+#ifdef CONFIG_RISCV_ISA_SVPBMT
 			else if (pte_bits[i].mask == _PAGE_MTMASK_SVPBMT) {
 				if (val == _PAGE_NOCACHE_SVPBMT)
 					sprintf(s, pte_bits[i].set, "NC");
Signature · 1 line
2.47.2
#58 lore raw

PATCH v3 14/22 riscv: mm: Fix up memory types when writing page tables

In reply to Samuel Holland

Currently, Linux on RISC-V has three ways to specify the cacheability and ordering PMAs of a page:
1) Do nothing; assume the system is entirely cache-coherent and rely on the hardware for any ordering requirements
2) Use the page table bits specified by Svpbmt
3) Use the page table bits specified by XTheadMae

To support all three methods, the kernel dynamically determines the definitions of the _PAGE_NOCACHE and _PAGE_IO fields. However, this alone is not sufficient, as XTheadMae uses a nonzero memory type value for normal memory pages. So the kernel uses an additional alternative sequence (ALT_THEAD_PMA) to insert the correct memory type when generating page table entries.

Some RISC-V platforms use a fourth method to specify the cacheability of a page of RAM: RAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined PMAs. Software selects the PMAs for a page by choosing the corresponding PFN from one of the available physical address ranges. Like for XTheadMae, this strategy also requires applying a transformation when writing page table entries. Since these physical memory aliases should be invisible to the rest of the kernel, the opposite transformation must be applied when reading page table entries.

However, with this last method of specifying PMAs, there is no inherent way to indicate the cacheability of a page in the pgprot_t value, since the PFN itself determines cacheability. This implementation reuses the PTE bits from Svpbmt, as Svpbmt is the standard RISC-V extension, and thus ought to be the most common way to indicate per-page PMAs. Thus, the Svpbmt variant of _PAGE_NOCACHE and _PAGE_IO is made available even when the CPU does not support the extension.

It turns out that with some clever bit manipulation, it is just as efficient to transform all three Svpbmt memory type values to the corresponding XTheadMae values, as it is to check for and insert the one XTheadMae memory type value for normal memory. Thus, we implement XTheadMae as a variant on top of Svpbmt. This allows the _PAGE_NOCACHE and _PAGE_IO definitions to be compile-time constants, and centralizes all memory type handling to a single set of alternative macros.

However, there is a tradeoff for platforms relying on hardware for all memory type handling: the memory type PTE bits must now be masked off when writing page table entries, whereas previously no transformation was needed.

As a side effect, since the inverse transformation is applied when reading back page table entries, this change fixes the reporting of the memory type bits from ptdump on platforms with XTheadMae.

---

(no changes since v2)

Changes in v2:
- Keep Kconfig options for each PBMT variant separate/non-overlapping
- Move fixup code sequences to set_pXX() and pXXp_get()
- Only define ALT_UNFIX_MT in configurations that need it
- Improve inline documentation of ALT_FIXUP_MT/ALT_UNFIX_MT

 arch/riscv/include/asm/errata_list.h |  45 -------
 arch/riscv/include/asm/pgtable-32.h  |   3 +
 arch/riscv/include/asm/pgtable-64.h  | 171 ++++++++++++++++++++++-----
 arch/riscv/include/asm/pgtable.h     |  47 ++++----
 arch/riscv/mm/pgtable.c              |  14 +--
 arch/riscv/mm/ptdump.c               |  12 +-
 6 files changed, 174 insertions(+), 118 deletions(-)
arch/riscv/include/asm/errata_list.h +0 -45
index 6694b5ccdcf8..fa03021b7074 100644
@@ -53,51 +53,6 @@ asm(ALTERNATIVE(	\
 	: /* no inputs */	\
 	: "memory")
 
-/*
- * _val is marked as "will be overwritten", so need to set it to 0
- * in the default case.
- */
-#define ALT_SVPBMT_SHIFT 61
-#define ALT_THEAD_MAE_SHIFT 59
-#define ALT_SVPBMT(_val, prot)						\
-asm(ALTERNATIVE_2("li %0, 0\t\nnop",					\
-		  "li %0, %1\t\nslli %0,%0,%3", 0,			\
-			RISCV_ISA_EXT_SVPBMT, CONFIG_RISCV_ISA_SVPBMT,	\
-		  "li %0, %2\t\nslli %0,%0,%4", THEAD_VENDOR_ID,	\
-			ERRATA_THEAD_MAE, CONFIG_ERRATA_THEAD_MAE)	\
-		: "=r"(_val)						\
-		: "I"(prot##_SVPBMT >> ALT_SVPBMT_SHIFT),		\
-		  "I"(prot##_THEAD >> ALT_THEAD_MAE_SHIFT),		\
-		  "I"(ALT_SVPBMT_SHIFT),				\
-		  "I"(ALT_THEAD_MAE_SHIFT))
-
-#ifdef CONFIG_ERRATA_THEAD_MAE
-/*
- * IO/NOCACHE memory types are handled together with svpbmt,
- * so on T-Head chips, check if no other memory type is set,
- * and set the non-0 PMA type if applicable.
- */
-#define ALT_THEAD_PMA(_val)						\
-asm volatile(ALTERNATIVE(						\
-	__nops(7),							\
-	"li      t3, %1\n\t"						\
-	"slli    t3, t3, %3\n\t"					\
-	"and     t3, %0, t3\n\t"					\
-	"bne     t3, zero, 2f\n\t"					\
-	"li      t3, %2\n\t"						\
-	"slli    t3, t3, %3\n\t"					\
-	"or      %0, %0, t3\n\t"					\
-	"2:",  THEAD_VENDOR_ID,						\
-		ERRATA_THEAD_MAE, CONFIG_ERRATA_THEAD_MAE)		\
-	: "+r"(_val)							\
-	: "I"(_PAGE_MTMASK_THEAD >> ALT_THEAD_MAE_SHIFT),		\
-	  "I"(_PAGE_PMA_THEAD >> ALT_THEAD_MAE_SHIFT),			\
-	  "I"(ALT_THEAD_MAE_SHIFT)					\
-	: "t3")
-#else
-#define ALT_THEAD_PMA(_val)
-#endif
-
 #define ALT_CMO_OP(_op, _start, _size, _cachesize)			\
 asm volatile(ALTERNATIVE(						\
 	__nops(5),							\
arch/riscv/include/asm/pgtable-32.h +3 -0
index fa6c87015c48..90ef35a7c1a5 100644
@@ -28,6 +28,9 @@
 #define _PAGE_IO		0
 #define _PAGE_MTMASK		0
 
+#define ALT_FIXUP_MT(_val)
+#define ALT_UNFIX_MT(_val)
+
 static const __maybe_unused int pgtable_l4_enabled;
 static const __maybe_unused int pgtable_l5_enabled;
 
arch/riscv/include/asm/pgtable-64.h +140 -31

254 lines not on this page · raw message

arch/riscv/include/asm/pgtable.h +21 -26

109 lines not on this page · raw message

arch/riscv/mm/pgtable.c +4 -10
index c4b85a828797..604744d6924f 100644
@@ -42,20 +42,14 @@ int ptep_test_and_clear_young(struct vm_area_struct *vma,
 EXPORT_SYMBOL_GPL(ptep_test_and_clear_young);
 
 #ifdef CONFIG_64BIT
-pud_t *pud_offset(p4d_t *p4d, unsigned long address)
+pud_t *pud_offset(p4d_t *p4dp, unsigned long address)
 {
-	if (pgtable_l4_enabled)
-		return p4d_pgtable(p4dp_get(p4d)) + pud_index(address);
-
-	return (pud_t *)p4d;
+	return pud_offset_lockless(p4dp, p4dp_get(p4dp), address);
 }
 
-p4d_t *p4d_offset(pgd_t *pgd, unsigned long address)
+p4d_t *p4d_offset(pgd_t *pgdp, unsigned long address)
 {
-	if (pgtable_l5_enabled)
-		return pgd_pgtable(pgdp_get(pgd)) + p4d_index(address);
-
-	return (p4d_t *)pgd;
+	return p4d_offset_lockless(pgdp, pgdp_get(pgdp), address);
 }
 #endif
 
arch/riscv/mm/ptdump.c +6 -6
index 0dd6ee282953..763ffde8ab5e 100644
@@ -140,8 +140,8 @@ static const struct prot_bits pte_bits[] = {
 		.clear = ".",
 	}, {
 #endif
-#ifdef CONFIG_RISCV_ISA_SVPBMT
-		.mask = _PAGE_MTMASK_SVPBMT,
+#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
+		.mask = _PAGE_MTMASK,
 		.set = "MT(%s)",
 		.clear = "  ..  ",
 	}, {
@@ -216,11 +216,11 @@ static void dump_prot(struct pg_state *st)
 		if (val) {
 			if (pte_bits[i].mask == _PAGE_SOFT)
 				sprintf(s, pte_bits[i].set, val >> 8);
-#ifdef CONFIG_RISCV_ISA_SVPBMT
-			else if (pte_bits[i].mask == _PAGE_MTMASK_SVPBMT) {
-				if (val == _PAGE_NOCACHE_SVPBMT)
+#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
+			else if (pte_bits[i].mask == _PAGE_MTMASK) {
+				if (val == _PAGE_NOCACHE)
 					sprintf(s, pte_bits[i].set, "NC");
-				else if (val == _PAGE_IO_SVPBMT)
+				else if (val == _PAGE_IO)
 					sprintf(s, pte_bits[i].set, "IO");
 				else
 					sprintf(s, pte_bits[i].set, "??");
Signature · 1 line
2.47.2
#59 lore raw

PATCH v3 15/22 riscv: mm: Expose all page table bits to assembly code

In reply to Samuel Holland

pgtable-32.h and pgtable-64.h are not usable by assembly code files, so move all page table field definitions to pgtable-bits.h. This allows handling more complex PTE transformations in out-of-line assembly code.

---

(no changes since v1)

 arch/riscv/include/asm/pgtable-32.h   | 11 -------
 arch/riscv/include/asm/pgtable-64.h   | 30 -------------------
 arch/riscv/include/asm/pgtable-bits.h | 42 +++++++++++++++++++++++++--
 3 files changed, 40 insertions(+), 43 deletions(-)
arch/riscv/include/asm/pgtable-32.h +0 -11
index 90ef35a7c1a5..eb556ab95732 100644
@@ -17,17 +17,6 @@
 
 #define MAX_POSSIBLE_PHYSMEM_BITS 34
 
-/*
- * rv32 PTE format:
- * | XLEN-1  10 | 9             8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0
- *       PFN      reserved for SW   D   A   G   U   X   W   R   V
- */
-#define _PAGE_PFN_MASK  GENMASK(31, 10)
-
-#define _PAGE_NOCACHE		0
-#define _PAGE_IO		0
-#define _PAGE_MTMASK		0
-
 #define ALT_FIXUP_MT(_val)
 #define ALT_UNFIX_MT(_val)
 
arch/riscv/include/asm/pgtable-64.h +0 -30
index aad34c754325..fa2c1dcb6f72 100644
@@ -70,20 +70,6 @@ typedef struct {
 
 #define MAX_POSSIBLE_PHYSMEM_BITS 56
 
-/*
- * rv64 PTE format:
- * | 63 | 62 61 | 60 54 | 53  10 | 9             8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0
- *   N      MT     RSV    PFN      reserved for SW   D   A   G   U   X   W   R   V
- */
-#define _PAGE_PFN_MASK  GENMASK(53, 10)
-
-/*
- * [63] Svnapot definitions:
- * 0 Svnapot disabled
- * 1 Svnapot enabled
- */
-#define _PAGE_NAPOT_SHIFT	63
-#define _PAGE_NAPOT		BIT(_PAGE_NAPOT_SHIFT)
 /*
  * Only 64KB (order 4) napot ptes supported.
  */
@@ -113,18 +99,6 @@ enum napot_cont_order {
 
 #if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
 
-/*
- * [62:61] Svpbmt Memory Type definitions:
- *
- *  00 - PMA    Normal Cacheable, No change to implied PMA memory type
- *  01 - NC     Non-cacheable, idempotent, weakly-ordered Main Memory
- *  10 - IO     Non-cacheable, non-idempotent, strongly-ordered I/O memory
- *  11 - Rsvd   Reserved for future standard use
- */
-#define _PAGE_NOCACHE		(1UL << 61)
-#define _PAGE_IO		(2UL << 61)
-#define _PAGE_MTMASK		(3UL << 61)
-
 /*
  * ALT_FIXUP_MT
  *
@@ -176,10 +150,6 @@ enum napot_cont_order {
 
 #else
 
-#define _PAGE_NOCACHE		0
-#define _PAGE_IO		0
-#define _PAGE_MTMASK		0
-
 #define ALT_FIXUP_MT(_val)
 
 #endif /* CONFIG_RISCV_ISA_SVPBMT || CONFIG_ERRATA_THEAD_MAE */
arch/riscv/include/asm/pgtable-bits.h +40 -2

60 lines not on this page · raw message

Signature · 1 line
2.47.2
#60 lore raw

PATCH v3 16/22 riscv: alternative: Add an ALTERNATIVE_3 macro

In reply to Samuel Holland

ALT_FIXUP_MT() is already using ALTERNATIVE_2(), but it needs to be extended to handle a fourth case. Add ALTERNATIVE_3(), which extends ALTERNATIVE_2() with another block of new content.

---

(no changes since v2)

Changes in v2:
- Fix erroneously-escaped newline in assembly ALTERNATIVE_CFG_3 macro

 arch/riscv/include/asm/alternative-macros.h | 45 ++++++++++++++++++---
 1 file changed, 40 insertions(+), 5 deletions(-)
arch/riscv/include/asm/alternative-macros.h +40 -5
index 9619bd5c8eba..e8bf384da5c2 100644
@@ -50,8 +50,17 @@
 	ALT_NEW_CONTENT \vendor_id_2, \patch_id_2, \enable_2, "\new_c_2"
 .endm
 
+.macro ALTERNATIVE_CFG_3 old_c, new_c_1, vendor_id_1, patch_id_1, enable_1,	\
+				new_c_2, vendor_id_2, patch_id_2, enable_2,	\
+				new_c_3, vendor_id_3, patch_id_3, enable_3
+	ALTERNATIVE_CFG_2 "\old_c", "\new_c_1", \vendor_id_1, \patch_id_1, \enable_1 \
+				    "\new_c_2", \vendor_id_2, \patch_id_2, \enable_2
+	ALT_NEW_CONTENT \vendor_id_3, \patch_id_3, \enable_3, "\new_c_3"
+.endm
+
 #define __ALTERNATIVE_CFG(...)		ALTERNATIVE_CFG __VA_ARGS__
 #define __ALTERNATIVE_CFG_2(...)	ALTERNATIVE_CFG_2 __VA_ARGS__
+#define __ALTERNATIVE_CFG_3(...)	ALTERNATIVE_CFG_3 __VA_ARGS__
 
 #else /* !__ASSEMBLER__ */
 
@@ -98,6 +107,13 @@
 	__ALTERNATIVE_CFG(old_c, new_c_1, vendor_id_1, patch_id_1, enable_1)	\
 	ALT_NEW_CONTENT(vendor_id_2, patch_id_2, enable_2, new_c_2)
 
+#define __ALTERNATIVE_CFG_3(old_c, new_c_1, vendor_id_1, patch_id_1, enable_1,	\
+				   new_c_2, vendor_id_2, patch_id_2, enable_2,	\
+				   new_c_3, vendor_id_3, patch_id_3, enable_3)	\
+	__ALTERNATIVE_CFG_2(old_c, new_c_1, vendor_id_1, patch_id_1, enable_1,	\
+				   new_c_2, vendor_id_2, patch_id_2, enable_2)	\
+	ALT_NEW_CONTENT(vendor_id_3, patch_id_3, enable_3, new_c_3)
+
 #endif /* __ASSEMBLER__ */
 
 #define _ALTERNATIVE_CFG(old_c, new_c, vendor_id, patch_id, CONFIG_k)	\
@@ -108,6 +124,13 @@
 	__ALTERNATIVE_CFG_2(old_c, new_c_1, vendor_id_1, patch_id_1, IS_ENABLED(CONFIG_k_1),	\
 				   new_c_2, vendor_id_2, patch_id_2, IS_ENABLED(CONFIG_k_2))
 
+#define _ALTERNATIVE_CFG_3(old_c, new_c_1, vendor_id_1, patch_id_1, CONFIG_k_1,		\
+				  new_c_2, vendor_id_2, patch_id_2, CONFIG_k_2,		\
+				  new_c_3, vendor_id_3, patch_id_3, CONFIG_k_3)		\
+	__ALTERNATIVE_CFG_3(old_c, new_c_1, vendor_id_1, patch_id_1, IS_ENABLED(CONFIG_k_1),	\
+				   new_c_2, vendor_id_2, patch_id_2, IS_ENABLED(CONFIG_k_2),	\
+				   new_c_3, vendor_id_3, patch_id_3, IS_ENABLED(CONFIG_k_3))
+
 #else /* CONFIG_RISCV_ALTERNATIVE */
 #ifdef __ASSEMBLER__
 
@@ -118,11 +141,17 @@
 #define __ALTERNATIVE_CFG(old_c, ...)		ALTERNATIVE_CFG old_c
 #define __ALTERNATIVE_CFG_2(old_c, ...)		ALTERNATIVE_CFG old_c
 
+#define _ALTERNATIVE_CFG_3(old_c, ...)	\
+	ALTERNATIVE_CFG old_c
+
 #else /* !__ASSEMBLER__ */
 
 #define __ALTERNATIVE_CFG(old_c, ...)		old_c "\n"
 #define __ALTERNATIVE_CFG_2(old_c, ...)		old_c "\n"
 
+#define _ALTERNATIVE_CFG_3(old_c, ...)	\
+	__ALTERNATIVE_CFG(old_c)
+
 #endif /* __ASSEMBLER__ */
 
 #define _ALTERNATIVE_CFG(old_c, ...)		__ALTERNATIVE_CFG(old_c)
@@ -147,15 +176,21 @@
 	_ALTERNATIVE_CFG(old_content, new_content, vendor_id, patch_id, CONFIG_k)
 
 /*
- * A vendor wants to replace an old_content, but another vendor has used
- * ALTERNATIVE() to patch its customized content at the same location. In
- * this case, this vendor can create a new macro ALTERNATIVE_2() based
- * on the following sample code and then replace ALTERNATIVE() with
- * ALTERNATIVE_2() to append its customized content.
+ * Variant of ALTERNATIVE() that supports two sets of replacement content.
  */
 #define ALTERNATIVE_2(old_content, new_content_1, vendor_id_1, patch_id_1, CONFIG_k_1,		\
 				   new_content_2, vendor_id_2, patch_id_2, CONFIG_k_2)		\
 	_ALTERNATIVE_CFG_2(old_content, new_content_1, vendor_id_1, patch_id_1, CONFIG_k_1,	\
 					new_content_2, vendor_id_2, patch_id_2, CONFIG_k_2)
 
+/*
+ * Variant of ALTERNATIVE() that supports three sets of replacement content.
+ */
+#define ALTERNATIVE_3(old_content, new_content_1, vendor_id_1, patch_id_1, CONFIG_k_1,		\
+				   new_content_2, vendor_id_2, patch_id_2, CONFIG_k_2,		\
+				   new_content_3, vendor_id_3, patch_id_3, CONFIG_k_3)		\
+	_ALTERNATIVE_CFG_3(old_content, new_content_1, vendor_id_1, patch_id_1, CONFIG_k_1,	\
+					new_content_2, vendor_id_2, patch_id_2, CONFIG_k_2,	\
+					new_content_3, vendor_id_3, patch_id_3, CONFIG_k_3)
+
 #endif
Signature · 1 line
2.47.2
#61 lore raw

PATCH v3 17/22 riscv: alternative: Allow calls with alternate link registers

In reply to Samuel Holland

Alternative assembly code may wish to use an alternate link register to minimize the number of clobbered registers. Apply the offset fix to all jalr (not jr) instructions, i.e. where rd is not x0.

---

(no changes since v1)

 arch/riscv/kernel/alternative.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/riscv/kernel/alternative.c +2 -2
index 7642704c7f18..e3eb2585faea 100644
@@ -126,8 +126,8 @@ void riscv_alternative_fix_offsets(void *alt_ptr, unsigned int len,
 			if (!riscv_insn_is_jalr(insn2))
 				continue;
 
-			/* if instruction pair is a call, it will use the ra register */
-			if (RV_EXTRACT_RD_REG(insn) != 1)
+			/* if instruction pair is a call, it will save a link register */
+			if (RV_EXTRACT_RD_REG(insn) == 0)
 				continue;
 
 			riscv_alternative_fix_auipc_jalr(alt_ptr + i * sizeof(u32),
Signature · 1 line
2.47.2
#62 lore raw

PATCH v3 18/22 riscv: Fix logic for selecting DMA_DIRECT_REMAP

In reply to Samuel Holland

DMA_DIRECT_REMAP allows the kernel to make pages coherent for DMA by remapping them in the page tables with a different pgprot_t value. On RISC-V, this is supported by the page-based memory type extensions (Svpbmt and Xtheadmae). It is independent from the software cache maintenance extensions (Zicbom and Xtheadcmo).

---

Changes in v3:
- New patch for v3

 arch/riscv/Kconfig        | 2 +-
 arch/riscv/Kconfig.errata | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
arch/riscv/Kconfig +1 -1
index fadec20b87a8..cf5a4b5cdcd4 100644
@@ -598,6 +598,7 @@ config RISCV_ISA_SVPBMT
 	depends on 64BIT && MMU
 	depends on RISCV_ALTERNATIVE
 	default y
+	select DMA_DIRECT_REMAP
 	help
 	   Add support for the Svpbmt ISA-extension (Supervisor-mode:
 	   page-based memory types) in the kernel when it is detected at boot.
@@ -811,7 +812,6 @@ config RISCV_ISA_ZICBOM
 	depends on RISCV_ALTERNATIVE
 	default y
 	select RISCV_DMA_NONCOHERENT
-	select DMA_DIRECT_REMAP
 	help
 	   Add support for the Zicbom extension (Cache Block Management
 	   Operations) and enable its use in the kernel when it is detected
arch/riscv/Kconfig.errata +1 -1
index aca9b0cfcfec..46a353a266e5 100644
@@ -108,6 +108,7 @@ config ERRATA_THEAD
 config ERRATA_THEAD_MAE
 	bool "Apply T-Head's memory attribute extension (XTheadMae) errata"
 	depends on ERRATA_THEAD && 64BIT && MMU
+	select DMA_DIRECT_REMAP
 	select RISCV_ALTERNATIVE_EARLY
 	default y
 	help
@@ -119,7 +120,6 @@ config ERRATA_THEAD_MAE
 config ERRATA_THEAD_CMO
 	bool "Apply T-Head cache management errata"
 	depends on ERRATA_THEAD && MMU
-	select DMA_DIRECT_REMAP
 	select RISCV_DMA_NONCOHERENT
 	select RISCV_NONSTANDARD_CACHE_OPS
 	default y
Signature · 1 line
2.47.2
#63 lore raw

PATCH v3 19/22 dt-bindings: riscv: Describe physical memory regions

In reply to Samuel Holland

Information about physical memory regions is needed by both the kernel and M-mode firmware. For example, the kernel needs to know about noncacheable aliases of cacheable memory in order to allocate coherent memory pages for DMA. M-mode firmware needs to know about those aliases so it can protect itself from lower-privileged software.

The RISC-V Privileged Architecture delegates the description of Physical Memory Attributes (PMAs) to the platform. On DT-based platforms, it makes sense to put this information in the devicetree.

---

Changes in v3:
- Split PMR_IS_ALIAS flag from PMR_ALIAS_MASK number
- Add "model" property to DT binding example to fix validation

Changes in v2:
- Remove references to Physical Address Width (no longer part of Smmpt)
- Remove special first entry from the list of physical memory regions
- Fix compatible string in DT binding example

 .../bindings/riscv/physical-memory.yaml       | 92 +++++++++++++++++++
 include/dt-bindings/riscv/physical-memory.h   | 45 +++++++++
 2 files changed, 137 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/riscv/physical-memory.yaml
 create mode 100644 include/dt-bindings/riscv/physical-memory.h
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +92 -0
new file mode 100644
index 000000000000..8beaa588c71c
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/riscv/physical-memory.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: RISC-V Physical Memory Regions
+
+maintainers:
+  - Samuel Holland <[email protected]>
+
+description:
+  The RISC-V Privileged Architecture defines a number of Physical Memory
+  Attributes (PMAs) which apply to a given region of memory. These include the
+  types of accesses (read, write, execute, LR/SC, and/or AMO) allowed within
+  a region, the supported access widths and alignments, the cacheability and
+  coherence of the region, and whether or not accesses to the region may have
+  side effects.
+
+  Some RISC-V platforms provide multiple physical address mappings for main
+  memory or certain peripherals. Each alias of a region generally has different
+  PMAs (e.g. cacheable vs non-cacheable), which allows software to dynamically
+  select the PMAs for an access by referencing the corresponding alias.
+
+  On DT-based RISC-V platforms, this information is provided by the
+  riscv,physical-memory-regions property of the root node.
+
+properties:
+  $nodename:
+    const: '/'
+
+  riscv,physical-memory-regions:
+    $ref: /schemas/types.yaml#/definitions/uint32-matrix
+    description:
+      Each table entry provides PMAs for a specific physical memory region,
+      which must not overlap with any other table entry.
+    minItems: 1
+    maxItems: 256
+    items:
+      minItems: 4
+      maxItems: 6
+      additionalItems: true
+      items:
+        - description: CPU physical address (#address-cells)
+        - description: >
+            Size (#size-cells). For entry 0, if the size is zero, the size is
+            assumed to be 2^(32 * #size-cells).
+        - description: >
+            Flags describing the most restrictive PMAs for any address within
+            the region.
+
+            The least significant byte indicates the types of accesses allowed
+            for this region. Note that a memory region may support a type of
+            access (e.g. AMOs) even if the CPU does not.
+
+            The next byte describes the cacheability, coherence, idempotency,
+            and ordering PMAs for this region. It also includes a flag to
+            indicate that accesses to a region are unsafe and must be
+            prohibited by software (for example using PMPs or Smmpt).
+
+            The third byte is reserved for future PMAs.
+
+            The most significant byte is the index of the lowest-numbered entry
+            which this entry is an alias of, if any. Aliases need not be the
+            same size, for example if a smaller memory region repeats within a
+            larger alias.
+        - description: Reserved for describing future PMAs
+
+additionalProperties: true
+
+examples:
+  - |
+    #include <dt-bindings/riscv/physical-memory.h>
+
+    / {
+      compatible = "beagle,beaglev-starlight-jh7100-r0", "starfive,jh7100";
+      model = "BeagleV Starlight Beta";
+      #address-cells = <2>;
+      #size-cells = <2>;
+
+      riscv,physical-memory-regions =
+          <0x00 0x18000000 0x00 0x00020000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x18080000 0x00 0x00020000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x41000000 0x00 0x1f000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x61000000 0x00 0x1f000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY | PMR_ALIAS(3)) 0x0>,
+          <0x00 0x80000000 0x08 0x00000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY) 0x0>,
+          <0x10 0x00000000 0x08 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY | PMR_ALIAS(5)) 0x0>,
+          <0x20 0x00000000 0x10 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x30 0x00000000 0x10 0x00000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY | PMR_ALIAS(7)) 0x0>;
+    };
+
+...
include/dt-bindings/riscv/physical-memory.h new file +45 -0

45 lines not on this page · raw message

Signature · 1 line
2.47.2
maintainer
#64 lore raw

Re: [PATCH v3 19/22] dt-bindings: riscv: Describe physical memory regions

Quoted 9 lines · Samuel Holland

Information about physical memory regions is needed by both the kernel and M-mode firmware. For example, the kernel needs to know about noncacheable aliases of cacheable memory in order to allocate coherent memory pages for DMA. M-mode firmware needs to know about those aliases so it can protect itself from lower-privileged software.

The RISC-V Privileged Architecture delegates the description of Physical Memory Attributes (PMAs) to the platform. On DT-based platforms, it makes sense to put this information in the devicetree.

I'm not sure how I feel about this. So here are my random thoughts on it.

I wonder if another arch may need something similar. I don't think arm64 ever would as aliases are not allowed. That may have happened on arm32, but that's all pretty mature at this point. I don't know about powerpc. I didn't find anything looking similar from a quick search.

Can this property go in the 'memory' nodes instead since the aliases are only for DRAM or main memory?

The /reserved-memory nodes you remove do look like an abuse of /reserved-memory.

Alternatively, I think you could solve this by using 3 address cells similar to how PCI bus bindings work.

memory {
	reg = <0x0 0x80000000 0x0 0x40000000>
	#address-cells = <3>;
	#size-cells = <2>;
	ranges = <PMA_foo 0x0 0x80000000 0x1 0x00000000 0x0 0x40000000>,
		...
}

So CPU address 0x1_00000000 maps to memory address 0x80000000 with attributes PMA_foo.

Not sure if you would have to change the dma-ranges in this case. I would think not.

Quoted 26 lines

---

Changes in v3:
- Split PMR_IS_ALIAS flag from PMR_ALIAS_MASK number
- Add "model" property to DT binding example to fix validation

Changes in v2:
- Remove references to Physical Address Width (no longer part of Smmpt)
- Remove special first entry from the list of physical memory regions
- Fix compatible string in DT binding example

 .../bindings/riscv/physical-memory.yaml       | 92 +++++++++++++++++++
 include/dt-bindings/riscv/physical-memory.h   | 45 +++++++++
 2 files changed, 137 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/riscv/physical-memory.yaml
 create mode 100644 include/dt-bindings/riscv/physical-memory.h
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +2 -0
new file mode 100644
index 000000000000..8beaa588c71c
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2

Documentation/devicetree/bindings/riscv/physical-memory.yaml line 12

Quoted 10 lines
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +10 -0
+---
+$id: http://devicetree.org/schemas/riscv/physical-memory.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: RISC-V Physical Memory Regions
+
+maintainers:
+  - Samuel Holland <[email protected]>
+
+description:

You need a '>' for paragraphs.

Quoted 5 lines
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +5 -0
+  The RISC-V Privileged Architecture defines a number of Physical Memory
+  Attributes (PMAs) which apply to a given region of memory. These include the
+  types of accesses (read, write, execute, LR/SC, and/or AMO) allowed within
+  a region, the supported access widths and alignments, the cacheability and
+  coherence of the region, and whether or not accesses to the region may have

Documentation/devicetree/bindings/riscv/physical-memory.yaml line 26

Quoted 10 lines
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +9 -0
+  side effects.
+
+  Some RISC-V platforms provide multiple physical address mappings for main
+  memory or certain peripherals. Each alias of a region generally has different
+  PMAs (e.g. cacheable vs non-cacheable), which allows software to dynamically
+  select the PMAs for an access by referencing the corresponding alias.
+
 
+  On DT-based RISC-V platforms, this information is provided by the
+  riscv,physical-memory-regions property of the root node.

That's kind of obvious. This document only applies to DT systems and the schema defines everything else you say.

Quoted 120 lines
Documentation/devicetree/bindings/riscv/physical-memory.yaml new file +66 -0
+
+properties:
+  $nodename:
+    const: '/'
+
+  riscv,physical-memory-regions:
+    $ref: /schemas/types.yaml#/definitions/uint32-matrix
+    description:
+      Each table entry provides PMAs for a specific physical memory region,
+      which must not overlap with any other table entry.
+    minItems: 1
+    maxItems: 256
+    items:
+      minItems: 4
+      maxItems: 6
+      additionalItems: true
+      items:
+        - description: CPU physical address (#address-cells)
+        - description: >
+            Size (#size-cells). For entry 0, if the size is zero, the size is
+            assumed to be 2^(32 * #size-cells).
+        - description: >
+            Flags describing the most restrictive PMAs for any address within
+            the region.
+
+            The least significant byte indicates the types of accesses allowed
+            for this region. Note that a memory region may support a type of
+            access (e.g. AMOs) even if the CPU does not.
+
+            The next byte describes the cacheability, coherence, idempotency,
+            and ordering PMAs for this region. It also includes a flag to
+            indicate that accesses to a region are unsafe and must be
+            prohibited by software (for example using PMPs or Smmpt).
+
+            The third byte is reserved for future PMAs.
+
+            The most significant byte is the index of the lowest-numbered entry
+            which this entry is an alias of, if any. Aliases need not be the
+            same size, for example if a smaller memory region repeats within a
+            larger alias.
+        - description: Reserved for describing future PMAs
+
+additionalProperties: true
+
+examples:
+  - |
+    #include <dt-bindings/riscv/physical-memory.h>
+
+    / {
+      compatible = "beagle,beaglev-starlight-jh7100-r0", "starfive,jh7100";
+      model = "BeagleV Starlight Beta";
+      #address-cells = <2>;
+      #size-cells = <2>;
+
+      riscv,physical-memory-regions =
+          <0x00 0x18000000 0x00 0x00020000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x18080000 0x00 0x00020000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x41000000 0x00 0x1f000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x00 0x61000000 0x00 0x1f000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY | PMR_ALIAS(3)) 0x0>,
+          <0x00 0x80000000 0x08 0x00000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY) 0x0>,
+          <0x10 0x00000000 0x08 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY | PMR_ALIAS(5)) 0x0>,
+          <0x20 0x00000000 0x10 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY) 0x0>,
+          <0x30 0x00000000 0x10 0x00000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY | PMR_ALIAS(7)) 0x0>;
+    };
+
+...
include/dt-bindings/riscv/physical-memory.h new file +45 -0
new file mode 100644
index 000000000000..d6ed8015c535
@@ -0,0 +1,45 @@
+/* SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) */
+
+#ifndef _DT_BINDINGS_RISCV_PHYSICAL_MEMORY_H
+#define _DT_BINDINGS_RISCV_PHYSICAL_MEMORY_H
+
+#define PMA_READ			(1 << 0)
+#define PMA_WRITE			(1 << 1)
+#define PMA_EXECUTE			(1 << 2)
+#define PMA_AMO_MASK			(3 << 4)
+#define PMA_AMO_NONE			(0 << 4)
+#define PMA_AMO_SWAP			(1 << 4)
+#define PMA_AMO_LOGICAL			(2 << 4)
+#define PMA_AMO_ARITHMETIC		(3 << 4)
+#define PMA_RSRV_MASK			(3 << 6)
+#define PMA_RSRV_NONE			(0 << 6)
+#define PMA_RSRV_NON_EVENTUAL		(1 << 6)
+#define PMA_RSRV_EVENTUAL		(2 << 6)
+
+#define PMA_RW				(PMA_READ | PMA_WRITE)
+#define PMA_RWA				(PMA_RW | PMA_AMO_ARITHMETIC | PMA_RSRV_EVENTUAL)
+#define PMA_RWX				(PMA_RW | PMA_EXECUTE)
+#define PMA_RWXA			(PMA_RWA | PMA_EXECUTE)
+
+#define PMA_ORDER_MASK			(3 << 8)
+#define PMA_ORDER_IO_RELAXED		(0 << 8)
+#define PMA_ORDER_IO_STRONG		(1 << 8)
+#define PMA_ORDER_MEMORY		(2 << 8)
+#define PMA_READ_IDEMPOTENT		(1 << 10)
+#define PMA_WRITE_IDEMPOTENT		(1 << 11)
+#define PMA_CACHEABLE			(1 << 12)
+#define PMA_COHERENT			(1 << 13)
+
+#define PMA_UNSAFE			(1 << 15)
+
+#define PMA_IO				(PMA_ORDER_IO_RELAXED)
+#define PMA_NONCACHEABLE_MEMORY		(PMA_ORDER_MEMORY | PMA_READ_IDEMPOTENT | \
+						PMA_WRITE_IDEMPOTENT)
+#define PMA_NONCOHERENT_MEMORY		(PMA_NONCACHEABLE_MEMORY | PMA_CACHEABLE)
+#define PMA_NORMAL_MEMORY		(PMA_NONCOHERENT_MEMORY | PMA_COHERENT)
+
+#define PMR_ALIAS_MASK			(0x7f << 24)
+#define PMR_IS_ALIAS			(0x80 << 24)
+#define PMR_ALIAS(n)			(PMR_IS_ALIAS | ((n) << 24))
+
+#endif /* _DT_BINDINGS_RISCV_PHYSICAL_MEMORY_H */
Signature · 1 line
2.47.2
#65 lore raw

PATCH v3 20/22 riscv: mm: Use physical memory aliases to apply PMAs

In reply to Samuel Holland

On some RISC-V platforms, RAM is mapped simultaneously to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs). Software alters the PMAs for a particular page at runtime by selecting a PFN from among the aliases of that page's physical address.

Implement this by transforming the PFN when writing page tables. If the memory type field is nonzero, replace the PFN with the corresponding PFN from the noncached alias. Similarly, when reading from the page tables, if the PFN is found in a noncached alias, replace it with the PFN from the normal memory alias, and insert _PAGE_NOCACHE.

The rest of the kernel sees only PFNs from normal memory and _PAGE_MTMASK values as if Svpbmt was implemented.

Memory alias pairs are determined from the devicetree. A Linux custom ISA extension is added to trigger the alternative patching, as alternatives must be linked to an extension or a vendor erratum, and this behavior is not associated with any particular processor vendor.

---

Changes in v3:
- Fix the logic to allow an alias to be paired with region entry 0
- Select DMA_DIRECT_REMAP

Changes in v2:
- Put new code behind a new Kconfig option RISCV_ISA_XLINUXMEMALIAS
- Document the calling convention of riscv_fixup/unfix_memory_alias()
- Do not transform !pte_present() (e.g. swap) PTEs
- Export riscv_fixup/unfix_memory_alias() to fix module compilation

 arch/riscv/Kconfig                    |  17 ++++
 arch/riscv/include/asm/hwcap.h        |   1 +
 arch/riscv/include/asm/pgtable-64.h   |  44 +++++++--
 arch/riscv/include/asm/pgtable-bits.h |   5 +-
 arch/riscv/include/asm/pgtable.h      |   8 ++
 arch/riscv/kernel/cpufeature.c        |   6 ++
 arch/riscv/kernel/setup.c             |   1 +
 arch/riscv/mm/Makefile                |   1 +
 arch/riscv/mm/memory-alias.S          | 123 ++++++++++++++++++++++++++
 arch/riscv/mm/pgtable.c               |  91 +++++++++++++++++++
 arch/riscv/mm/ptdump.c                |   6 +-
 11 files changed, 291 insertions(+), 12 deletions(-)
 create mode 100644 arch/riscv/mm/memory-alias.S
arch/riscv/Kconfig +17 -0
index cf5a4b5cdcd4..21efa0d9bdd4 100644
@@ -877,6 +877,23 @@ config TOOLCHAIN_NEEDS_OLD_ISA_SPEC
 	  versions of clang and GCC to be passed to GAS, which has the same result
 	  as passing zicsr and zifencei to -march.
 
+config RISCV_ISA_XLINUXMEMALIAS
+	bool "Use physical memory aliases to emulate page-based memory types"
+	depends on 64BIT && MMU
+	depends on RISCV_ALTERNATIVE
+	default y
+	select DMA_DIRECT_REMAP
+	help
+	  Add support for the kernel to alter the Physical Memory Attributes
+	  (PMAs) of a page at runtime by selecting from among the aliases of
+	  that page in the physical address space.
+
+	  On systems where physical memory aliases are present, this option
+	  is required in order to mark pages as non-cacheable for use with
+	  non-coherent DMA devices.
+
+	  If you don't know what to do here, say Y.
+
 config FPU
 	bool "FPU support"
 	default y
arch/riscv/include/asm/hwcap.h +1 -0
index affd63e11b0a..6c6349fe15a7 100644
@@ -107,6 +107,7 @@
 #define RISCV_ISA_EXT_ZALRSC		98
 #define RISCV_ISA_EXT_ZICBOP		99
 
+#define RISCV_ISA_EXT_XLINUXMEMALIAS	126
 #define RISCV_ISA_EXT_XLINUXENVCFG	127
 
 #define RISCV_ISA_EXT_MAX		128
arch/riscv/include/asm/pgtable-64.h +36 -8

100 lines not on this page · raw message

arch/riscv/include/asm/pgtable-bits.h +3 -2
index 18c50cbd78bf..4586917b2d98 100644
@@ -38,7 +38,8 @@
 #define _PAGE_PFN_MASK		GENMASK(31, 10)
 #endif /* CONFIG_64BIT */
 
-#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
+#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_RISCV_ISA_XLINUXMEMALIAS) || \
+	defined(CONFIG_ERRATA_THEAD_MAE)
 /*
  * [62:61] Svpbmt Memory Type definitions:
  *
@@ -54,7 +55,7 @@
 #define _PAGE_NOCACHE		0
 #define _PAGE_IO		0
 #define _PAGE_MTMASK		0
-#endif /* CONFIG_RISCV_ISA_SVPBMT || CONFIG_ERRATA_THEAD_MAE */
+#endif /* CONFIG_RISCV_ISA_SVPBMT || CONFIG_RISCV_ISA_XLINUXMEMALIAS || CONFIG_ERRATA_THEAD_MAE */
 
 #ifdef CONFIG_RISCV_ISA_SVNAPOT
 #define _PAGE_NAPOT_SHIFT	63
arch/riscv/include/asm/pgtable.h +8 -0
index 8b622f901707..27e8c20af0e2 100644
@@ -1113,6 +1113,14 @@ extern u64 satp_mode;
 void paging_init(void);
 void misc_mem_init(void);
 
+#ifdef CONFIG_RISCV_ISA_XLINUXMEMALIAS
+bool __init riscv_have_memory_alias(void);
+void __init riscv_init_memory_alias(void);
+#else
+static inline bool riscv_have_memory_alias(void) { return false; }
+static inline void riscv_init_memory_alias(void) {}
+#endif /* CONFIG_RISCV_ISA_XLINUXMEMALIAS */
+
 /*
  * ZERO_PAGE is a global shared page that is always zero,
  * used for zero-mapped memory areas, etc.
arch/riscv/kernel/cpufeature.c +6 -0
index 72ca768f4e91..ee59b160e886 100644
@@ -1093,6 +1093,12 @@ void __init riscv_fill_hwcap(void)
 		riscv_v_setup_vsize();
 	}
 
+	/* Vendor-independent alternatives require a bit in the ISA bitmap. */
+	if (riscv_have_memory_alias()) {
+		set_bit(RISCV_ISA_EXT_XLINUXMEMALIAS, riscv_isa);
+		pr_info("Using physical memory alias for noncached mappings\n");
+	}
+
 	memset(print_str, 0, sizeof(print_str));
 	for (i = 0, j = 0; i < NUM_ALPHA_EXTS; i++)
 		if (riscv_isa[0] & BIT_MASK(i))
arch/riscv/kernel/setup.c +1 -0
index b5bc5fc65cea..a6f821150101 100644
@@ -357,6 +357,7 @@ void __init setup_arch(char **cmdline_p)
 	}
 
 	riscv_init_cbo_blocksizes();
+	riscv_init_memory_alias();
 	riscv_fill_hwcap();
 	apply_boot_alternatives();
 	init_rt_signal_env();
arch/riscv/mm/Makefile +1 -0
index b916a68d324a..b4d757226efb 100644
@@ -33,3 +33,4 @@ endif
 obj-$(CONFIG_DEBUG_VIRTUAL) += physaddr.o
 obj-$(CONFIG_RISCV_DMA_NONCOHERENT) += dma-noncoherent.o
 obj-$(CONFIG_RISCV_NONSTANDARD_CACHE_OPS) += cache-ops.o
+obj-$(CONFIG_RISCV_ISA_XLINUXMEMALIAS) += memory-alias.o
arch/riscv/mm/memory-alias.S new file +123 -0

123 lines not on this page · raw message

arch/riscv/mm/pgtable.c +91 -0

102 lines not on this page · raw message

arch/riscv/mm/ptdump.c +4 -2
index 763ffde8ab5e..29a7be14cca5 100644
@@ -140,7 +140,8 @@ static const struct prot_bits pte_bits[] = {
 		.clear = ".",
 	}, {
 #endif
-#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
+#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_RISCV_ISA_XLINUXMEMALIAS) || \
+	defined(CONFIG_ERRATA_THEAD_MAE)
 		.mask = _PAGE_MTMASK,
 		.set = "MT(%s)",
 		.clear = "  ..  ",
@@ -216,7 +217,8 @@ static void dump_prot(struct pg_state *st)
 		if (val) {
 			if (pte_bits[i].mask == _PAGE_SOFT)
 				sprintf(s, pte_bits[i].set, val >> 8);
-#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_ERRATA_THEAD_MAE)
+#if defined(CONFIG_RISCV_ISA_SVPBMT) || defined(CONFIG_RISCV_ISA_XLINUXMEMALIAS) || \
+	defined(CONFIG_ERRATA_THEAD_MAE)
 			else if (pte_bits[i].mask == _PAGE_MTMASK) {
 				if (val == _PAGE_NOCACHE)
 					sprintf(s, pte_bits[i].set, "NC");
Signature · 1 line
2.47.2
#66 lore raw

PATCH v3 21/22 riscv: dts: starfive: jh7100: Use physical memory ranges for DMA

In reply to Samuel Holland

JH7100 provides a physical memory region which is a noncached alias of normal cacheable DRAM. Now that Linux can apply PMAs by selecting between aliases of a physical memory region, any page of DRAM can be marked as noncached for use with DMA, and the preallocated DMA pool is no longer needed. This allows portable kernels to boot on JH7100 boards.

---

Changes in v3:
- Fix the entry number of the paired region in the DT
- Keep the ERRATA_STARFIVE_JH7100 option but update its description

Changes in v2:
- Move the JH7100 DT changes from jh7100-common.dtsi to jh7100.dtsi
- Keep RISCV_DMA_NONCOHERENT and RISCV_NONSTANDARD_CACHE_OPS selected

 arch/riscv/Kconfig.errata                     |  9 +++----
 arch/riscv/Kconfig.socs                       |  2 ++
 .../boot/dts/starfive/jh7100-common.dtsi      | 24 -------------------
 arch/riscv/boot/dts/starfive/jh7100.dtsi      |  4 ++++
 4 files changed, 11 insertions(+), 28 deletions(-)
arch/riscv/Kconfig.errata +5 -4
index 46a353a266e5..be5afec66eaa 100644
@@ -77,13 +77,11 @@ config ERRATA_SIFIVE_CIP_1200
 	  If you don't know what to do here, say "Y".
 
 config ERRATA_STARFIVE_JH7100
-	bool "StarFive JH7100 support"
+	bool "StarFive JH7100 support for old devicetrees"
 	depends on ARCH_STARFIVE
 	depends on !DMA_DIRECT_REMAP
 	depends on NONPORTABLE
 	select DMA_GLOBAL_POOL
-	select RISCV_DMA_NONCOHERENT
-	select RISCV_NONSTANDARD_CACHE_OPS
 	select SIFIVE_CCACHE
 	default n
 	help
@@ -93,7 +91,10 @@ config ERRATA_STARFIVE_JH7100
 	  cache operations through the SiFive cache controller.
 
 	  Say "Y" if you want to support the BeagleV Starlight and/or
-	  StarFive VisionFive V1 boards.
+	  StarFive VisionFive V1 boards with older devicetrees that reserve
+	  memory for DMA using a "shared-dma-pool". If your devicetree has
+	  the "riscv,physical-memory-regions" property, you should instead
+	  enable RISCV_ISA_XLINUXMEMALIAS and use a portable kernel.
 
 config ERRATA_THEAD
 	bool "T-HEAD errata"
arch/riscv/Kconfig.socs +2 -0
index 848e7149e443..a8950206fb75 100644
@@ -50,6 +50,8 @@ config SOC_STARFIVE
 	bool "StarFive SoCs"
 	select PINCTRL
 	select RESET_CONTROLLER
+	select RISCV_DMA_NONCOHERENT
+	select RISCV_NONSTANDARD_CACHE_OPS
 	select ARM_AMBA
 	help
 	  This enables support for StarFive SoC platform hardware.
arch/riscv/boot/dts/starfive/jh7100-common.dtsi +0 -24
index ae1a6aeb0aea..47d0cf55bfc0 100644
@@ -42,30 +42,6 @@ led-ack {
 		};
 	};
 
-	reserved-memory {
-		#address-cells = <2>;
-		#size-cells = <2>;
-		ranges;
-
-		dma-reserved@fa000000 {
-			reg = <0x0 0xfa000000 0x0 0x1000000>;
-			no-map;
-		};
-
-		linux,dma@107a000000 {
-			compatible = "shared-dma-pool";
-			reg = <0x10 0x7a000000 0x0 0x1000000>;
-			no-map;
-			linux,dma-default;
-		};
-	};
-
-	soc {
-		dma-ranges = <0x00 0x80000000 0x00 0x80000000 0x00 0x7a000000>,
-			     <0x00 0xfa000000 0x10 0x7a000000 0x00 0x01000000>,
-			     <0x00 0xfb000000 0x00 0xfb000000 0x07 0x85000000>;
-	};
-
 	wifi_pwrseq: wifi-pwrseq {
 		compatible = "mmc-pwrseq-simple";
 		reset-gpios = <&gpio 37 GPIO_ACTIVE_LOW>;
arch/riscv/boot/dts/starfive/jh7100.dtsi +4 -0
index 7de0732b8eab..c7d7ec9ed8c9 100644
@@ -7,11 +7,15 @@
 /dts-v1/;
 #include <dt-bindings/clock/starfive-jh7100.h>
 #include <dt-bindings/reset/starfive-jh7100.h>
+#include <dt-bindings/riscv/physical-memory.h>
 
 / {
 	compatible = "starfive,jh7100";
 	#address-cells = <2>;
 	#size-cells = <2>;
+	riscv,physical-memory-regions =
+		<0x00 0x80000000 0x08 0x00000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY) 0x0>,
+		<0x10 0x00000000 0x08 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY | PMR_ALIAS(0)) 0x0>;
 
 	cpus: cpus {
 		#address-cells = <1>;
Signature · 1 line
2.47.2
#67 lore raw

PATCH v3 22/22 riscv: dts: eswin: eic7700: Use physical memory ranges for DMA

In reply to Samuel Holland

EIC7700 provides a physical memory region which is a noncached alias of normal cacheable DRAM. Declare this alias in the devicetree so Linux can allocate noncached pages for noncoherent DMA, and M-mode firmware can protect the noncached alias with PMPs.

---

Changes in v3:
- Fix the entry number of the paired region in the DT

Changes in v2:
- New patch for v2

 arch/riscv/Kconfig.socs                | 2 ++
 arch/riscv/boot/dts/eswin/eic7700.dtsi | 5 +++++
 2 files changed, 7 insertions(+)
arch/riscv/Kconfig.socs +2 -0
index a8950206fb75..df3ed1d322fe 100644
@@ -9,6 +9,8 @@ config ARCH_ANDES
 
 config ARCH_ESWIN
 	bool "ESWIN SoCs"
+	select RISCV_DMA_NONCOHERENT
+	select RISCV_NONSTANDARD_CACHE_OPS
 	help
 	  This enables support for ESWIN SoC platform hardware,
 	  including the ESWIN EIC7700 SoC.
arch/riscv/boot/dts/eswin/eic7700.dtsi +5 -0
index c3ed93008bca..d566bca4e09e 100644
@@ -5,9 +5,14 @@
 
 /dts-v1/;
 
+#include <dt-bindings/riscv/physical-memory.h>
+
 / {
 	#address-cells = <2>;
 	#size-cells = <2>;
+	riscv,physical-memory-regions =
+		<0x000 0x80000000 0x00f 0x80000000 (PMA_RWXA | PMA_NONCOHERENT_MEMORY) 0x0>,
+		<0x0c0 0x00000000 0x010 0x00000000 (PMA_RWX | PMA_NONCACHEABLE_MEMORY | PMR_ALIAS(0)) 0x0>;
 
 	cpus {
 		#address-cells = <1>;
Signature · 1 line
2.47.2
#68 lore raw
In reply to Samuel Holland
Quoted 9 lines · Samuel Holland

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

Quoted 7 lines

These physical memory aliases are only visible to architecture code. Generic MM code only ever sees the primary (cacheable) alias. The major change from v1 of this series is that I was asked to move the hooks from pfn_pXX()/pXX_pfn() to set_pXX()/pXXp_get().

- Patches 1-10 ensure that architecture-specific code that hooks page table reads and writes is always called, and the calls are balanced.

It is not immediately clear to me from the description why that is required. Can you summarize the core problem here, and why we have to route everything through these accessors?

Signature · 3 lines
Cheers

David
#69 lore raw
In reply to Samuel Holland
Quoted 9 lines · Samuel Holland

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

Then why don't you solve this at the DMA API layer ? Are those alternative PMAs going to be used for something else ? If the only usecase is to support noncoherent DMA I suggest playing with arch_dma_set_uncached and/or arch_dma_prep_coherent, we can deal with this similar to how MIPS did it with UNCAC_BASE.

Regards,
Nick

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

#70 lore raw
In reply to Samuel Holland
This series was applied to riscv/linux.git (fixes) by Andrew Morton <[email protected]>:

Hello:

This series was applied to riscv/linux.git (fixes) by Andrew Morton <[email protected]>:

Quoted 9 lines · On Wed, 12 Nov 2025 17:45:13 -0800 you wrote:

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

[...]

Here is the summary with links:
- [v3,01/22] mm/ptdump: replace READ_ONCE() with standard page table accessors

    https://git.kernel.org/riscv/c/11119b19f62d
  - [v3,02/22] mm: replace READ_ONCE() with standard page table accessors
    https://git.kernel.org/riscv/c/c0efdb373c3a
  - [v3,03/22] mm/dirty: replace READ_ONCE() with pudp_get()
    https://git.kernel.org/riscv/c/b4e53984f240

- [v3,04/22] perf/events: replace READ_ONCE() with standard page table accessors (no matching commit)
- [v3,05/22] mm: Move the fallback definitions of pXXp_get()
(no matching commit)
- [v3,06/22] mm: Always use page table accessor functions
(no matching commit)
- [v3,07/22] checkpatch: Warn on page table access without accessors (no matching commit)
- [v3,08/22] mm: Allow page table accessors to be non-idempotent (no matching commit)
- [v3,09/22] riscv: hibernate: Replace open-coded pXXp_get()
(no matching commit)
- [v3,10/22] riscv: mm: Always use page table accessor functions (no matching commit)
- [v3,11/22] riscv: mm: Simplify set_p4d() and set_pgd()
(no matching commit)
- [v3,12/22] riscv: mm: Deduplicate _PAGE_CHG_MASK definition
(no matching commit)
- [v3,13/22] riscv: ptdump: Only show N and MT bits when enabled in the kernel (no matching commit)
- [v3,14/22] riscv: mm: Fix up memory types when writing page tables (no matching commit)
- [v3,15/22] riscv: mm: Expose all page table bits to assembly code (no matching commit)
- [v3,16/22] riscv: alternative: Add an ALTERNATIVE_3 macro
(no matching commit)
- [v3,17/22] riscv: alternative: Allow calls with alternate link registers (no matching commit)
- [v3,18/22] riscv: Fix logic for selecting DMA_DIRECT_REMAP
(no matching commit)
- [v3,19/22] dt-bindings: riscv: Describe physical memory regions (no matching commit)
- [v3,20/22] riscv: mm: Use physical memory aliases to apply PMAs (no matching commit)
- [v3,21/22] riscv: dts: starfive: jh7100: Use physical memory ranges for DMA (no matching commit)
- [v3,22/22] riscv: dts: eswin: eic7700: Use physical memory ranges for DMA (no matching commit)

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html
#71 lore raw

Hi Samuel

Quoted 4 lines · On Fri, 2025-12-19 at 08:10 +0000, [email protected] wrote:

Hello:

This series was applied to riscv/linux.git (fixes) by Andrew Morton <[email protected]>:

Any idea what happened to patches 04-22 as I don't think anything other than patches 01-03 ever got applied anywhere. Or am I missing anything?

For what it's worth I carried an updated patch set through up to v6.19.4 [1] and latest -next, which at least on EBC77 seems to work fine.

Thanks!

Cheers

Marcel

[1] https://github.com/riscv/meta-riscv/pull/602

Quoted 58 lines · On Wed, 12 Nov 2025 17:45:13 -0800 you wrote:
Quoted 9 lines

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

[...]

Here is the summary with links:
  - [v3,01/22] mm/ptdump: replace READ_ONCE() with standard page table accessors
    https://git.kernel.org/riscv/c/11119b19f62d
  - [v3,02/22] mm: replace READ_ONCE() with standard page table accessors
    https://git.kernel.org/riscv/c/c0efdb373c3a
  - [v3,03/22] mm/dirty: replace READ_ONCE() with pudp_get()
    https://git.kernel.org/riscv/c/b4e53984f240
  - [v3,04/22] perf/events: replace READ_ONCE() with standard page table accessors (no matching commit)
  - [v3,05/22] mm: Move the fallback definitions of pXXp_get()
    (no matching commit)
  - [v3,06/22] mm: Always use page table accessor functions
    (no matching commit)
  - [v3,07/22] checkpatch: Warn on page table access without accessors (no matching commit)
  - [v3,08/22] mm: Allow page table accessors to be non-idempotent (no matching commit)
  - [v3,09/22] riscv: hibernate: Replace open-coded pXXp_get()
    (no matching commit)
  - [v3,10/22] riscv: mm: Always use page table accessor functions (no matching commit)
  - [v3,11/22] riscv: mm: Simplify set_p4d() and set_pgd()
    (no matching commit)
  - [v3,12/22] riscv: mm: Deduplicate _PAGE_CHG_MASK definition
    (no matching commit)
  - [v3,13/22] riscv: ptdump: Only show N and MT bits when enabled in the kernel (no matching commit)
  - [v3,14/22] riscv: mm: Fix up memory types when writing page tables (no matching commit)
  - [v3,15/22] riscv: mm: Expose all page table bits to assembly code (no matching commit)
  - [v3,16/22] riscv: alternative: Add an ALTERNATIVE_3 macro
    (no matching commit)
  - [v3,17/22] riscv: alternative: Allow calls with alternate link registers (no matching commit)
  - [v3,18/22] riscv: Fix logic for selecting DMA_DIRECT_REMAP
    (no matching commit)
  - [v3,19/22] dt-bindings: riscv: Describe physical memory regions (no matching commit)
  - [v3,20/22] riscv: mm: Use physical memory aliases to apply PMAs (no matching commit)
  - [v3,21/22] riscv: dts: starfive: jh7100: Use physical memory ranges for DMA (no matching commit)
  - [v3,22/22] riscv: dts: eswin: eic7700: Use physical memory ranges for DMA (no matching commit)

You are awesome, thank you!

#72 lore raw
In reply to Samuel Holland
This series was applied to riscv/linux.git (fixes) by Peter Zijlstra <[email protected]>:

Hello:

This series was applied to riscv/linux.git (fixes) by Peter Zijlstra <[email protected]>:

Quoted 9 lines · On Wed, 12 Nov 2025 17:45:13 -0800 you wrote:

On some RISC-V platforms, including StarFive JH7100 and ESWIN EIC7700, DRAM is mapped to multiple physical address ranges, with each alias having a different set of statically-determined Physical Memory Attributes (PMAs), such as cacheability. Software can alter the PMAs for a page by selecting a PFN from the corresponding physical address range. On these platforms, this is the only way to allocate noncached memory for use with noncoherent DMA.

[...]

Here is the summary with links:
- [v3,01/22] mm/ptdump: replace READ_ONCE() with standard page table accessors (no matching commit)
- [v3,02/22] mm: replace READ_ONCE() with standard page table accessors (no matching commit)
- [v3,03/22] mm/dirty: replace READ_ONCE() with pudp_get()
(no matching commit)
- [v3,04/22] perf/events: replace READ_ONCE() with standard page table accessors

    https://git.kernel.org/riscv/c/5a84b600050c

- [v3,05/22] mm: Move the fallback definitions of pXXp_get()
(no matching commit)
- [v3,06/22] mm: Always use page table accessor functions
(no matching commit)
- [v3,07/22] checkpatch: Warn on page table access without accessors (no matching commit)
- [v3,08/22] mm: Allow page table accessors to be non-idempotent (no matching commit)
- [v3,09/22] riscv: hibernate: Replace open-coded pXXp_get()
(no matching commit)
- [v3,10/22] riscv: mm: Always use page table accessor functions (no matching commit)
- [v3,11/22] riscv: mm: Simplify set_p4d() and set_pgd()
(no matching commit)
- [v3,12/22] riscv: mm: Deduplicate _PAGE_CHG_MASK definition
(no matching commit)
- [v3,13/22] riscv: ptdump: Only show N and MT bits when enabled in the kernel (no matching commit)
- [v3,14/22] riscv: mm: Fix up memory types when writing page tables (no matching commit)
- [v3,15/22] riscv: mm: Expose all page table bits to assembly code (no matching commit)
- [v3,16/22] riscv: alternative: Add an ALTERNATIVE_3 macro
(no matching commit)
- [v3,17/22] riscv: alternative: Allow calls with alternate link registers (no matching commit)
- [v3,18/22] riscv: Fix logic for selecting DMA_DIRECT_REMAP
(no matching commit)
- [v3,19/22] dt-bindings: riscv: Describe physical memory regions (no matching commit)
- [v3,20/22] riscv: mm: Use physical memory aliases to apply PMAs (no matching commit)
- [v3,21/22] riscv: dts: starfive: jh7100: Use physical memory ranges for DMA (no matching commit)
- [v3,22/22] riscv: dts: eswin: eic7700: Use physical memory ranges for DMA (no matching commit)

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html