Skip to contentSkip to conversation

Boot-time page size selection for arm64

RFC PATCH In review Ryan Roberts 34 participants 196 messages Oct 14, 2024 – Dec 6, 2024 Page 1 of 2

Subsystems (93)
lore
Share & tools
lore

Ryan Roberts

author reviewer
#0 lore raw

cover Boot-time page size selection for arm64

Hi All,

Patch bomb incoming... This covers many subsystems, so I've included a core set of people on the full series and additionally included maintainers on relevant patches. I haven't included those maintainers on this cover letter since the numbers were far too big for it to work. But I've included a link to this cover letter on each patch, so they can hopefully find their way here. For follow up submissions I'll break it up by subsystem, but for now thought it was important to show the full picture.

This RFC series implements support for boot-time page size selection within the arm64 kernel. arm64 supports 3 base page sizes (4K, 16K, 64K), but to date, page size has been selected at compile-time, meaning the size is baked into a given kernel image. As use of larger-than-4K page sizes become more prevalent this starts to present a problem for distributions. Boot-time page size selection enables the creation of a single kernel image, which can be told which page size to use on the kernel command line.

Why is having an image-per-page size problematic?
=================================================

Many traditional distros are now supporting both 4K and 64K. And this means managing 2 kernel packages, along with drivers for each. For some, it means multiple installer flavours and multiple ISOs. All of this adds up to a less-than-ideal level of complexity. Additionally, Android now supports 4K and 16K kernels. I'm told having to explicitly manage their KABI for each kernel is painful, and the extra flash space required for both kernel images and the duplicated modules has been problematic. Boot-time page size selection solves all of this.

Additionally, in starting to think about the longer term deployment story for D128 page tables, which Arm architecture now supports, a lot of the same problems need to be solved, so this work sets us up nicely for that.

So what's the down side?
========================

Well nothing's free; Various static allocations in the kernel image must be sized for the worst case (largest supported page size), so image size is in line with size of 64K compile-time image. So if you're interested in 4K or 16K, there is a slight increase to the image size. But I expect that problem goes away if you're compressing the image - its just some extra zeros. At boot-time, I expect we could free the unused static storage once we know the page size - although that would be a follow up enhancement.

And then there is performance. Since PAGE_SIZE and friends are no longer compile-time constants, we must look up their values and do arithmetic at runtime instead of compile-time. My early perf testing suggests this is inperceptible for real-world workloads, and only has small impact on microbenchmarks - more on this below.

Approach
========

The basic idea is to rid the source of any assumptions that PAGE_SIZE and friends are compile-time constant, but in a way that allows the compiler to perform the same optimizations as was previously being done if they do turn out to be compile-time constant. Where constants are required, we use limits; PAGE_SIZE_MIN and PAGE_SIZE_MAX. See commit log in patch 1 for full description of all the classes of problems to solve.

By default PAGE_SIZE_MIN=PAGE_SIZE_MAX=PAGE_SIZE. But an arch may opt-in to boot-time page size selection by defining PAGE_SIZE_MIN & PAGE_SIZE_MAX. arm64 does this if the user selects the CONFIG_ARM64_BOOT_TIME_PAGE_SIZE Kconfig, which is an alternative to selecting a compile-time page size.

When boot-time page size is active, the arch pgtable geometry macro definitions resolve to something that can be configured at boot. The arm64 implementation in this series mainly uses global, __ro_after_init variables. I've tried using alternatives patching, but that performs worse than loading from memory; I think due to code size bloat.

Status
======

When CONFIG_ARM64_BOOT_TIME_PAGE_SIZE is selected, I've only implemented enough to compile the kernel image itself with defconfig (and a few other bits and pieces). This is enough to build a kernel that can boot under QEMU or FVP. I'll happily do the rest of the work to enable all the extra drivers, but wanted to get feedback on the shape of this effort first. If anyone wants to do any testing, and has a must-have config, let me know and I'll prioritize enabling it first.

The series is arranged as follows:

- patch 1: Add macros required for converting non-arch code to support
boot-time page size selection
- patches 2-36: Remove PAGE_SIZE compile-time constant assumption from all non-arch code
- patches 37-38: Some arm64 tidy ups
- patch 39: Add macros required for converting arm64 code to support
boot-time page size selection
- patches 40-56: arm64 changes to support boot-time page size selection
- patch 57: Add arm64 Kconfig option to enable boot-time page size
selection

Ideally, I'd like to get the basics merged (something like this series), then incrementally improve it over a handful of kernel releases until we can demonstrate that we have feature parity with the compile-time build and no performance blockers. Once at that point, ideally the compile-time build options would be removed and the code could be cleaned up further.

One of the bigger peices that I'd propose to add as a follow up, is to make va-size boot-time selectable too. That will greatly simplify LPA2 fallback handling.

Assuming people are ammenable to the rough shape, how would I go about getting the non-arch changes merged? Since they cover many subsystems, will each piece need to go independently to each relevant maintainer or could it all be merged together through the arm64 tree?

Image Size
==========

The below shows the size of a defconfig (+ xfs, squashfs, ftrace, kprobes) kernel image on disk for base (before any changes applied), compile (with changes, configured for compile-time page size) and boot (with changes, configured for boot-time page size).

You can see the that compile-16k and 64k configs are actually slightly smaller than the baselines; that's due to optimizing some buffer sizes which didn't need to depend on page size during the series. The boot-time image is ~1% bigger than the 64k compile-time image. I believe there is scope to improve this to make it equal to compile-64k if required:

| config      | size/KB | diff/KB |  diff/% |
|-------------|---------|---------|---------|
| base-4k     |   54895 |       0 |    0.0% |
| base-16k    |   55161 |     266 |    0.5% |
| base-64k    |   56775 |    1880 |    3.4% |
| compile-4k  |   54895 |       0 |    0.0% |
| compile-16k |   55097 |     202 |    0.4% |
| compile-64k |   56391 |    1496 |    2.7% |
| boot-4K     |   57045 |    2150 |    3.9% |

And below shows the size of the image in memory at run-time, separated for text and data costs. The boot image has ~1% text cost; most likely due to the fact that PAGE_SIZE and friends are not compile-time constants so need instructions to load the values and do arithmetic. I believe we could eventually get the data cost to match the cost for the compile image for the chosen page size by freeing the ends of the static buffers not needed for the selected page size:

|             |    text |    text |    text |    data |    data |    data |
| config      | size/KB | diff/KB |  diff/% | size/KB | diff/KB |  diff/% |
|-------------|---------|---------|---------|---------|---------|---------|
| base-4k     |   20561 |       0 |    0.0% |   14314 |       0 |    0.0% |
| base-16k    |   20439 |    -122 |   -0.6% |   14625 |     311 |    2.2% |
| base-64k    |   20435 |    -126 |   -0.6% |   15673 |    1359 |    9.5% |
| compile-4k  |   20565 |       4 |    0.0% |   14315 |       1 |    0.0% |
| compile-16k |   20443 |    -118 |   -0.6% |   14517 |     204 |    1.4% |
| compile-64k |   20439 |    -122 |   -0.6% |   15134 |     820 |    5.7% |
| boot-4K     |   20811 |     250 |    1.2% |   15287 |     973 |    6.8% |

Functional Testing
==================

I've build-tested defconfig for all arches supported by tuxmake (which is most) without issue.

I've boot-tested arm64 with CONFIG_ARM64_BOOT_TIME_PAGE_SIZE for all page sizes and a few va-sizes, and additionally have run all the mm-selftests, with no regressions observed vs the equivalent compile-time page size build (although the mm-selftests have a few existing failures when run against 16K and 64K kernels - those should really be investigated and fixed independently).

Test coverage is lacking for many of the drivers that I've touched, but in many cases, I'm hoping the changes are simple enough that review might suffice?

Performance Testing
===================

I've run some limited performance benchmarks:

First, a real-world benchmark that causes a lot of page table manipulation (and therefore we would expect to see regression here if we are going to see it anywhere); kernel compilation. It barely registers a change. Values are times, so smaller is better. All relative to base-4k:

|             |    kern |    kern |    user |    user |    real |    real |
| config      |    mean |   stdev |    mean |   stdev |    mean |   stdev |
|-------------|---------|---------|---------|---------|---------|---------|
| base-4k     |    0.0% |    1.1% |    0.0% |    0.3% |    0.0% |    0.3% |
| compile-4k  |   -0.2% |    1.1% |   -0.2% |    0.3% |   -0.1% |    0.3% |
| boot-4k     |    0.1% |    1.0% |   -0.3% |    0.2% |   -0.2% |    0.2% |

The Speedometer JavaScript benchmark also shows no change. Values are runs per min, so bigger is better. All relative to base-4k:

| config      |    mean |   stdev |
|-------------|---------|---------|
| base-4k     |    0.0% |    0.8% |
| compile-4k  |    0.4% |    0.8% |
| boot-4k     |    0.0% |    0.9% |

Finally, I've run some microbenchmarks known to stress page table manipulations (originally from David Hildenbrand). The fork test maps/allocs 1G of anon memory, then measures the cost of fork(). The munmap test maps/allocs 1G of anon memory then measures the cost of munmap()ing it. The fork test is known to be extremely sensitive to any changes that cause instructions to be aligned differently in cachelines. When using this test for other changes, I've seen double digit regressions for the slightest thing, so 12% regression on this test is actually fairly good. This likely represents the extreme worst case for regressions that will be observed across other microbenchmarks (famous last words). Values are times, so smaller is better. All relative to base-4k:

|             |    fork |    fork |  munmap |  munmap |
| config      |    mean |   stdev |   stdev |   stdev |
|-------------|---------|---------|---------|---------|
| base-4k     |    0.0% |    1.3% |    0.0% |    0.3% |
| compile-4k  |    0.1% |    1.3% |   -0.9% |    0.1% |
| boot-4k     |   12.8% |    1.2% |    3.8% |    1.0% |

NOTE: The series applies on top of v6.11.

Thanks,
Ryan

Ryan Roberts (57):
mm: Add macros ahead of supporting boot-time page size selection
vmlinux: Align to PAGE_SIZE_MAX
mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large mm/page_alloc: Make page_frag_cache boot-time page size compatible
mm: Avoid split pmd ptl if pmd level is run-time folded
mm: Remove PAGE_SIZE compile-time constant assumption
fs: Introduce MAX_BUF_PER_PAGE_SIZE_MAX for array sizing
fs: Remove PAGE_SIZE compile-time constant assumption fs/nfs: Remove PAGE_SIZE compile-time constant assumption fs/ext4: Remove PAGE_SIZE compile-time constant assumption
fork: Permit boot-time THREAD_SIZE determination
cgroup: Remove PAGE_SIZE compile-time constant assumption
bpf: Remove PAGE_SIZE compile-time constant assumption pm/hibernate: Remove PAGE_SIZE compile-time constant assumption
stackdepot: Remove PAGE_SIZE compile-time constant assumption
perf: Remove PAGE_SIZE compile-time constant assumption
kvm: Remove PAGE_SIZE compile-time constant assumption
trace: Remove PAGE_SIZE compile-time constant assumption
crash: Remove PAGE_SIZE compile-time constant assumption
crypto: Remove PAGE_SIZE compile-time constant assumption
sunrpc: Remove PAGE_SIZE compile-time constant assumption
sound: Remove PAGE_SIZE compile-time constant assumption
net: Remove PAGE_SIZE compile-time constant assumption
net: fec: Remove PAGE_SIZE compile-time constant assumption
net: marvell: Remove PAGE_SIZE compile-time constant assumption
net: hns3: Remove PAGE_SIZE compile-time constant assumption
net: e1000: Remove PAGE_SIZE compile-time constant assumption
net: igbvf: Remove PAGE_SIZE compile-time constant assumption
net: igb: Remove PAGE_SIZE compile-time constant assumption drivers/base: Remove PAGE_SIZE compile-time constant assumption
edac: Remove PAGE_SIZE compile-time constant assumption
optee: Remove PAGE_SIZE compile-time constant assumption
random: Remove PAGE_SIZE compile-time constant assumption
sata_sil24: Remove PAGE_SIZE compile-time constant assumption
virtio: Remove PAGE_SIZE compile-time constant assumption
xen: Remove PAGE_SIZE compile-time constant assumption
arm64: Fix macros to work in C code in addition to the linker script
arm64: Track early pgtable allocation limit
arm64: Introduce macros required for boot-time page selection
arm64: Refactor early pgtable size calculation macros
arm64: Pass desired page size on command line
arm64: Divorce early init from PAGE_SIZE
arm64: Clean up simple cases of CONFIG_ARM64_*K_PAGES
arm64: Align sections to PAGE_SIZE_MAX
arm64: Rework trampoline rodata mapping
arm64: Generalize fixmap for boot-time page size
arm64: Statically allocate and align for worst-case page size
arm64: Convert switch to if for non-const comparison values
arm64: Convert BUILD_BUG_ON to VM_BUG_ON
arm64: Remove PAGE_SZ asm-offset
arm64: Introduce cpu features for page sizes
arm64: Remove PAGE_SIZE from assembly code
arm64: Runtime-fold pmd level
arm64: Support runtime folding in idmap_kpti_install_ng_mappings
arm64: TRAMP_VALIAS is no longer compile-time constant
arm64: Determine THREAD_SIZE at boot-time
arm64: Enable boot-time page size selection

 arch/alpha/include/asm/page.h                 |   1 +
 arch/arc/include/asm/page.h                   |   1 +
 arch/arm/include/asm/page.h                   |   1 +
 arch/arm64/Kconfig                            |  26 ++-
 arch/arm64/include/asm/assembler.h            |  78 ++++++-
 arch/arm64/include/asm/cpufeature.h           |  44 +++-
 arch/arm64/include/asm/efi.h                  |   2 +-
 arch/arm64/include/asm/fixmap.h               |  28 ++-
 arch/arm64/include/asm/kernel-pgtable.h       | 150 +++++++++----
 arch/arm64/include/asm/kvm_arm.h              |  21 +-
 arch/arm64/include/asm/kvm_hyp.h              |  11 +
 arch/arm64/include/asm/kvm_pgtable.h          |   6 +-
 arch/arm64/include/asm/memory.h               |  62 ++++--
 arch/arm64/include/asm/page-def.h             |   3 +-
 arch/arm64/include/asm/pgalloc.h              |  16 +-
 arch/arm64/include/asm/pgtable-geometry.h     |  46 ++++
 arch/arm64/include/asm/pgtable-hwdef.h        |  28 ++-
 arch/arm64/include/asm/pgtable-prot.h         |   2 +-
 arch/arm64/include/asm/pgtable.h              | 133 +++++++++---
 arch/arm64/include/asm/processor.h            |  10 +-
 arch/arm64/include/asm/sections.h             |   1 +
 arch/arm64/include/asm/smp.h                  |   1 +
 arch/arm64/include/asm/sparsemem.h            |  15 +-
 arch/arm64/include/asm/sysreg.h               |  54 +++--
 arch/arm64/include/asm/tlb.h                  |   3 +
 arch/arm64/kernel/asm-offsets.c               |   4 +-
 arch/arm64/kernel/cpufeature.c                |  93 ++++++--
 arch/arm64/kernel/efi.c                       |   2 +-
 arch/arm64/kernel/entry.S                     |  60 +++++-
 arch/arm64/kernel/head.S                      |  46 +++-
 arch/arm64/kernel/hibernate-asm.S             |   6 +-
 arch/arm64/kernel/image-vars.h                |  14 ++
 arch/arm64/kernel/image.h                     |   4 +
 arch/arm64/kernel/pi/idreg-override.c         |  68 +++++-
 arch/arm64/kernel/pi/map_kernel.c             | 165 ++++++++++----
 arch/arm64/kernel/pi/map_range.c              | 201 ++++++++++++++++--
 arch/arm64/kernel/pi/pi.h                     |  63 +++++-
 arch/arm64/kernel/relocate_kernel.S           |  10 +-
 arch/arm64/kernel/vdso-wrap.S                 |   4 +-
 arch/arm64/kernel/vdso.c                      |   7 +-
 arch/arm64/kernel/vdso/vdso.lds.S             |   4 +-
 arch/arm64/kernel/vdso32-wrap.S               |   4 +-
 arch/arm64/kernel/vdso32/vdso.lds.S           |   4 +-
 arch/arm64/kernel/vmlinux.lds.S               |  48 +++--
 arch/arm64/kvm/arm.c                          |  10 +
 arch/arm64/kvm/hyp/nvhe/Makefile              |   1 +
 arch/arm64/kvm/hyp/nvhe/host.S                |  10 +-
 arch/arm64/kvm/hyp/nvhe/hyp.lds.S             |   4 +-
 arch/arm64/kvm/hyp/nvhe/pgtable-geometry.c    |  16 ++
 arch/arm64/kvm/mmu.c                          |  39 ++--
 arch/arm64/lib/clear_page.S                   |   7 +-
 arch/arm64/lib/copy_page.S                    |  33 ++-
 arch/arm64/lib/mte.S                          |  27 ++-
 arch/arm64/mm/Makefile                        |   1 +
 arch/arm64/mm/fixmap.c                        |  38 ++--
 arch/arm64/mm/hugetlbpage.c                   |  40 +---
 arch/arm64/mm/init.c                          |  26 +--
 arch/arm64/mm/kasan_init.c                    |   8 +-
 arch/arm64/mm/mmu.c                           |  53 +++--
 arch/arm64/mm/pgd.c                           |  12 +-
 arch/arm64/mm/pgtable-geometry.c              |  24 +++
 arch/arm64/mm/proc.S                          | 128 ++++++++---
 arch/arm64/mm/ptdump.c                        |   3 +-
 arch/arm64/tools/cpucaps                      |   3 +
 arch/csky/include/asm/page.h                  |   3 +
 arch/hexagon/include/asm/page.h               |   2 +
 arch/loongarch/include/asm/page.h             |   2 +
 arch/m68k/include/asm/page.h                  |   1 +
 arch/microblaze/include/asm/page.h            |   1 +
 arch/mips/include/asm/page.h                  |   1 +
 arch/nios2/include/asm/page.h                 |   2 +
 arch/openrisc/include/asm/page.h              |   1 +
 arch/parisc/include/asm/page.h                |   1 +
 arch/powerpc/include/asm/page.h               |   2 +
 arch/riscv/include/asm/page.h                 |   1 +
 arch/s390/include/asm/page.h                  |   1 +
 arch/sh/include/asm/page.h                    |   1 +
 arch/sparc/include/asm/page.h                 |   3 +
 arch/um/include/asm/page.h                    |   2 +
 arch/x86/include/asm/page_types.h             |   2 +
 arch/xtensa/include/asm/page.h                |   1 +
 crypto/lskcipher.c                            |   4 +-
 drivers/ata/sata_sil24.c                      |  46 ++--
 drivers/base/node.c                           |   6 +-
 drivers/base/topology.c                       |  32 +--
 drivers/block/virtio_blk.c                    |   2 +-
 drivers/char/random.c                         |   4 +-
 drivers/edac/edac_mc.h                        |  13 +-
 drivers/firmware/efi/libstub/arm64.c          |   3 +-
 drivers/irqchip/irq-gic-v3-its.c              |   2 +-
 drivers/mtd/mtdswap.c                         |   4 +-
 drivers/net/ethernet/freescale/fec.h          |   3 +-
 drivers/net/ethernet/freescale/fec_main.c     |   5 +-
 .../net/ethernet/hisilicon/hns3/hns3_enet.h   |   4 +-
 drivers/net/ethernet/intel/e1000/e1000_main.c |   6 +-
 drivers/net/ethernet/intel/igb/igb.h          |  25 +--
 drivers/net/ethernet/intel/igb/igb_main.c     | 149 +++++++------
 drivers/net/ethernet/intel/igbvf/netdev.c     |   6 +-
 drivers/net/ethernet/marvell/mvneta.c         |   9 +-
 drivers/net/ethernet/marvell/sky2.h           |   2 +-
 drivers/tee/optee/call.c                      |   7 +-
 drivers/tee/optee/smc_abi.c                   |   2 +-
 drivers/virtio/virtio_balloon.c               |  10 +-
 drivers/xen/balloon.c                         |  11 +-
 drivers/xen/biomerge.c                        |  12 +-
 drivers/xen/privcmd.c                         |   2 +-
 drivers/xen/xenbus/xenbus_client.c            |   5 +-
 drivers/xen/xlate_mmu.c                       |   6 +-
 fs/binfmt_elf.c                               |  11 +-
 fs/buffer.c                                   |   2 +-
 fs/coredump.c                                 |   8 +-
 fs/ext4/ext4.h                                |  36 ++--
 fs/ext4/move_extent.c                         |   2 +-
 fs/ext4/readpage.c                            |   2 +-
 fs/fat/dir.c                                  |   4 +-
 fs/fat/fatent.c                               |   4 +-
 fs/nfs/nfs42proc.c                            |   2 +-
 fs/nfs/nfs42xattr.c                           |   2 +-
 fs/nfs/nfs4proc.c                             |   2 +-
 include/asm-generic/pgtable-geometry.h        |  71 +++++++
 include/asm-generic/vmlinux.lds.h             |  38 ++--
 include/linux/buffer_head.h                   |   1 +
 include/linux/cpumask.h                       |   5 +
 include/linux/linkage.h                       |   4 +-
 include/linux/mm.h                            |  17 +-
 include/linux/mm_types.h                      |  15 +-
 include/linux/mm_types_task.h                 |   2 +-
 include/linux/mmzone.h                        |   3 +-
 include/linux/netlink.h                       |   6 +-
 include/linux/percpu-defs.h                   |   4 +-
 include/linux/perf_event.h                    |   2 +-
 include/linux/sched.h                         |   4 +-
 include/linux/slab.h                          |   7 +-
 include/linux/stackdepot.h                    |   6 +-
 include/linux/sunrpc/svc.h                    |   8 +-
 include/linux/sunrpc/svc_rdma.h               |   4 +-
 include/linux/sunrpc/svcsock.h                |   2 +-
 include/linux/swap.h                          |  17 +-
 include/linux/swapops.h                       |   6 +-
 include/linux/thread_info.h                   |  10 +-
 include/xen/page.h                            |   2 +
 init/main.c                                   |   7 +-
 kernel/bpf/core.c                             |   9 +-
 kernel/bpf/ringbuf.c                          |  54 ++---
 kernel/cgroup/cgroup.c                        |   8 +-
 kernel/crash_core.c                           |   2 +-
 kernel/events/core.c                          |   2 +-
 kernel/fork.c                                 |  71 +++----
 kernel/power/power.h                          |   2 +-
 kernel/power/snapshot.c                       |   2 +-
 kernel/power/swap.c                           | 129 +++++++++--
 kernel/trace/fgraph.c                         |   2 +-
 kernel/trace/trace.c                          |   2 +-
 lib/stackdepot.c                              |   6 +-
 mm/kasan/report.c                             |   3 +-
 mm/memcontrol.c                               |  11 +-
 mm/memory.c                                   |   4 +-
 mm/mmap.c                                     |   2 +-
 mm/page-writeback.c                           |   2 +-
 mm/page_alloc.c                               |  31 +--
 mm/slub.c                                     |   2 +-
 mm/sparse.c                                   |   2 +-
 mm/swapfile.c                                 |   2 +-
 mm/vmalloc.c                                  |   7 +-
 net/9p/trans_virtio.c                         |   4 +-
 net/core/hotdata.c                            |   4 +-
 net/core/skbuff.c                             |   4 +-
 net/core/sysctl_net_core.c                    |   2 +-
 net/sunrpc/cache.c                            |   3 +-
 net/unix/af_unix.c                            |   2 +-
 sound/soc/soc-utils.c                         |   4 +-
 virt/kvm/kvm_main.c                           |   2 +-
 172 files changed, 2185 insertions(+), 951 deletions(-)
 create mode 100644 arch/arm64/include/asm/pgtable-geometry.h
 create mode 100644 arch/arm64/kvm/hyp/nvhe/pgtable-geometry.c
 create mode 100644 arch/arm64/mm/pgtable-geometry.c
 create mode 100644 include/asm-generic/pgtable-geometry.h

--
2.43.0

author reviewer
#1 lore raw

RFC PATCH 1/57 mm: Add macros ahead of supporting boot-time page size selection

arm64 can support multiple base page sizes. Instead of selecting a page size at compile time, as is done today, we will make it possible to select the desired page size on the command line.

In this case PAGE_SHIFT and it's derivatives, PAGE_SIZE and PAGE_MASK (as well as a number of other macros related to or derived from PAGE_SHIFT, but I'm not worrying about those yet), are no longer compile-time constants. So the code base needs to cope with that.

As a first step, introduce MIN and MAX variants of these macros, which express the range of possible page sizes. These are always compile-time constants and can be used in many places where PAGE_[SHIFT|SIZE|MASK] were previously used where a compile-time constant is required. (Subsequent patches will do that conversion work). When the arch/build doesn't support boot-time page size selection, the MIN and MAX variants are equal and everything resolves as it did previously.

Additionally, introduce DEFINE_GLOBAL_PAGE_SIZE_VAR[_CONST]() which wrap global variable defintions so that for boot-time page size selection builds, the variable being wrapped is initialized at boot-time, instead of compile-time. This is done by defining a function to do the assignment, which has the "constructor" attribute. Constructor is preferred over initcall, because when compiling a module, the module is limited to a single initcall but constructors are unlimited. For built-in code, constructors are now called earlier to guarrantee that the variables are initialized by the time they are used. Any arch that wants to enable boot-time page size selection will need to select CONFIG_CONSTRUCTORS.

These new macros need to be available anywhere PAGE_SHIFT and friends are available. Those are defined via asm/page.h (although some arches have a sub-include that defines them). Unfortunately there is no reliable asm-generic header we can easily piggy-back on, so let's define a new one, pgtable-geometry.h, which we include near where each arch defines PAGE_SHIFT. Ugh.

-------

Most of the problems that need to be solved over the next few patches fall into these broad categories, which are all solved with the help of these new macros:

1. Assignment of values derived from PAGE_SIZE in global variables

For boot-time page size builds, we must defer the initialization of these variables until boot-time, when the page size is known. See DEFINE_GLOBAL_PAGE_SIZE_VAR[_CONST]() as described above.

2. Define static storage in units related to PAGE_SIZE

This static storage will be defined according to PAGE_SIZE_MAX.

3. Define size of struct so that it is related to PAGE_SIZE

The struct often contains an array that is sized to fill the page. In this case, use a flexible array with dynamic allocation. In other cases, the struct fits exactly over a page, which is a header (e.g. swap file header). In this case, remove the padding, and manually determine the struct pointer within the page.

4. BUILD_BUG_ON() with values derived from PAGE_SIZE

In most cases, we can change these to compare againt the appropriate limit (either MIN or MAX). In other cases, we must change these to run-time BUG_ON().

5. Ensure page alignment of static data structures

Align instead to PAGE_SIZE_MAX.

6. #ifdeffery based on PAGE_SIZE

Often these can be changed to c code constructs. e.g. a macro that returns a different value depending on page size can be changed to use the ternary operator and the compiler will dead code strip it for the compile-time constant case and runtime evaluate it for the non-const case. Or #if/#else/#endif within a function can be converted to c if/else blocks, which are also dead code stripped for the const case. Sometimes we can change the c-preprocessor logic to use the appropriate MIN/MAX limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/alpha/include/asm/page.h          |  1 +
 arch/arc/include/asm/page.h            |  1 +
 arch/arm/include/asm/page.h            |  1 +
 arch/arm64/include/asm/page-def.h      |  2 +
 arch/csky/include/asm/page.h           |  3 ++
 arch/hexagon/include/asm/page.h        |  2 +
 arch/loongarch/include/asm/page.h      |  2 +
 arch/m68k/include/asm/page.h           |  1 +
 arch/microblaze/include/asm/page.h     |  1 +
 arch/mips/include/asm/page.h           |  1 +
 arch/nios2/include/asm/page.h          |  2 +
 arch/openrisc/include/asm/page.h       |  1 +
 arch/parisc/include/asm/page.h         |  1 +
 arch/powerpc/include/asm/page.h        |  2 +
 arch/riscv/include/asm/page.h          |  1 +
 arch/s390/include/asm/page.h           |  1 +
 arch/sh/include/asm/page.h             |  1 +
 arch/sparc/include/asm/page.h          |  3 ++
 arch/um/include/asm/page.h             |  2 +
 arch/x86/include/asm/page_types.h      |  2 +
 arch/xtensa/include/asm/page.h         |  1 +
 include/asm-generic/pgtable-geometry.h | 71 ++++++++++++++++++++++++++
 init/main.c                            |  5 +-
 23 files changed, 107 insertions(+), 1 deletion(-)
 create mode 100644 include/asm-generic/pgtable-geometry.h
arch/alpha/include/asm/page.h +1 -0
index 70419e6be1a35..d0096fb5521b8 100644
@@ -88,5 +88,6 @@ typedef struct page *pgtable_t;
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* _ALPHA_PAGE_H */
arch/arc/include/asm/page.h +1 -0
index def0dfb95b436..8d56549db7a33 100644
@@ -6,6 +6,7 @@
 #define __ASM_ARC_PAGE_H
 
 #include <uapi/asm/page.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #ifdef CONFIG_ARC_HAS_PAE40
 
arch/arm/include/asm/page.h +1 -0
index 62af9f7f9e963..417aa8533c718 100644
@@ -191,5 +191,6 @@ extern int pfn_valid(unsigned long);
 
 #include <asm-generic/getorder.h>
 #include <asm-generic/memory_model.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif
arch/arm64/include/asm/page-def.h +2 -0
index 792e9fe881dcf..d69971cf49cd2 100644
@@ -15,4 +15,6 @@
 #define PAGE_SIZE		(_AC(1, UL) << PAGE_SHIFT)
 #define PAGE_MASK		(~(PAGE_SIZE-1))
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif /* __ASM_PAGE_DEF_H */
arch/csky/include/asm/page.h +3 -0
index 0ca6c408c07f2..95173d57adc8b 100644
@@ -92,4 +92,7 @@ static inline unsigned long virt_to_pfn(const void *kaddr)
 #include <asm-generic/getorder.h>
 
 #endif /* !__ASSEMBLY__ */
+
+#include <asm-generic/pgtable-geometry.h>
+
 #endif /* __ASM_CSKY_PAGE_H */
arch/hexagon/include/asm/page.h +2 -0
index 8a6af57274c2d..ba7ad5231695f 100644
@@ -139,4 +139,6 @@ static inline unsigned long virt_to_pfn(const void *kaddr)
 #endif /* ifdef __ASSEMBLY__ */
 #endif /* ifdef __KERNEL__ */
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif
arch/loongarch/include/asm/page.h +2 -0
index e85df33f11c77..9862e8fb047a6 100644
@@ -123,4 +123,6 @@ extern int __virt_addr_valid(volatile void *kaddr);
 
 #endif /* !__ASSEMBLY__ */
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif /* _ASM_PAGE_H */
arch/m68k/include/asm/page.h +1 -0
index 8cfb84b499751..4df4681b02194 100644
@@ -60,5 +60,6 @@ extern unsigned long _ramend;
 
 #include <asm-generic/getorder.h>
 #include <asm-generic/memory_model.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* _M68K_PAGE_H */
arch/microblaze/include/asm/page.h +1 -0
index 8810f4f1c3b02..abc23c3d743bd 100644
@@ -142,5 +142,6 @@ static inline const void *pfn_to_virt(unsigned long pfn)
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* _ASM_MICROBLAZE_PAGE_H */
arch/mips/include/asm/page.h +1 -0
index 4609cb0326cf3..3d91021538f02 100644
@@ -227,5 +227,6 @@ static inline unsigned long kaslr_offset(void)
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* _ASM_PAGE_H */
arch/nios2/include/asm/page.h +2 -0
index 0722f88e63cc7..2e5f93beb42b7 100644
@@ -97,4 +97,6 @@ extern struct page *mem_map;
 
 #endif /* !__ASSEMBLY__ */
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif /* _ASM_NIOS2_PAGE_H */
arch/openrisc/include/asm/page.h +1 -0
index 1d5913f67c312..a0da2a9842241 100644
@@ -88,5 +88,6 @@ static inline unsigned long virt_to_pfn(const void *kaddr)
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* __ASM_OPENRISC_PAGE_H */
arch/parisc/include/asm/page.h +1 -0
index 4bea2e95798f0..2a75496237c09 100644
@@ -173,6 +173,7 @@ extern int npmem_ranges;
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 #include <asm/pdc.h>
 
 #define PAGE0   ((struct zeropage *)absolute_pointer(__PAGE_OFFSET))
arch/powerpc/include/asm/page.h +2 -0
index 83d0a4fc5f755..4601c115b6485 100644
@@ -300,4 +300,6 @@ static inline unsigned long kaslr_offset(void)
 #include <asm-generic/memory_model.h>
 #endif /* __ASSEMBLY__ */
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif /* _ASM_POWERPC_PAGE_H */
arch/riscv/include/asm/page.h +1 -0
index 7ede2111c5917..e5af7579e45bf 100644
@@ -204,5 +204,6 @@ static __always_inline void *pfn_to_kaddr(unsigned long pfn)
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* _ASM_RISCV_PAGE_H */
arch/s390/include/asm/page.h +1 -0
index 16e4caa931f1f..42157e7690a77 100644
@@ -275,6 +275,7 @@ static inline unsigned long virt_to_pfn(const void *kaddr)
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #define AMODE31_SIZE		(3 * PAGE_SIZE)
 
arch/sh/include/asm/page.h +1 -0
index f780b467e75d7..09533d46ef033 100644
@@ -162,5 +162,6 @@ typedef struct page *pgtable_t;
 
 #include <asm-generic/memory_model.h>
 #include <asm-generic/getorder.h>
+#include <asm-generic/pgtable-geometry.h>
 
 #endif /* __ASM_SH_PAGE_H */
arch/sparc/include/asm/page.h +3 -0
index 5e44cdf2a8f2b..4327fe2bfa010 100644
@@ -9,4 +9,7 @@
 #else
 #include <asm/page_32.h>
 #endif
+
+#include <asm-generic/pgtable-geometry.h>
+
 #endif
arch/um/include/asm/page.h +2 -0
index 9ef9a8aedfa66..f26011808f514 100644
@@ -119,4 +119,6 @@ extern unsigned long uml_physmem;
 #define __HAVE_ARCH_GATE_AREA 1
 #endif
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif	/* __UM_PAGE_H */
arch/x86/include/asm/page_types.h +2 -0
index 52f1b4ff0cc16..6d2381342047f 100644
@@ -71,4 +71,6 @@ extern void initmem_init(void);
 
 #endif	/* !__ASSEMBLY__ */
 
+#include <asm-generic/pgtable-geometry.h>
+
 #endif	/* _ASM_X86_PAGE_DEFS_H */
arch/xtensa/include/asm/page.h +1 -0
index 4db56ef052d22..86952cb32af23 100644
@@ -200,4 +200,5 @@ static inline unsigned long ___pa(unsigned long va)
 #endif /* __ASSEMBLY__ */
 
 #include <asm-generic/memory_model.h>
+#include <asm-generic/pgtable-geometry.h>
 #endif /* _XTENSA_PAGE_H */
include/asm-generic/pgtable-geometry.h new file +71 -0

71 lines not on this page · raw message

init/main.c +4 -1
index 206acdde51f5a..ba1515eb20b9d 100644
@@ -899,6 +899,8 @@ static void __init early_numa_node_init(void)
 #endif
 }
 
+static __init void do_ctors(void);
+
 asmlinkage __visible __init __no_sanitize_address __noreturn __no_stack_protector
 void start_kernel(void)
 {
@@ -910,6 +912,8 @@ void start_kernel(void)
 	debug_objects_early_init();
 	init_vmlinux_build_id();
 
+	do_ctors();
+
 	cgroup_init_early();
 
 	local_irq_disable();
@@ -1360,7 +1364,6 @@ static void __init do_basic_setup(void)
 	cpuset_init_smp();
 	driver_init();
 	init_irq_proc();
-	do_ctors();
 	do_initcalls();
 }
 
Signature · 1 line
2.43.0
author reviewer
#2 lore raw

RFC PATCH 2/57 vmlinux: Align to PAGE_SIZE_MAX

Increase alignment of structures requiring at least PAGE_SIZE alignment to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/asm-generic/vmlinux.lds.h | 32 +++++++++++++++----------------
 include/linux/linkage.h           |  4 ++--
 include/linux/percpu-defs.h       |  4 ++--
 3 files changed, 20 insertions(+), 20 deletions(-)
include/asm-generic/vmlinux.lds.h +16 -16
index 1ae44793132a8..5727f883001bb 100644
@@ -13,7 +13,7 @@
  *	. = START;
  *	__init_begin = .;
  *	HEAD_TEXT_SECTION
- *	INIT_TEXT_SECTION(PAGE_SIZE)
+ *	INIT_TEXT_SECTION(PAGE_SIZE_MAX)
  *	INIT_DATA_SECTION(...)
  *	PERCPU_SECTION(CACHELINE_SIZE)
  *	__init_end = .;
@@ -23,7 +23,7 @@
  *	_etext = .;
  *
  *      _sdata = .;
- *	RO_DATA(PAGE_SIZE)
+ *	RO_DATA(PAGE_SIZE_MAX)
  *	RW_DATA(...)
  *	_edata = .;
  *
@@ -371,10 +371,10 @@
  * Data section helpers
  */
 #define NOSAVE_DATA							\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	__nosave_begin = .;						\
 	*(.data..nosave)						\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	__nosave_end = .;
 
 #define PAGE_ALIGNED_DATA(page_align)					\
@@ -733,9 +733,9 @@
 	. = ALIGN(bss_align);						\
 	.bss : AT(ADDR(.bss) - LOAD_OFFSET) {				\
 		BSS_FIRST_SECTIONS					\
-		. = ALIGN(PAGE_SIZE);					\
+		. = ALIGN(PAGE_SIZE_MAX);				\
 		*(.bss..page_aligned)					\
-		. = ALIGN(PAGE_SIZE);					\
+		. = ALIGN(PAGE_SIZE_MAX);				\
 		*(.dynbss)						\
 		*(BSS_MAIN)						\
 		*(COMMON)						\
@@ -950,9 +950,9 @@
  */
 #ifdef CONFIG_AMD_MEM_ENCRYPT
 #define PERCPU_DECRYPTED_SECTION					\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	*(.data..percpu..decrypted)					\
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE_MAX);
 #else
 #define PERCPU_DECRYPTED_SECTION
 #endif
@@ -1030,7 +1030,7 @@
 #define PERCPU_INPUT(cacheline)						\
 	__per_cpu_start = .;						\
 	*(.data..percpu..first)						\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	*(.data..percpu..page_aligned)					\
 	. = ALIGN(cacheline);						\
 	*(.data..percpu..read_mostly)					\
@@ -1075,16 +1075,16 @@
  * PERCPU_SECTION - define output section for percpu area, simple version
  * @cacheline: cacheline size
  *
- * Align to PAGE_SIZE and outputs output section for percpu area.  This
+ * Align to PAGE_SIZE_MAX and outputs output section for percpu area.  This
  * macro doesn't manipulate @vaddr or @phdr and __per_cpu_load and
  * __per_cpu_start will be identical.
  *
- * This macro is equivalent to ALIGN(PAGE_SIZE); PERCPU_VADDR(@cacheline,,)
+ * This macro is equivalent to ALIGN(PAGE_SIZE_MAX); PERCPU_VADDR(@cacheline,,)
  * except that __per_cpu_load is defined as a relative symbol against
  * .data..percpu which is required for relocatable x86_32 configuration.
  */
 #define PERCPU_SECTION(cacheline)					\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	.data..percpu	: AT(ADDR(.data..percpu) - LOAD_OFFSET) {	\
 		__per_cpu_load = .;					\
 		PERCPU_INPUT(cacheline)					\
@@ -1102,15 +1102,15 @@
  * All sections are combined in a single .data section.
  * The sections following CONSTRUCTORS are arranged so their
  * typical alignment matches.
- * A cacheline is typical/always less than a PAGE_SIZE so
+ * A cacheline is typical/always less than a PAGE_SIZE_MAX so
  * the sections that has this restriction (or similar)
- * is located before the ones requiring PAGE_SIZE alignment.
- * NOSAVE_DATA starts and ends with a PAGE_SIZE alignment which
+ * is located before the ones requiring PAGE_SIZE_MAX alignment.
+ * NOSAVE_DATA starts and ends with a PAGE_SIZE_MAX alignment which
  * matches the requirement of PAGE_ALIGNED_DATA.
  *
  * use 0 as page_align if page_aligned data is not used */
 #define RW_DATA(cacheline, pagealigned, inittask)			\
-	. = ALIGN(PAGE_SIZE);						\
+	. = ALIGN(PAGE_SIZE_MAX);					\
 	.data : AT(ADDR(.data) - LOAD_OFFSET) {				\
 		INIT_TASK_DATA(inittask)				\
 		NOSAVE_DATA						\
include/linux/linkage.h +2 -2
index 5c8865bb59d91..68aa9775fce51 100644
@@ -36,8 +36,8 @@
 		  __stringify(name))
 #endif
 
-#define __page_aligned_data	__section(".data..page_aligned") __aligned(PAGE_SIZE)
-#define __page_aligned_bss	__section(".bss..page_aligned") __aligned(PAGE_SIZE)
+#define __page_aligned_data	__section(".data..page_aligned") __aligned(PAGE_SIZE_MAX)
+#define __page_aligned_bss	__section(".bss..page_aligned") __aligned(PAGE_SIZE_MAX)
 
 /*
  * For assembly routines.
include/linux/percpu-defs.h +2 -2
index 8efce7414fad6..89c7f430015ba 100644
@@ -156,11 +156,11 @@
  */
 #define DECLARE_PER_CPU_PAGE_ALIGNED(type, name)			\
 	DECLARE_PER_CPU_SECTION(type, name, "..page_aligned")		\
-	__aligned(PAGE_SIZE)
+	__aligned(PAGE_SIZE_MAX)
 
 #define DEFINE_PER_CPU_PAGE_ALIGNED(type, name)				\
 	DEFINE_PER_CPU_SECTION(type, name, "..page_aligned")		\
-	__aligned(PAGE_SIZE)
+	__aligned(PAGE_SIZE_MAX)
 
 /*
  * Declaration/definition used for per-CPU variables that must be read mostly.
Signature · 1 line
2.43.0
#3 lore raw

Re: [RFC PATCH v1 02/57] vmlinux: Align to PAGE_SIZE_MAX

Quoted 4 lines · Ryan Roberts

Increase alignment of structures requiring at least PAGE_SIZE alignment to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

Can you verify that this works with the arch specific portions? This may also allow to to reduce some of the arch dependent stuff.

author reviewer
#4 lore raw

Re: [RFC PATCH v1 02/57] vmlinux: Align to PAGE_SIZE_MAX

Quoted 9 lines · Christoph Lameter (Ampere)
Quoted 4 lines · Ryan Roberts

Increase alignment of structures requiring at least PAGE_SIZE alignment to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

Can you verify that this works with the arch specific portions? This may also allow to to reduce some of the arch dependent stuff.

Sorry, Chistoph, I'm not exactly sure what you mean here by "arch specific portions" and "reduce some of the arch dependent stuff"? Could you elaborate?

I can certainly verify that this change works for all the test scenarios I've listed on the cover letter.

Thanks,
Ryan

author reviewer
#5 lore raw

RFC PATCH 3/57 mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

In reply to Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 mm/memcontrol.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
mm/memcontrol.c +5 -4
index d563fb515766b..c5f9195f76c65 100644
@@ -95,6 +95,7 @@ static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
 
 #define THRESHOLDS_EVENTS_TARGET 128
 #define SOFTLIMIT_EVENTS_TARGET 1024
+#define SEQ_BUF_SIZE		SZ_4K
 
 static inline bool task_is_dying(void)
 {
@@ -1519,7 +1520,7 @@ void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *
 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
 {
 	/* Use static buffer, for the caller is holding oom_lock. */
-	static char buf[PAGE_SIZE];
+	static char buf[SEQ_BUF_SIZE];
 	struct seq_buf s;
 
 	lockdep_assert_held(&oom_lock);
@@ -1545,7 +1546,7 @@ void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
 	pr_info("Memory cgroup stats for ");
 	pr_cont_cgroup_path(memcg->css.cgroup);
 	pr_cont(":");
-	seq_buf_init(&s, buf, sizeof(buf));
+	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
 	memory_stat_format(memcg, &s);
 	seq_buf_do_printk(&s, KERN_INFO);
 }
@@ -4158,12 +4159,12 @@ static int memory_events_local_show(struct seq_file *m, void *v)
 int memory_stat_show(struct seq_file *m, void *v)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
-	char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
+	char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
 	struct seq_buf s;
 
 	if (!buf)
 		return -ENOMEM;
-	seq_buf_init(&s, buf, PAGE_SIZE);
+	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
 	memory_stat_format(memcg, &s);
 	seq_puts(m, buf);
 	kfree(buf);
Signature · 1 line
2.43.0
maintainer Acked-by on v1 3/57
#6 lore raw

Re: [RFC PATCH v1 03/57] mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

Quoted 11 lines · Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

maintainer Acked-by on v1 3/57
#7 lore raw

Re: [RFC PATCH v1 03/57] mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

In reply to Ryan Roberts
Quoted 11 lines · Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

author reviewer
#8 lore raw

Re: [RFC PATCH v1 03/57] mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

Quoted 7 lines · Shakeel Butt
Quoted 6 lines · Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

Quoted 7 lines
Quoted 5 lines

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

Thanks Shakeel and Johannes, for the acks. Given this patch is totally independent, I'll plan to resubmit it on its own and hopefully we can get it in independently of the rest of the series.

Thanks,
Ryan

reviewer Acked-by
#9 lore raw

Re: [RFC PATCH v1 03/57] mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

Quoted 12 lines · Ryan Roberts
Quoted 11 lines · Shakeel Butt
Quoted 10 lines · Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

Thanks Shakeel and Johannes, for the acks. Given this patch is totally independent, I'll plan to resubmit it on its own and hopefully we can get it in independently of the rest of the series.

Yes, this makes sense independent on the whole series.

Thanks!

Signature · 2 lines
Michal Hocko
SUSE Labs
maintainer Acked-by on v1 3/57
#10 lore raw

Re: [RFC PATCH v1 03/57] mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large

In reply to Ryan Roberts
Quoted 11 lines · Ryan Roberts

Previously the seq_buf used for accumulating the memory.stat output was sized at PAGE_SIZE. But the amount of output is invariant to PAGE_SIZE; If 4K is enough on a 4K page system, then it should also be enough on a 64K page system, so we can save 60K om the static buffer used in mem_cgroup_print_oom_meminfo(). Let's make it so.

This also has the beneficial side effect of removing a place in the code that assumed PAGE_SIZE is a compile-time constant. So this helps our quest towards supporting boot-time page size selection.

Thanks!

author reviewer
#11 lore raw

RFC PATCH 4/57 mm/page_alloc: Make page_frag_cache boot-time page size compatible

In reply to Ryan Roberts

"struct page_frag_cache" has some optimizations that depend on page size. Let's refactor it a bit so that those optimizations can be determined at run-time for the case where page size is a boot-time parameter. For compile-time page size, the compiler should dead code strip and the result is very similar to before.

One wrinkle is that we don't know if we need the size member until runtime. So remove the ifdeffery and always define offset as u32 (needed if PAGE_SIZE is >= 64K) and size as u16 (only used when PAGE_SIZE <= 32K). We move the members around a bit so that the overall size of the struct remains the same; 24 bytes for 64-bit and 16 bytes on 32 bit.

page_alloc
---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/mm_types.h | 13 ++++++-------
 mm/page_alloc.c          | 31 ++++++++++++++++++-------------
 2 files changed, 24 insertions(+), 20 deletions(-)
include/linux/mm_types.h +6 -7
index 4854249792545..0844ed7cfaa53 100644
@@ -544,16 +544,15 @@ static inline void *folio_get_private(struct folio *folio)
 
 struct page_frag_cache {
 	void * va;
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	__u16 offset;
-	__u16 size;
-#else
-	__u32 offset;
-#endif
 	/* we maintain a pagecount bias, so that we dont dirty cache line
 	 * containing page->_refcount every time we allocate a fragment.
 	 */
-	unsigned int		pagecnt_bias;
+	unsigned int pagecnt_bias;
+	__u32 offset;
+	/* size only used when PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE, in which
+	 * case PAGE_FRAG_CACHE_MAX_SIZE is 32K and 16 bits is sufficient.
+	 */
+	__u16 size;
 	bool pfmemalloc;
 };
 
mm/page_alloc.c +18 -13
index 91ace8ca97e21..8678103b1b396 100644
@@ -4822,13 +4822,18 @@ static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
 	struct page *page = NULL;
 	gfp_t gfp = gfp_mask;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
-		   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
-	page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
-				PAGE_FRAG_CACHE_MAX_ORDER);
-	nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
-#endif
+	if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) {
+		gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
+			   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
+		page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
+					PAGE_FRAG_CACHE_MAX_ORDER);
+		/*
+		 * Cast to silence warning due to 16-bit nc->size. Not real
+		 * because PAGE_SIZE only less than PAGE_FRAG_CACHE_MAX_SIZE
+		 * when PAGE_FRAG_CACHE_MAX_SIZE is 32K.
+		 */
+		nc->size = (__u16)(page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE);
+	}
 	if (unlikely(!page))
 		page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
 
@@ -4870,10 +4875,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 		if (!page)
 			return NULL;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* Even if we own the page, we do not use atomic_set().
 		 * This would break get_page_unless_zero() users.
 		 */
@@ -4897,10 +4902,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 			goto refill;
 		}
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* OK, page count is 0, we can safely set it */
 		set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
 
Signature · 1 line
2.43.0
#12 lore raw

Re: [RFC PATCH v1 04/57] mm/page_alloc: Make page_frag_cache boot-time page size compatible

Quoted 6 lines · Ryan Roberts

"struct page_frag_cache" has some optimizations that depend on page size. Let's refactor it a bit so that those optimizations can be determined at run-time for the case where page size is a boot-time parameter. For compile-time page size, the compiler should dead code strip and the result is very similar to before.

Quoted 7 lines

One wrinkle is that we don't know if we need the size member until runtime. So remove the ifdeffery and always define offset as u32 (needed if PAGE_SIZE is >= 64K) and size as u16 (only used when PAGE_SIZE <= 32K). We move the members around a bit so that the overall size of the struct remains the same; 24 bytes for 64-bit and 16 bytes on 32 bit.

Looks ok, but ideally the PAGE_FRAG_CACHE_MAX_ORDER #define should also be replaced by some variable that's populated just once. It can be static local to page_alloc.c as nothing else seems to use it.

Quoted 97 lines

page_alloc
---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/mm_types.h | 13 ++++++-------
 mm/page_alloc.c          | 31 ++++++++++++++++++-------------
 2 files changed, 24 insertions(+), 20 deletions(-)
include/linux/mm_types.h +6 -7
index 4854249792545..0844ed7cfaa53 100644
@@ -544,16 +544,15 @@ static inline void *folio_get_private(struct folio *folio)
 
 struct page_frag_cache {
 	void * va;
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	__u16 offset;
-	__u16 size;
-#else
-	__u32 offset;
-#endif
 	/* we maintain a pagecount bias, so that we dont dirty cache line
 	 * containing page->_refcount every time we allocate a fragment.
 	 */
-	unsigned int		pagecnt_bias;
+	unsigned int pagecnt_bias;
+	__u32 offset;
+	/* size only used when PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE, in which
+	 * case PAGE_FRAG_CACHE_MAX_SIZE is 32K and 16 bits is sufficient.
+	 */
+	__u16 size;
 	bool pfmemalloc;
 };
 
mm/page_alloc.c +18 -13
index 91ace8ca97e21..8678103b1b396 100644
@@ -4822,13 +4822,18 @@ static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
 	struct page *page = NULL;
 	gfp_t gfp = gfp_mask;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
-		   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
-	page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
-				PAGE_FRAG_CACHE_MAX_ORDER);
-	nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
-#endif
+	if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) {
+		gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
+			   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
+		page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
+					PAGE_FRAG_CACHE_MAX_ORDER);
+		/*
+		 * Cast to silence warning due to 16-bit nc->size. Not real
+		 * because PAGE_SIZE only less than PAGE_FRAG_CACHE_MAX_SIZE
+		 * when PAGE_FRAG_CACHE_MAX_SIZE is 32K.
+		 */
+		nc->size = (__u16)(page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE);
+	}
 	if (unlikely(!page))
 		page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
 
@@ -4870,10 +4875,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 		if (!page)
 			return NULL;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* Even if we own the page, we do not use atomic_set().
 		 * This would break get_page_unless_zero() users.
 		 */
@@ -4897,10 +4902,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 			goto refill;
 		}
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* OK, page count is 0, we can safely set it */
 		set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
 
author reviewer
#13 lore raw

Re: [RFC PATCH v1 04/57] mm/page_alloc: Make page_frag_cache boot-time page size compatible

Quoted 13 lines · Vlastimil Babka
Quoted 12 lines · Ryan Roberts

"struct page_frag_cache" has some optimizations that depend on page size. Let's refactor it a bit so that those optimizations can be determined at run-time for the case where page size is a boot-time parameter. For compile-time page size, the compiler should dead code strip and the result is very similar to before.

One wrinkle is that we don't know if we need the size member until runtime. So remove the ifdeffery and always define offset as u32 (needed if PAGE_SIZE is >= 64K) and size as u16 (only used when PAGE_SIZE <= 32K). We move the members around a bit so that the overall size of the struct remains the same; 24 bytes for 64-bit and 16 bytes on 32 bit.

Quoted 5 lines
Quoted 1 line

Looks ok, but ideally the PAGE_FRAG_CACHE_MAX_ORDER #define should also be replaced by some variable that's populated just once. It can be static local to page_alloc.c as nothing else seems to use it.

I can certainly do that, but wouldn't that be penalizing a compile-time page size configuration? My current change means that PAGE_FRAG_CACHE_MAX_ORDER still resolves to a compile-time constant in that situation and the compiler can eliminate conditional branches it knows will never be taken. Or perhaps you're suggesting I conditionally make it a variable if PAGE_SIZE_MIN != PAGE_SIZE_MAX?

Thanks,
Ryan

Quoted 99 lines
Quoted 98 lines

page_alloc
---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/mm_types.h | 13 ++++++-------
 mm/page_alloc.c          | 31 ++++++++++++++++++-------------
 2 files changed, 24 insertions(+), 20 deletions(-)
include/linux/mm_types.h +6 -7
index 4854249792545..0844ed7cfaa53 100644
@@ -544,16 +544,15 @@ static inline void *folio_get_private(struct folio *folio)
 
 struct page_frag_cache {
 	void * va;
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	__u16 offset;
-	__u16 size;
-#else
-	__u32 offset;
-#endif
 	/* we maintain a pagecount bias, so that we dont dirty cache line
 	 * containing page->_refcount every time we allocate a fragment.
 	 */
-	unsigned int		pagecnt_bias;
+	unsigned int pagecnt_bias;
+	__u32 offset;
+	/* size only used when PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE, in which
+	 * case PAGE_FRAG_CACHE_MAX_SIZE is 32K and 16 bits is sufficient.
+	 */
+	__u16 size;
 	bool pfmemalloc;
 };
 
mm/page_alloc.c +18 -13
index 91ace8ca97e21..8678103b1b396 100644
@@ -4822,13 +4822,18 @@ static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
 	struct page *page = NULL;
 	gfp_t gfp = gfp_mask;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
-	gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
-		   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
-	page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
-				PAGE_FRAG_CACHE_MAX_ORDER);
-	nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
-#endif
+	if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) {
+		gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) |  __GFP_COMP |
+			   __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
+		page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
+					PAGE_FRAG_CACHE_MAX_ORDER);
+		/*
+		 * Cast to silence warning due to 16-bit nc->size. Not real
+		 * because PAGE_SIZE only less than PAGE_FRAG_CACHE_MAX_SIZE
+		 * when PAGE_FRAG_CACHE_MAX_SIZE is 32K.
+		 */
+		nc->size = (__u16)(page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE);
+	}
 	if (unlikely(!page))
 		page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
 
@@ -4870,10 +4875,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 		if (!page)
 			return NULL;
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* Even if we own the page, we do not use atomic_set().
 		 * This would break get_page_unless_zero() users.
 		 */
@@ -4897,10 +4902,10 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc,
 			goto refill;
 		}
 
-#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
 		/* if size can vary use size else just use PAGE_SIZE */
-		size = nc->size;
-#endif
+		if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
+			size = nc->size;
+
 		/* OK, page count is 0, we can safely set it */
 		set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
 
#14 lore raw

Re: [RFC PATCH v1 04/57] mm/page_alloc: Make page_frag_cache boot-time page size compatible

Quoted 16 lines · Ryan Roberts
Quoted 15 lines · Vlastimil Babka
Quoted 13 lines · Ryan Roberts

"struct page_frag_cache" has some optimizations that depend on page size. Let's refactor it a bit so that those optimizations can be determined at run-time for the case where page size is a boot-time parameter. For compile-time page size, the compiler should dead code strip and the result is very similar to before.

One wrinkle is that we don't know if we need the size member until runtime. So remove the ifdeffery and always define offset as u32 (needed if PAGE_SIZE is >= 64K) and size as u16 (only used when PAGE_SIZE <= 32K). We move the members around a bit so that the overall size of the struct remains the same; 24 bytes for 64-bit and 16 bytes on 32 bit.

Quoted 8 lines
Quoted 3 lines

Looks ok, but ideally the PAGE_FRAG_CACHE_MAX_ORDER #define should also be replaced by some variable that's populated just once. It can be static local to page_alloc.c as nothing else seems to use it.

I can certainly do that, but wouldn't that be penalizing a compile-time page size configuration? My current change means that PAGE_FRAG_CACHE_MAX_ORDER still resolves to a compile-time constant in that situation and the compiler can eliminate conditional branches it knows will never be taken. Or perhaps you're

Ah, I see.

Quoted 1 line

suggesting I conditionally make it a variable if PAGE_SIZE_MIN != PAGE_SIZE_MAX?

Given the only place it's being used, it shouldn't be worth it after all.

You can add for this patch:

Quoted 2 lines

Thanks,
Ryan

author reviewer
#15 lore raw

RFC PATCH 5/57 mm: Avoid split pmd ptl if pmd level is run-time folded

In reply to Ryan Roberts

If there are only 2 levels of translation, the first level (pgd) may not be an entire page and so does not have a ptdesc backing it (this may be true on arm64 depending on the VA size and page size). Even if it is an entire page and does therefore have an entire ptdesc, pagetable_pmd_ctor() won't be called for the ptdesc (since it's a pgd not pmd table) and so the per-ptdec ptl fields won't be initialised.

To date this has been fine; the arch knows at compile time if it needs to fold the pmd level and in this case does not select CONFIG_ARCH_ENABLE_SPLIT_PMD_PTLOCK. However, if the number of levels are not known at compile time (as is the case for boot-time page size selection), we want to be able to choose at boot whether to use split pmd ptls in the pmd's ptdesc or simply fall back to the lock in the mm_struct.

So let's make that change; when CONFIG_ARCH_ENABLE_SPLIT_PMD_PTLOCK is selected, determine if it should be used at run-time based on mm_pmd_folded().

This sets us up for arm64 to support boot-time page size selection.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/mm.h       | 15 ++++++++++++++-
 include/linux/mm_types.h |  2 +-
 kernel/fork.c            |  4 ++--
 3 files changed, 17 insertions(+), 4 deletions(-)
include/linux/mm.h +14 -1
index 1470736017168..09a840517c23a 100644
@@ -3037,6 +3037,8 @@ static inline struct ptdesc *pmd_ptdesc(pmd_t *pmd)
 
 static inline spinlock_t *pmd_lockptr(struct mm_struct *mm, pmd_t *pmd)
 {
+	if (mm_pmd_folded(mm))
+		return &mm->page_table_lock;
 	return ptlock_ptr(pmd_ptdesc(pmd));
 }
 
@@ -3056,7 +3058,18 @@ static inline void pmd_ptlock_free(struct ptdesc *ptdesc)
 	ptlock_free(ptdesc);
 }
 
-#define pmd_huge_pte(mm, pmd) (pmd_ptdesc(pmd)->pmd_huge_pte)
+static inline pgtable_t *__pmd_huge_pte(struct mm_struct *mm, pmd_t *pmd)
+{
+#ifdef CONFIG_TRANSPARENT_HUGEPAGE
+	if (mm_pmd_folded(mm))
+		return &mm->pmd_huge_pte;
+	return &pmd_ptdesc(pmd)->pmd_huge_pte;
+#else
+	return NULL;
+#endif
+}
+
+#define pmd_huge_pte(mm, pmd) (*__pmd_huge_pte(mm, pmd))
 
 #else
 
include/linux/mm_types.h +1 -1
index 0844ed7cfaa53..87dc6de7b7baf 100644
@@ -946,7 +946,7 @@ struct mm_struct {
 #ifdef CONFIG_MMU_NOTIFIER
 		struct mmu_notifier_subscriptions *notifier_subscriptions;
 #endif
-#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
+#if defined(CONFIG_TRANSPARENT_HUGEPAGE)
 		pgtable_t pmd_huge_pte; /* protected by page_table_lock */
 #endif
 #ifdef CONFIG_NUMA_BALANCING
kernel/fork.c +2 -2
index cc760491f2012..ea472566d4fcc 100644
@@ -832,7 +832,7 @@ static void check_mm(struct mm_struct *mm)
 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
 				mm_pgtables_bytes(mm));
 
-#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
+#if defined(CONFIG_TRANSPARENT_HUGEPAGE)
 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
 #endif
 }
@@ -1276,7 +1276,7 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
 	RCU_INIT_POINTER(mm->exe_file, NULL);
 	mmu_notifier_subscriptions_init(mm);
 	init_tlb_flush_pending(mm);
-#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
+#if defined(CONFIG_TRANSPARENT_HUGEPAGE)
 	mm->pmd_huge_pte = NULL;
 #endif
 	mm_init_uprobes_state(mm);
Signature · 1 line
2.43.0
author reviewer
#16 lore raw

RFC PATCH 6/57 mm: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct vmap_block" to use a flexible array for used_mmap since VMAP_BBMAP_BITS is not a compile time constant for the boot-time page size case.

Update various BUILD_BUG_ON() instances to check against appropriate page size limit.

Re-define "union swap_header" so that it's no longer exactly page-sized. Instead define a flexible "magic" array with a define which tells the offset to where the magic signature begins.

Consider page size limit in some CPP condditionals.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/mtd/mtdswap.c         |  4 ++--
 include/linux/mm.h            |  2 +-
 include/linux/mm_types_task.h |  2 +-
 include/linux/mmzone.h        |  3 ++-
 include/linux/slab.h          |  7 ++++---
 include/linux/swap.h          | 17 ++++++++++++-----
 include/linux/swapops.h       |  6 +++++-
 mm/memcontrol.c               |  2 +-
 mm/memory.c                   |  4 ++--
 mm/mmap.c                     |  2 +-
 mm/page-writeback.c           |  2 +-
 mm/slub.c                     |  2 +-
 mm/sparse.c                   |  2 +-
 mm/swapfile.c                 |  2 +-
 mm/vmalloc.c                  |  7 ++++---
 15 files changed, 39 insertions(+), 25 deletions(-)
drivers/mtd/mtdswap.c +2 -2
index 680366616da24..7412a32708114 100644
@@ -1062,13 +1062,13 @@ static int mtdswap_auto_header(struct mtdswap_dev *d, char *buf)
 {
 	union swap_header *hd = (union swap_header *)(buf);
 
-	memset(buf, 0, PAGE_SIZE - 10);
+	memset(buf, 0, SWAP_HEADER_MAGIC);
 
 	hd->info.version = 1;
 	hd->info.last_page = d->mbd_dev->size - 1;
 	hd->info.nr_badpages = 0;
 
-	memcpy(buf + PAGE_SIZE - 10, "SWAPSPACE2", 10);
+	memcpy(buf + SWAP_HEADER_MAGIC, "SWAPSPACE2", 10);
 
 	return 0;
 }
include/linux/mm.h +1 -1
index 09a840517c23a..49c2078354e6e 100644
@@ -2927,7 +2927,7 @@ static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmd)
 static inline spinlock_t *ptep_lockptr(struct mm_struct *mm, pte_t *pte)
 {
 	BUILD_BUG_ON(IS_ENABLED(CONFIG_HIGHPTE));
-	BUILD_BUG_ON(MAX_PTRS_PER_PTE * sizeof(pte_t) > PAGE_SIZE);
+	BUILD_BUG_ON(MAX_PTRS_PER_PTE * sizeof(pte_t) > PAGE_SIZE_MAX);
 	return ptlock_ptr(virt_to_ptdesc(pte));
 }
 
include/linux/mm_types_task.h +1 -1
index a2f6179b672b8..c356897d5f41c 100644
@@ -37,7 +37,7 @@ struct page;
 
 struct page_frag {
 	struct page *page;
-#if (BITS_PER_LONG > 32) || (PAGE_SIZE >= 65536)
+#if (BITS_PER_LONG > 32) || (PAGE_SIZE_MAX >= 65536)
 	__u32 offset;
 	__u32 size;
 #else
include/linux/mmzone.h +2 -1
index 1dc6248feb832..cd58034b82c81 100644
@@ -1744,6 +1744,7 @@ static inline bool movable_only_nodes(nodemask_t *nodes)
  */
 #define PA_SECTION_SHIFT	(SECTION_SIZE_BITS)
 #define PFN_SECTION_SHIFT	(SECTION_SIZE_BITS - PAGE_SHIFT)
+#define PFN_SECTION_SHIFT_MIN	(SECTION_SIZE_BITS - PAGE_SHIFT_MAX)
 
 #define NR_MEM_SECTIONS		(1UL << SECTIONS_SHIFT)
 
@@ -1753,7 +1754,7 @@ static inline bool movable_only_nodes(nodemask_t *nodes)
 #define SECTION_BLOCKFLAGS_BITS \
 	((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
 
-#if (MAX_PAGE_ORDER + PAGE_SHIFT) > SECTION_SIZE_BITS
+#if (MAX_PAGE_ORDER + PAGE_SHIFT_MAX) > SECTION_SIZE_BITS
 #error Allocator MAX_PAGE_ORDER exceeds SECTION_SIZE
 #endif
 
include/linux/slab.h +4 -3
index eb2bf46291576..11c6ff3a12579 100644
@@ -347,7 +347,7 @@ static inline unsigned int arch_slab_minalign(void)
  */
 #define __assume_kmalloc_alignment __assume_aligned(ARCH_KMALLOC_MINALIGN)
 #define __assume_slab_alignment __assume_aligned(ARCH_SLAB_MINALIGN)
-#define __assume_page_alignment __assume_aligned(PAGE_SIZE)
+#define __assume_page_alignment __assume_aligned(PAGE_SIZE_MIN)
 
 /*
  * Kmalloc array related definitions
@@ -358,6 +358,7 @@ static inline unsigned int arch_slab_minalign(void)
  * (PAGE_SIZE*2).  Larger requests are passed to the page allocator.
  */
 #define KMALLOC_SHIFT_HIGH	(PAGE_SHIFT + 1)
+#define KMALLOC_SHIFT_HIGH_MAX	(PAGE_SHIFT_MAX + 1)
 #define KMALLOC_SHIFT_MAX	(MAX_PAGE_ORDER + PAGE_SHIFT)
 #ifndef KMALLOC_SHIFT_LOW
 #define KMALLOC_SHIFT_LOW	3
@@ -426,7 +427,7 @@ enum kmalloc_cache_type {
 	NR_KMALLOC_TYPES
 };
 
-typedef struct kmem_cache * kmem_buckets[KMALLOC_SHIFT_HIGH + 1];
+typedef struct kmem_cache * kmem_buckets[KMALLOC_SHIFT_HIGH_MAX + 1];
 
 extern kmem_buckets kmalloc_caches[NR_KMALLOC_TYPES];
 
@@ -524,7 +525,7 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
 	/* Will never be reached. Needed because the compiler may complain */
 	return -1;
 }
-static_assert(PAGE_SHIFT <= 20);
+static_assert(PAGE_SHIFT_MAX <= 20);
 #define kmalloc_index(s) __kmalloc_index(s, true)
 
 #include <linux/alloc_tag.h>
include/linux/swap.h +12 -5
index ba7ea95d1c57a..e85df0332979f 100644
@@ -132,10 +132,17 @@ static inline int current_is_kswapd(void)
  * bootbits...
  */
 union swap_header {
-	struct {
-		char reserved[PAGE_SIZE - 10];
-		char magic[10];			/* SWAP-SPACE or SWAPSPACE2 */
-	} magic;
+	/*
+	 * Exists conceptually, but since PAGE_SIZE may not be known at compile
+	 * time, we must access through pointer arithmetic at run time.
+	 *
+	 * struct {
+	 * 	char reserved[PAGE_SIZE - 10];
+	 * 	char magic[10];			   SWAP-SPACE or SWAPSPACE2
+	 * } magic;
+	 */
+#define SWAP_HEADER_MAGIC	(PAGE_SIZE - 10)
+	char magic[1];
 	struct {
 		char		bootbits[1024];	/* Space for disklabel etc. */
 		__u32		version;
@@ -201,7 +208,7 @@ struct swap_extent {
  * Max bad pages in the new format..
  */
 #define MAX_SWAP_BADPAGES \
-	((offsetof(union swap_header, magic.magic) - \
+	((SWAP_HEADER_MAGIC - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
 enum {
include/linux/swapops.h +5 -1
index cb468e418ea11..890fe6a3e6702 100644
@@ -34,10 +34,14 @@
  */
 #ifdef MAX_PHYSMEM_BITS
 #define SWP_PFN_BITS		(MAX_PHYSMEM_BITS - PAGE_SHIFT)
+#define SWP_PFN_BITS_MAX	(MAX_PHYSMEM_BITS - PAGE_SHIFT_MIN)
 #else  /* MAX_PHYSMEM_BITS */
 #define SWP_PFN_BITS		min_t(int, \
 				      sizeof(phys_addr_t) * 8 - PAGE_SHIFT, \
 				      SWP_TYPE_SHIFT)
+#define SWP_PFN_BITS_MAX	min_t(int, \
+				      sizeof(phys_addr_t) * 8 - PAGE_SHIFT_MIN, \
+				      SWP_TYPE_SHIFT)
 #endif	/* MAX_PHYSMEM_BITS */
 #define SWP_PFN_MASK		(BIT(SWP_PFN_BITS) - 1)
 
@@ -519,7 +523,7 @@ static inline struct folio *pfn_swap_entry_folio(swp_entry_t entry)
 static inline bool is_pfn_swap_entry(swp_entry_t entry)
 {
 	/* Make sure the swp offset can always store the needed fields */
-	BUILD_BUG_ON(SWP_TYPE_SHIFT < SWP_PFN_BITS);
+	BUILD_BUG_ON(SWP_TYPE_SHIFT < SWP_PFN_BITS_MAX);
 
 	return is_migration_entry(entry) || is_device_private_entry(entry) ||
 	       is_device_exclusive_entry(entry) || is_hwpoison_entry(entry);
mm/memcontrol.c +1 -1
index c5f9195f76c65..4b17bec566fbd 100644
@@ -4881,7 +4881,7 @@ static int __init mem_cgroup_init(void)
 	 * to work fine, we should make sure that the overfill threshold can't
 	 * exceed S32_MAX / PAGE_SIZE.
 	 */
-	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
+	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE_MIN);
 
 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
 				  memcg_hotplug_cpu_dead);
mm/memory.c +2 -2
index ebfc9768f801a..14b5ef6870486 100644
@@ -4949,8 +4949,8 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
 	return ret;
 }
 
-static unsigned long fault_around_pages __read_mostly =
-	65536 >> PAGE_SHIFT;
+static __DEFINE_GLOBAL_PAGE_SIZE_VAR(unsigned long, fault_around_pages,
+				     __read_mostly, 65536 >> PAGE_SHIFT);
 
 #ifdef CONFIG_DEBUG_FS
 static int fault_around_bytes_get(void *data, u64 *val)
mm/mmap.c +1 -1
index d0dfc85b209bb..d9642aba07ac4 100644
@@ -2279,7 +2279,7 @@ int expand_downwards(struct vm_area_struct *vma, unsigned long address)
 }
 
 /* enforced gap between the expanding stack and other mappings. */
-unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
+DEFINE_GLOBAL_PAGE_SIZE_VAR(unsigned long, stack_guard_gap, 256UL<<PAGE_SHIFT);
 
 static int __init cmdline_parse_stack_guard_gap(char *p)
 {
mm/page-writeback.c +1 -1
index 4430ac68e4c41..8fc9ac50749bd 100644
@@ -2292,7 +2292,7 @@ static int page_writeback_cpu_online(unsigned int cpu)
 #ifdef CONFIG_SYSCTL
 
 /* this is needed for the proc_doulongvec_minmax of vm_dirty_bytes */
-static const unsigned long dirty_bytes_min = 2 * PAGE_SIZE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(unsigned long, dirty_bytes_min, 2 * PAGE_SIZE);
 
 static struct ctl_table vm_page_writeback_sysctls[] = {
 	{
mm/slub.c +1 -1
index a77f354f83251..82f6e98cf25bb 100644
@@ -5001,7 +5001,7 @@ init_kmem_cache_node(struct kmem_cache_node *n)
 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
 {
 	BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
-			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
+			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH_MAX *
 			sizeof(struct kmem_cache_cpu));
 
 	/*
mm/sparse.c +1 -1
index dc38539f85603..2491425930c4d 100644
@@ -277,7 +277,7 @@ static unsigned long sparse_encode_mem_map(struct page *mem_map, unsigned long p
 {
 	unsigned long coded_mem_map =
 		(unsigned long)(mem_map - (section_nr_to_pfn(pnum)));
-	BUILD_BUG_ON(SECTION_MAP_LAST_BIT > PFN_SECTION_SHIFT);
+	BUILD_BUG_ON(SECTION_MAP_LAST_BIT > PFN_SECTION_SHIFT_MIN);
 	BUG_ON(coded_mem_map & ~SECTION_MAP_MASK);
 	return coded_mem_map;
 }
mm/swapfile.c +1 -1
index 38bdc439651ac..6311a1cc7e46b 100644
@@ -2931,7 +2931,7 @@ static unsigned long read_swap_header(struct swap_info_struct *p,
 	unsigned long swapfilepages;
 	unsigned long last_page;
 
-	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
+	if (memcmp("SWAPSPACE2", &swap_header->magic[SWAP_HEADER_MAGIC], 10)) {
 		pr_err("Unable to find swap-space signature\n");
 		return 0;
 	}
mm/vmalloc.c +4 -3
index a0df1e2e155a8..b4fbba204603c 100644
@@ -2497,12 +2497,12 @@ struct vmap_block {
 	spinlock_t lock;
 	struct vmap_area *va;
 	unsigned long free, dirty;
-	DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS);
 	unsigned long dirty_min, dirty_max; /*< dirty range */
 	struct list_head free_list;
 	struct rcu_head rcu_head;
 	struct list_head purge;
 	unsigned int cpu;
+	unsigned long used_map[];
 };
 
 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
@@ -2600,11 +2600,12 @@ static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
 	unsigned long vb_idx;
 	int node, err;
 	void *vaddr;
+	size_t size;
 
 	node = numa_node_id();
 
-	vb = kmalloc_node(sizeof(struct vmap_block),
-			gfp_mask & GFP_RECLAIM_MASK, node);
+	size = struct_size(vb, used_map, BITS_TO_LONGS(VMAP_BBMAP_BITS));
+	vb = kmalloc_node(size, gfp_mask & GFP_RECLAIM_MASK, node);
 	if (unlikely(!vb))
 		return ERR_PTR(-ENOMEM);
 
Signature · 1 line
2.43.0
author reviewer
#17 lore raw

Re: [RFC PATCH v1 06/57] mm: Remove PAGE_SIZE compile-time constant assumption

+ Matthew Wilcox

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 340 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct vmap_block" to use a flexible array for used_mmap since VMAP_BBMAP_BITS is not a compile time constant for the boot-time page size case.

Update various BUILD_BUG_ON() instances to check against appropriate page size limit.

Re-define "union swap_header" so that it's no longer exactly page-sized. Instead define a flexible "magic" array with a define which tells the offset to where the magic signature begins.

Consider page size limit in some CPP condditionals.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/mtd/mtdswap.c         |  4 ++--
 include/linux/mm.h            |  2 +-
 include/linux/mm_types_task.h |  2 +-
 include/linux/mmzone.h        |  3 ++-
 include/linux/slab.h          |  7 ++++---
 include/linux/swap.h          | 17 ++++++++++++-----
 include/linux/swapops.h       |  6 +++++-
 mm/memcontrol.c               |  2 +-
 mm/memory.c                   |  4 ++--
 mm/mmap.c                     |  2 +-
 mm/page-writeback.c           |  2 +-
 mm/slub.c                     |  2 +-
 mm/sparse.c                   |  2 +-
 mm/swapfile.c                 |  2 +-
 mm/vmalloc.c                  |  7 ++++---
 15 files changed, 39 insertions(+), 25 deletions(-)
drivers/mtd/mtdswap.c +2 -2
index 680366616da24..7412a32708114 100644
@@ -1062,13 +1062,13 @@ static int mtdswap_auto_header(struct mtdswap_dev *d, char *buf)
 {
 	union swap_header *hd = (union swap_header *)(buf);
 
-	memset(buf, 0, PAGE_SIZE - 10);
+	memset(buf, 0, SWAP_HEADER_MAGIC);
 
 	hd->info.version = 1;
 	hd->info.last_page = d->mbd_dev->size - 1;
 	hd->info.nr_badpages = 0;
 
-	memcpy(buf + PAGE_SIZE - 10, "SWAPSPACE2", 10);
+	memcpy(buf + SWAP_HEADER_MAGIC, "SWAPSPACE2", 10);
 
 	return 0;
 }
include/linux/mm.h +1 -1
index 09a840517c23a..49c2078354e6e 100644
@@ -2927,7 +2927,7 @@ static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmd)
 static inline spinlock_t *ptep_lockptr(struct mm_struct *mm, pte_t *pte)
 {
 	BUILD_BUG_ON(IS_ENABLED(CONFIG_HIGHPTE));
-	BUILD_BUG_ON(MAX_PTRS_PER_PTE * sizeof(pte_t) > PAGE_SIZE);
+	BUILD_BUG_ON(MAX_PTRS_PER_PTE * sizeof(pte_t) > PAGE_SIZE_MAX);
 	return ptlock_ptr(virt_to_ptdesc(pte));
 }
 
include/linux/mm_types_task.h +1 -1
index a2f6179b672b8..c356897d5f41c 100644
@@ -37,7 +37,7 @@ struct page;
 
 struct page_frag {
 	struct page *page;
-#if (BITS_PER_LONG > 32) || (PAGE_SIZE >= 65536)
+#if (BITS_PER_LONG > 32) || (PAGE_SIZE_MAX >= 65536)
 	__u32 offset;
 	__u32 size;
 #else
include/linux/mmzone.h +2 -1
index 1dc6248feb832..cd58034b82c81 100644
@@ -1744,6 +1744,7 @@ static inline bool movable_only_nodes(nodemask_t *nodes)
  */
 #define PA_SECTION_SHIFT	(SECTION_SIZE_BITS)
 #define PFN_SECTION_SHIFT	(SECTION_SIZE_BITS - PAGE_SHIFT)
+#define PFN_SECTION_SHIFT_MIN	(SECTION_SIZE_BITS - PAGE_SHIFT_MAX)
 
 #define NR_MEM_SECTIONS		(1UL << SECTIONS_SHIFT)
 
@@ -1753,7 +1754,7 @@ static inline bool movable_only_nodes(nodemask_t *nodes)
 #define SECTION_BLOCKFLAGS_BITS \
 	((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
 
-#if (MAX_PAGE_ORDER + PAGE_SHIFT) > SECTION_SIZE_BITS
+#if (MAX_PAGE_ORDER + PAGE_SHIFT_MAX) > SECTION_SIZE_BITS
 #error Allocator MAX_PAGE_ORDER exceeds SECTION_SIZE
 #endif
 
include/linux/slab.h +4 -3
index eb2bf46291576..11c6ff3a12579 100644
@@ -347,7 +347,7 @@ static inline unsigned int arch_slab_minalign(void)
  */
 #define __assume_kmalloc_alignment __assume_aligned(ARCH_KMALLOC_MINALIGN)
 #define __assume_slab_alignment __assume_aligned(ARCH_SLAB_MINALIGN)
-#define __assume_page_alignment __assume_aligned(PAGE_SIZE)
+#define __assume_page_alignment __assume_aligned(PAGE_SIZE_MIN)
 
 /*
  * Kmalloc array related definitions
@@ -358,6 +358,7 @@ static inline unsigned int arch_slab_minalign(void)
  * (PAGE_SIZE*2).  Larger requests are passed to the page allocator.
  */
 #define KMALLOC_SHIFT_HIGH	(PAGE_SHIFT + 1)
+#define KMALLOC_SHIFT_HIGH_MAX	(PAGE_SHIFT_MAX + 1)
 #define KMALLOC_SHIFT_MAX	(MAX_PAGE_ORDER + PAGE_SHIFT)
 #ifndef KMALLOC_SHIFT_LOW
 #define KMALLOC_SHIFT_LOW	3
@@ -426,7 +427,7 @@ enum kmalloc_cache_type {
 	NR_KMALLOC_TYPES
 };
 
-typedef struct kmem_cache * kmem_buckets[KMALLOC_SHIFT_HIGH + 1];
+typedef struct kmem_cache * kmem_buckets[KMALLOC_SHIFT_HIGH_MAX + 1];
 
 extern kmem_buckets kmalloc_caches[NR_KMALLOC_TYPES];
 
@@ -524,7 +525,7 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
 	/* Will never be reached. Needed because the compiler may complain */
 	return -1;
 }
-static_assert(PAGE_SHIFT <= 20);
+static_assert(PAGE_SHIFT_MAX <= 20);
 #define kmalloc_index(s) __kmalloc_index(s, true)
 
 #include <linux/alloc_tag.h>
include/linux/swap.h +12 -5
index ba7ea95d1c57a..e85df0332979f 100644
@@ -132,10 +132,17 @@ static inline int current_is_kswapd(void)
  * bootbits...
  */
 union swap_header {
-	struct {
-		char reserved[PAGE_SIZE - 10];
-		char magic[10];			/* SWAP-SPACE or SWAPSPACE2 */
-	} magic;
+	/*
+	 * Exists conceptually, but since PAGE_SIZE may not be known at compile
+	 * time, we must access through pointer arithmetic at run time.
+	 *
+	 * struct {
+	 * 	char reserved[PAGE_SIZE - 10];
+	 * 	char magic[10];			   SWAP-SPACE or SWAPSPACE2
+	 * } magic;
+	 */
+#define SWAP_HEADER_MAGIC	(PAGE_SIZE - 10)
+	char magic[1];
 	struct {
 		char		bootbits[1024];	/* Space for disklabel etc. */
 		__u32		version;
@@ -201,7 +208,7 @@ struct swap_extent {
  * Max bad pages in the new format..
  */
 #define MAX_SWAP_BADPAGES \
-	((offsetof(union swap_header, magic.magic) - \
+	((SWAP_HEADER_MAGIC - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
 enum {
include/linux/swapops.h +5 -1
index cb468e418ea11..890fe6a3e6702 100644
@@ -34,10 +34,14 @@
  */
 #ifdef MAX_PHYSMEM_BITS
 #define SWP_PFN_BITS		(MAX_PHYSMEM_BITS - PAGE_SHIFT)
+#define SWP_PFN_BITS_MAX	(MAX_PHYSMEM_BITS - PAGE_SHIFT_MIN)
 #else  /* MAX_PHYSMEM_BITS */
 #define SWP_PFN_BITS		min_t(int, \
 				      sizeof(phys_addr_t) * 8 - PAGE_SHIFT, \
 				      SWP_TYPE_SHIFT)
+#define SWP_PFN_BITS_MAX	min_t(int, \
+				      sizeof(phys_addr_t) * 8 - PAGE_SHIFT_MIN, \
+				      SWP_TYPE_SHIFT)
 #endif	/* MAX_PHYSMEM_BITS */
 #define SWP_PFN_MASK		(BIT(SWP_PFN_BITS) - 1)
 
@@ -519,7 +523,7 @@ static inline struct folio *pfn_swap_entry_folio(swp_entry_t entry)
 static inline bool is_pfn_swap_entry(swp_entry_t entry)
 {
 	/* Make sure the swp offset can always store the needed fields */
-	BUILD_BUG_ON(SWP_TYPE_SHIFT < SWP_PFN_BITS);
+	BUILD_BUG_ON(SWP_TYPE_SHIFT < SWP_PFN_BITS_MAX);
 
 	return is_migration_entry(entry) || is_device_private_entry(entry) ||
 	       is_device_exclusive_entry(entry) || is_hwpoison_entry(entry);
mm/memcontrol.c +1 -1
index c5f9195f76c65..4b17bec566fbd 100644
@@ -4881,7 +4881,7 @@ static int __init mem_cgroup_init(void)
 	 * to work fine, we should make sure that the overfill threshold can't
 	 * exceed S32_MAX / PAGE_SIZE.
 	 */
-	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
+	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE_MIN);
 
 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
 				  memcg_hotplug_cpu_dead);
mm/memory.c +2 -2
index ebfc9768f801a..14b5ef6870486 100644
@@ -4949,8 +4949,8 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
 	return ret;
 }
 
-static unsigned long fault_around_pages __read_mostly =
-	65536 >> PAGE_SHIFT;
+static __DEFINE_GLOBAL_PAGE_SIZE_VAR(unsigned long, fault_around_pages,
+				     __read_mostly, 65536 >> PAGE_SHIFT);
 
 #ifdef CONFIG_DEBUG_FS
 static int fault_around_bytes_get(void *data, u64 *val)
mm/mmap.c +1 -1
index d0dfc85b209bb..d9642aba07ac4 100644
@@ -2279,7 +2279,7 @@ int expand_downwards(struct vm_area_struct *vma, unsigned long address)
 }
 
 /* enforced gap between the expanding stack and other mappings. */
-unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
+DEFINE_GLOBAL_PAGE_SIZE_VAR(unsigned long, stack_guard_gap, 256UL<<PAGE_SHIFT);
 
 static int __init cmdline_parse_stack_guard_gap(char *p)
 {
mm/page-writeback.c +1 -1
index 4430ac68e4c41..8fc9ac50749bd 100644
@@ -2292,7 +2292,7 @@ static int page_writeback_cpu_online(unsigned int cpu)
 #ifdef CONFIG_SYSCTL
 
 /* this is needed for the proc_doulongvec_minmax of vm_dirty_bytes */
-static const unsigned long dirty_bytes_min = 2 * PAGE_SIZE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(unsigned long, dirty_bytes_min, 2 * PAGE_SIZE);
 
 static struct ctl_table vm_page_writeback_sysctls[] = {
 	{
mm/slub.c +1 -1
index a77f354f83251..82f6e98cf25bb 100644
@@ -5001,7 +5001,7 @@ init_kmem_cache_node(struct kmem_cache_node *n)
 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
 {
 	BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
-			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
+			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH_MAX *
 			sizeof(struct kmem_cache_cpu));
 
 	/*
mm/sparse.c +1 -1
index dc38539f85603..2491425930c4d 100644
@@ -277,7 +277,7 @@ static unsigned long sparse_encode_mem_map(struct page *mem_map, unsigned long p
 {
 	unsigned long coded_mem_map =
 		(unsigned long)(mem_map - (section_nr_to_pfn(pnum)));
-	BUILD_BUG_ON(SECTION_MAP_LAST_BIT > PFN_SECTION_SHIFT);
+	BUILD_BUG_ON(SECTION_MAP_LAST_BIT > PFN_SECTION_SHIFT_MIN);
 	BUG_ON(coded_mem_map & ~SECTION_MAP_MASK);
 	return coded_mem_map;
 }
mm/swapfile.c +1 -1
index 38bdc439651ac..6311a1cc7e46b 100644
@@ -2931,7 +2931,7 @@ static unsigned long read_swap_header(struct swap_info_struct *p,
 	unsigned long swapfilepages;
 	unsigned long last_page;
 
-	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
+	if (memcmp("SWAPSPACE2", &swap_header->magic[SWAP_HEADER_MAGIC], 10)) {
 		pr_err("Unable to find swap-space signature\n");
 		return 0;
 	}
mm/vmalloc.c +4 -3
index a0df1e2e155a8..b4fbba204603c 100644
@@ -2497,12 +2497,12 @@ struct vmap_block {
 	spinlock_t lock;
 	struct vmap_area *va;
 	unsigned long free, dirty;
-	DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS);
 	unsigned long dirty_min, dirty_max; /*< dirty range */
 	struct list_head free_list;
 	struct rcu_head rcu_head;
 	struct list_head purge;
 	unsigned int cpu;
+	unsigned long used_map[];
 };
 
 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
@@ -2600,11 +2600,12 @@ static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
 	unsigned long vb_idx;
 	int node, err;
 	void *vaddr;
+	size_t size;
 
 	node = numa_node_id();
 
-	vb = kmalloc_node(sizeof(struct vmap_block),
-			gfp_mask & GFP_RECLAIM_MASK, node);
+	size = struct_size(vb, used_map, BITS_TO_LONGS(VMAP_BBMAP_BITS));
+	vb = kmalloc_node(size, gfp_mask & GFP_RECLAIM_MASK, node);
 	if (unlikely(!vb))
 		return ERR_PTR(-ENOMEM);
 
#18 lore raw

RFC PATCH 1/1 mm/slab: Avoid build bug for calls to kmalloc with a large constant

In reply to Ryan Roberts

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

 include/linux/slab.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
 	if (size <= 1024 * 1024) return 20;
 	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
 		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
 	else
 		BUG();
Signature · 1 line
2.47.0
author reviewer
#19 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 25 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

 include/linux/slab.h | 3 ++-

 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +0 -0
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t
 size,
      if (size <= 1024 * 1024) return 20;
      if (size <=  2 * 1024 * 1024) return 21;
Quoted 3 lines


-    if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant) +    if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&

Thanks for the patch! I think this may be better as:

       if (PAGE_SHIFT_MIN == PAGE_SHIFT_MAX &&

Since that is independent of the architecture. Your approach wouldn't work if another arch wanted to enable boot time page size, or if arm64 dropped the Kconfig because it decided only boot time page size will be supported in future.

Thanks,
Ryan

Quoted 4 lines

+        !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant) BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()"); else
         BUG();

#20 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 32 lines · Ryan Roberts
Quoted 22 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +0 -0
index 9848296ca6ba..a4c7507ab8ec 100644

include/linux/slab.h static __always_inline unsigned int __kmalloc_index(size_t · line 689

Quoted 6 lines
include/linux/slab.h +1 -1
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t
 size,
      if (size <= 1024 * 1024) return 20;
      if (size <=  2 * 1024 * 1024) return 21;
 
-    if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+    if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&

Thanks for the patch! I think this may be better as:

Quoted 5 lines
        if (PAGE_SHIFT_MIN == PAGE_SHIFT_MAX &&

Since that is independent of the architecture. Your approach wouldn't work if another arch wanted to enable boot time page size, or if arm64 dropped the Kconfig because it decided only boot time page size will be supported in future.

Absolutely. I may be sending some more. I haven't gotten to JFS yet, but that one is my responsibility.

Thanks,
Shaggy

Quoted 9 lines

Thanks,
Ryan

Quoted 4 lines
include/linux/slab.h +1 -0
+        !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
          BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
      else

         BUG();

#21 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

In reply to Dave Kleikamp
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
author reviewer
#22 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

I'm happy to make this change if you're certain it's the right approach; please confirm.

Quoted 4 lines

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

I'm inferring from this that perhaps there is a memory cost with having the higher orders defined but unused.

Thanks,
Ryan

Quoted 31 lines

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
#23 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Quoted 2 lines

I'm happy to make this change if you're certain it's the right approach; please confirm.

Yes it's much better option than breaking the build-time-constant part of kmalloc_noprof().

Quoted 7 lines
Quoted 4 lines

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

I'm inferring from this that perhaps there is a memory cost with having the higher orders defined but unused.

Yeah as per above, should not be too large and we could tune it down if necessary.

Quoted 35 lines

Thanks,
Ryan

Quoted 31 lines

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
author reviewer
#24 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 35 lines · Vlastimil Babka
Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Quoted 5 lines
Quoted 2 lines

I'm happy to make this change if you're certain it's the right approach; please confirm.

Yes it's much better option than breaking the build-time-constant part of kmalloc_noprof().

OK, I'll take this approach as you suggest.

Thanks,
Ryan

Quoted 48 lines
Quoted 8 lines
Quoted 5 lines

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

I'm inferring from this that perhaps there is a memory cost with having the higher orders defined but unused.

Yeah as per above, should not be too large and we could tune it down if necessary.

Quoted 35 lines

Thanks,
Ryan

Quoted 31 lines

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
author reviewer
#25 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

In reply to Vlastimil Babka
Quoted 26 lines · Vlastimil Babka
Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Quoted 8 lines

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Sorry to keep pushing on this, now that I've actually looked at the code, I feel I have a slightly better understanding:

void *kmalloc_noprof(size_t size, gfp_t flags)

{
	if (__builtin_constant_p(size) && size) {
		
		if (size > KMALLOC_MAX_CACHE_SIZE)
			return __kmalloc_large_noprof(size, flags); <<< (1)

		index = kmalloc_index(size);
		return __kmalloc_cache_noprof(...);   <<< (2)
	}
	return __kmalloc_noprof(size, flags);   <<< (3)
}

So if size and KMALLOC_MAX_CACHE_SIZE are constant, we end up with this resolving either to a call to (1) or (2), decided at compile time. If KMALLOC_MAX_CACHE_SIZE is not constant, (1), (2) and the runtime conditional need to be kept in the function.

But intuatively, I would have guessed that given the choice between the overhead of keeping that runtime conditional vs keeping per-cpu slab caches for extra sizes between 16K and 128K, then the runtime conditional would be preferable. I would guess that quite a bit of memory could get tied up in those caches?

Why is your preference the opposite? What am I not understanding?

Quoted 54 lines
Quoted 3 lines

I'm happy to make this change if you're certain it's the right approach; please confirm.

Yes it's much better option than breaking the build-time-constant part of kmalloc_noprof().

Quoted 7 lines
Quoted 4 lines

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

I'm inferring from this that perhaps there is a memory cost with having the higher orders defined but unused.

Yeah as per above, should not be too large and we could tune it down if necessary.

Quoted 35 lines

Thanks,
Ryan

Quoted 31 lines

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
#26 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 57 lines · Ryan Roberts
Quoted 26 lines · Vlastimil Babka
Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Quoted 8 lines

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Sorry to keep pushing on this, now that I've actually looked at the code, I feel I have a slightly better understanding:

void *kmalloc_noprof(size_t size, gfp_t flags)

{
	if (__builtin_constant_p(size) && size) {
		
		if (size > KMALLOC_MAX_CACHE_SIZE)
			return __kmalloc_large_noprof(size, flags); <<< (1)

		index = kmalloc_index(size);
		return __kmalloc_cache_noprof(...);   <<< (2)
	}
	return __kmalloc_noprof(size, flags);   <<< (3)
}

So if size and KMALLOC_MAX_CACHE_SIZE are constant, we end up with this resolving either to a call to (1) or (2), decided at compile time. If KMALLOC_MAX_CACHE_SIZE is not constant, (1), (2) and the runtime conditional need to be kept in the function.

Quoted 6 lines

But intuatively, I would have guessed that given the choice between the overhead of keeping that runtime conditional vs keeping per-cpu slab caches for extra sizes between 16K and 128K, then the runtime conditional would be preferable. I would guess that quite a bit of memory could get tied up in those caches?

Why is your preference the opposite? What am I not understanding?

+CC more slab people.

So the above is an inline function, but constructed in a way that it should, without further inline code, become
- a call to __kmalloc_large_noprof() for build-time constant size larger than KMALLOC_MAX_CACHE_SIZE
- a call to __kmalloc_cache_noprof() for build-time constant size smaller than KMALLOC_MAX_CACHE_SIZE, where the cache is picked from an array with compile-time calculated index
- call to __kmalloc_noprof() for non-constant sizes otherwise

If KMALLOC_MAX_CACHE_SIZE stops being build-time constant, the sensible way to handle it would be to #ifdef or otherwise compile out away the whole "if __builtin_constant_p(size)" part and just call __kmalloc_noprof() always, so we don't blow the inline paths with a KMALLOC_MAX_CACHE_SIZE check leading to choice between calling __kmalloc_large_noprof() or __kmalloc_cache_noprof().

I just don't believe we would waste so much memory with caches the extra sizes for sizes between 16K and 128K, so would do that suggestion only if proven wrong. But I wouldn't mind it that much if you chose it right away. The solution earlier in this thread to patch __kmalloc_index() would be worse than either of those two alternatives though.

Quoted 56 lines
Quoted 55 lines
Quoted 4 lines

I'm happy to make this change if you're certain it's the right approach; please confirm.

Yes it's much better option than breaking the build-time-constant part of kmalloc_noprof().

Quoted 7 lines
Quoted 4 lines

Maybe we could also stop adding + 1 to PAGE_SHIFT_MAX if it's >=64k, so the cache size is max 64k and not 128k but that should be probably evaluated separately from this series.

I'm inferring from this that perhaps there is a memory cost with having the higher orders defined but unused.

Yeah as per above, should not be too large and we could tune it down if necessary.

Quoted 35 lines

Thanks,
Ryan

Quoted 31 lines

Vlastimil

Quoted 27 lines

Found compiling drivers/net/ethernet/qlogic/qed/qed_sriov.c

---

Ryan,

Please consider incorporating this fix or something similar into your mm patch in the boot-time pages size patches.

  include/linux/slab.h | 3 ++-
  1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/slab.h +2 -1
index 9848296ca6ba..a4c7507ab8ec 100644
@@ -685,7 +685,8 @@ static __always_inline unsigned int __kmalloc_index(size_t size,
  	if (size <= 1024 * 1024) return 20;
  	if (size <=  2 * 1024 * 1024) return 21;
 
-	if (!IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
+	if (!IS_ENABLED(CONFIG_ARM64_BOOT_TIME_PAGE_SIZE) &&
+	    !IS_ENABLED(CONFIG_PROFILE_ALL_BRANCHES) && size_is_constant)
  		BUILD_BUG_ON_MSG(1, "unexpected size in kmalloc_index()");
  	else
  		BUG();
#27 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 76 lines · Vlastimil Babka
Quoted 57 lines · Ryan Roberts
Quoted 26 lines · Vlastimil Babka
Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Quoted 8 lines

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Sorry to keep pushing on this, now that I've actually looked at the code, I feel I have a slightly better understanding:

void *kmalloc_noprof(size_t size, gfp_t flags)

{
	if (__builtin_constant_p(size) && size) {
		
		if (size > KMALLOC_MAX_CACHE_SIZE)
			return __kmalloc_large_noprof(size, flags); <<< (1)

		index = kmalloc_index(size);
		return __kmalloc_cache_noprof(...);   <<< (2)
	}
	return __kmalloc_noprof(size, flags);   <<< (3)
}

So if size and KMALLOC_MAX_CACHE_SIZE are constant, we end up with this resolving either to a call to (1) or (2), decided at compile time. If KMALLOC_MAX_CACHE_SIZE is not constant, (1), (2) and the runtime conditional need to be kept in the function.

Quoted 6 lines

But intuatively, I would have guessed that given the choice between the overhead of keeping that runtime conditional vs keeping per-cpu slab caches for extra sizes between 16K and 128K, then the runtime conditional would be preferable. I would guess that quite a bit of memory could get tied up in those caches?

Why is your preference the opposite? What am I not understanding?

+CC more slab people.

So the above is an inline function, but constructed in a way that it should, without further inline code, become
- a call to __kmalloc_large_noprof() for build-time constant size larger than KMALLOC_MAX_CACHE_SIZE
- a call to __kmalloc_cache_noprof() for build-time constant size smaller than KMALLOC_MAX_CACHE_SIZE, where the cache is picked from an array with compile-time calculated index
- call to __kmalloc_noprof() for non-constant sizes otherwise

Quoted 5 lines

If KMALLOC_MAX_CACHE_SIZE stops being build-time constant, the sensible way to handle it would be to #ifdef or otherwise compile out away the whole "if __builtin_constant_p(size)" part and just call __kmalloc_noprof() always, so we don't blow the inline paths with a KMALLOC_MAX_CACHE_SIZE check leading to choice between calling __kmalloc_large_noprof() or __kmalloc_cache_noprof().

Or maybe we could have PAGE_SIZE_MAX derived KMALLOC_MAX_CACHE_SIZE_MAX behave as the code above currently does with KMALLOC_MAX_CACHE_SIZE, and additionally have PAGE_SIZE_MIN derived KMALLOC_MAX_CACHE_SIZE_MIN, where build-time-constant size larger than KMALLOC_MAX_CACHE_SIZE_MIN (which is a compile-time test) is redirected to __kmalloc_noprof() for a run-time test.

That seems like the optimum solution :)

Quoted 5 lines

I just don't believe we would waste so much memory with caches the extra sizes for sizes between 16K and 128K, so would do that suggestion only if proven wrong. But I wouldn't mind it that much if you chose it right away. The solution earlier in this thread to patch __kmalloc_index() would be worse than either of those two alternatives though.

author reviewer
#28 lore raw

Re: [RFC PATCH] mm/slab: Avoid build bug for calls to kmalloc with a large constant

Quoted 83 lines · Vlastimil Babka
Quoted 76 lines · Vlastimil Babka
Quoted 57 lines · Ryan Roberts
Quoted 26 lines · Vlastimil Babka
Quoted 18 lines · Ryan Roberts
Quoted 9 lines · Vlastimil Babka
Quoted 3 lines · Dave Kleikamp

When boot-time page size is enabled, the test against KMALLOC_MAX_CACHE_SIZE is no longer optimized out with a constant size, so a build bug may occur on a path that won't be reached.

That's rather unfortunate, the __builtin_constant_p(size) part of kmalloc_noprof() really expects things to resolve at compile time and it would be better to keep it that way.

Quoted 7 lines

I think it would be better if we based KMALLOC_MAX_CACHE_SIZE itself on PAGE_SHIFT_MAX and kept it constant, instead of introducing KMALLOC_SHIFT_HIGH_MAX only for some sanity checks.

So if the kernel was built to support 4k to 64k, but booted as 4k, it would still create and use kmalloc caches up to 128k. SLUB should handle that fine (if not, please report it :)

Quoted 6 lines

So when PAGE_SIZE_MAX=64K and PAGE_SIZE=4K, kmalloc will support up to 128K whereas before it only supported up to 8K. I was trying to avoid that since I assumed that would be costly in terms of extra memory allocated for those higher order buckets that will never be used. But I have no idea how SLUB works in practice. Perhaps memory for the cache is only lazily allocated so we won't see an issue in practice?

Quoted 8 lines

Yes the e.g. 128k slabs themselves will be lazily allocated. There will be some overhead with the management structures (struct kmem_cache etc) but much smaller.
To be completely honest, some extra overhead might come to be when the slabs are allocated ans later the user frees those allocations. kmalloc_large() wwould return them immediately, while a regular kmem_cache will keep one or more per cpu for reuse. But if that becomes a visible problem we can tune those caches to discard slabs more aggressively.

Sorry to keep pushing on this, now that I've actually looked at the code, I feel I have a slightly better understanding:

void *kmalloc_noprof(size_t size, gfp_t flags)

{
	if (__builtin_constant_p(size) && size) {
		
		if (size > KMALLOC_MAX_CACHE_SIZE)
			return __kmalloc_large_noprof(size, flags); <<< (1)

		index = kmalloc_index(size);
		return __kmalloc_cache_noprof(...);   <<< (2)
	}
	return __kmalloc_noprof(size, flags);   <<< (3)
}

So if size and KMALLOC_MAX_CACHE_SIZE are constant, we end up with this resolving either to a call to (1) or (2), decided at compile time. If KMALLOC_MAX_CACHE_SIZE is not constant, (1), (2) and the runtime conditional need to be kept in the function.

Quoted 6 lines

But intuatively, I would have guessed that given the choice between the overhead of keeping that runtime conditional vs keeping per-cpu slab caches for extra sizes between 16K and 128K, then the runtime conditional would be preferable. I would guess that quite a bit of memory could get tied up in those caches?

Why is your preference the opposite? What am I not understanding?

+CC more slab people.

So the above is an inline function, but constructed in a way that it should, without further inline code, become
- a call to __kmalloc_large_noprof() for build-time constant size larger than KMALLOC_MAX_CACHE_SIZE
- a call to __kmalloc_cache_noprof() for build-time constant size smaller than KMALLOC_MAX_CACHE_SIZE, where the cache is picked from an array with compile-time calculated index
- call to __kmalloc_noprof() for non-constant sizes otherwise

Quoted 5 lines

If KMALLOC_MAX_CACHE_SIZE stops being build-time constant, the sensible way to handle it would be to #ifdef or otherwise compile out away the whole "if __builtin_constant_p(size)" part and just call __kmalloc_noprof() always, so we don't blow the inline paths with a KMALLOC_MAX_CACHE_SIZE check leading to choice between calling __kmalloc_large_noprof() or __kmalloc_cache_noprof().

Quoted 7 lines

Or maybe we could have PAGE_SIZE_MAX derived KMALLOC_MAX_CACHE_SIZE_MAX behave as the code above currently does with KMALLOC_MAX_CACHE_SIZE, and additionally have PAGE_SIZE_MIN derived KMALLOC_MAX_CACHE_SIZE_MIN, where build-time-constant size larger than KMALLOC_MAX_CACHE_SIZE_MIN (which is a compile-time test) is redirected to __kmalloc_noprof() for a run-time test.

That seems like the optimum solution :)

Yes; that feels like the better approach to me. I'll implement this by default unless anyone else objects.

Quoted 8 lines
Quoted 6 lines

I just don't believe we would waste so much memory with caches the extra sizes for sizes between 16K and 128K, so would do that suggestion only if proven wrong. But I wouldn't mind it that much if you chose it right away. The solution earlier in this thread to patch __kmalloc_index() would be worse than either of those two alternatives though.

#29 lore raw

Re: [RFC PATCH v1 06/57] mm: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts
Quoted 57 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct vmap_block" to use a flexible array for used_mmap since VMAP_BBMAP_BITS is not a compile time constant for the boot-time page size case.

Update various BUILD_BUG_ON() instances to check against appropriate page size limit.

Re-define "union swap_header" so that it's no longer exactly page-sized. Instead define a flexible "magic" array with a define which tells the offset to where the magic signature begins.

Consider page size limit in some CPP condditionals.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/mtd/mtdswap.c         |  4 ++--
 include/linux/mm.h            |  2 +-
 include/linux/mm_types_task.h |  2 +-
 include/linux/mmzone.h        |  3 ++-
 include/linux/slab.h          |  7 ++++---
 include/linux/swap.h          | 17 ++++++++++++-----
 include/linux/swapops.h       |  6 +++++-
 mm/memcontrol.c               |  2 +-
 mm/memory.c                   |  4 ++--
 mm/mmap.c                     |  2 +-
 mm/page-writeback.c           |  2 +-
 mm/slub.c                     |  2 +-
 mm/sparse.c                   |  2 +-
 mm/swapfile.c                 |  2 +-
 mm/vmalloc.c                  |  7 ++++---
 15 files changed, 39 insertions(+), 25 deletions(-)
include/linux/swap.h +1 -4
@@ -132,10 +132,17 @@ static inline int current_is_kswapd(void)
  * bootbits...
  */
 union swap_header {
-	struct {
-		char reserved[PAGE_SIZE - 10];
-		char magic[10];			/* SWAP-SPACE or SWAPSPACE2 */
-	} magic;
+	/*

include/linux/swap.h static inline int current_is_kswapd(void) · line 145

Quoted 10 lines
include/linux/swap.h +10 -0
+	 * Exists conceptually, but since PAGE_SIZE may not be known at compile
+	 * time, we must access through pointer arithmetic at run time.
+	 *
+	 * struct {
+	 * 	char reserved[PAGE_SIZE - 10];
+	 * 	char magic[10];			   SWAP-SPACE or SWAPSPACE2
+	 * } magic;
+	 */
+#define SWAP_HEADER_MAGIC	(PAGE_SIZE - 10)
+	char magic[1];

I wonder if it makes sense to even keep this magic field anymore.

Quoted 12 lines
include/linux/swap.h +1 -1
 	struct {
 		char		bootbits[1024];	/* Space for disklabel etc. */
 		__u32		version;
@@ -201,7 +208,7 @@ struct swap_extent {
  * Max bad pages in the new format..
  */
 #define MAX_SWAP_BADPAGES \
-	((offsetof(union swap_header, magic.magic) - \
+	((SWAP_HEADER_MAGIC - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
 enum {

<snip>

mm/swapfile.c static unsigned long read_swap_header(struct swap_info_struct *p, · line 2934

Quoted 8 lines
mm/swapfile.c +1 -1
@@ -2931,7 +2931,7 @@ static unsigned long read_swap_header(struct swap_info_struct *p,
 	unsigned long swapfilepages;
 	unsigned long last_page;
 
-	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
+	if (memcmp("SWAPSPACE2", &swap_header->magic[SWAP_HEADER_MAGIC], 10)) {

I'd expect static checkers to scream here because we overflow the magic[1] both due to copying 10 bytes into 1 byte array and also with the insane offset. Hence my suggestion to drop the field and use purely pointer arithmetic.

mm/vmalloc.c

Quoted 5 lines
mm/swapfile.c +0 -0
 		pr_err("Unable to find swap-space signature\n");
 		return 0;
 	}
mm/vmalloc.c +0 -0
index a0df1e2e155a8..b4fbba204603c 100644

Hm I'm actually looking at yourwip branch which also has:

mm/huge_memory.c +1 -1
@@ -969,7 +969,7 @@ static inline int get_order_from_str(const char *size_str)
        return -EINVAL;
 }
 
-static char str_dup[PAGE_SIZE] __initdata;
+static char str_dup[PAGE_SIZE_MAX] __initdata;
 static int __init setup_thp_anon(char *str)
 {
        char *token, *range, *policy, *subtoken;

Why PAGE_SIZE_MAX? Isn't this the same case as "mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large"

author reviewer
#30 lore raw

Re: [RFC PATCH v1 06/57] mm: Remove PAGE_SIZE compile-time constant assumption

Hi Vlastimil,

Sorry about the slow response to your review of this series - I'm just getting to it now. Comment's below...

Quoted 92 lines · Vlastimil Babka
Quoted 57 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct vmap_block" to use a flexible array for used_mmap since VMAP_BBMAP_BITS is not a compile time constant for the boot-time page size case.

Update various BUILD_BUG_ON() instances to check against appropriate page size limit.

Re-define "union swap_header" so that it's no longer exactly page-sized. Instead define a flexible "magic" array with a define which tells the offset to where the magic signature begins.

Consider page size limit in some CPP condditionals.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/mtd/mtdswap.c         |  4 ++--
 include/linux/mm.h            |  2 +-
 include/linux/mm_types_task.h |  2 +-
 include/linux/mmzone.h        |  3 ++-
 include/linux/slab.h          |  7 ++++---
 include/linux/swap.h          | 17 ++++++++++++-----
 include/linux/swapops.h       |  6 +++++-
 mm/memcontrol.c               |  2 +-
 mm/memory.c                   |  4 ++--
 mm/mmap.c                     |  2 +-
 mm/page-writeback.c           |  2 +-
 mm/slub.c                     |  2 +-
 mm/sparse.c                   |  2 +-
 mm/swapfile.c                 |  2 +-
 mm/vmalloc.c                  |  7 ++++---
 15 files changed, 39 insertions(+), 25 deletions(-)
include/linux/swap.h +1 -4
@@ -132,10 +132,17 @@ static inline int current_is_kswapd(void)
  * bootbits...
  */
 union swap_header {
-	struct {
-		char reserved[PAGE_SIZE - 10];
-		char magic[10];			/* SWAP-SPACE or SWAPSPACE2 */
-	} magic;
+	/*

include/linux/swap.h static inline int current_is_kswapd(void) · line 145

Quoted 10 lines
include/linux/swap.h +10 -0
+	 * Exists conceptually, but since PAGE_SIZE may not be known at compile
+	 * time, we must access through pointer arithmetic at run time.
+	 *
+	 * struct {
+	 * 	char reserved[PAGE_SIZE - 10];
+	 * 	char magic[10];			   SWAP-SPACE or SWAPSPACE2
+	 * } magic;
+	 */
+#define SWAP_HEADER_MAGIC	(PAGE_SIZE - 10)
+	char magic[1];

I wonder if it makes sense to even keep this magic field anymore.

Quoted 12 lines
include/linux/swap.h +1 -1
 	struct {
 		char		bootbits[1024];	/* Space for disklabel etc. */
 		__u32		version;
@@ -201,7 +208,7 @@ struct swap_extent {
  * Max bad pages in the new format..
  */
 #define MAX_SWAP_BADPAGES \
-	((offsetof(union swap_header, magic.magic) - \
+	((SWAP_HEADER_MAGIC - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
 enum {

<snip>

Quoted 6 lines
mm/swapfile.c +0 -0
@@ -2931,7 +2931,7 @@ static unsigned long read_swap_header(struct swap_info_struct *p,
 	unsigned long swapfilepages;
 	unsigned long last_page;
 
Quoted 6 lines

mm/swapfile.c static unsigned long read_swap_header(struct swap_info_struct *p, · line 2934

Quoted 2 lines
mm/swapfile.c +1 -1
-	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
+	if (memcmp("SWAPSPACE2", &swap_header->magic[SWAP_HEADER_MAGIC], 10)) {

I'd expect static checkers to scream here because we overflow the magic[1] both due to copying 10 bytes into 1 byte array and also with the insane offset. Hence my suggestion to drop the field and use purely pointer arithmetic.

Yeah, good point. I'll remove magic[] and use pointer arithmetic.

Quoted 21 lines

mm/vmalloc.c

Quoted 6 lines
mm/swapfile.c +0 -0
 		pr_err("Unable to find swap-space signature\n");
 		return 0;
 	}
mm/vmalloc.c +0 -0
index a0df1e2e155a8..b4fbba204603c 100644

Hm I'm actually looking at yourwip branch which also has:

mm/huge_memory.c +1 -1
@@ -969,7 +969,7 @@ static inline int get_order_from_str(const char *size_str)
        return -EINVAL;
 }
 
-static char str_dup[PAGE_SIZE] __initdata;
+static char str_dup[PAGE_SIZE_MAX] __initdata;
 static int __init setup_thp_anon(char *str)
 {
        char *token, *range, *policy, *subtoken;
Quoted 2 lines

Why PAGE_SIZE_MAX? Isn't this the same case as "mm/memcontrol: Fix seq_buf size to save memory when PAGE_SIZE is large"

Hmm, you're probably right. I had a vague notion that "str", as passed into the function, was guarranteed to be no bigger than PAGE_SIZE (perhaps I'm wrong). So assumed that's where the original definition of str_dup[PAGE_SIZE] was coming from.

But I think your real question is "should the max size of str be a function of PAGE_SIZE?". I think it could; there are more page orders that can legitimately be described when the page size is bigger (at least for arm64). But in practice, I'd expect any sane string for any page size to be easily within 4K.

So on that basis, I'll take your advice; changing this buffer to be 4K always.

Thanks,
Ryan

author reviewer
#31 lore raw

RFC PATCH 7/57 fs: Introduce MAX_BUF_PER_PAGE_SIZE_MAX for array sizing

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Code that previously defined arrays with MAX_BUF_PER_PAGE will no longer work with boot-time page selection because PAGE_SIZE is not known at compile-time. Introduce MAX_BUF_PER_PAGE_SIZE_MAX for this purpose, which is the requirement in the limit when PAGE_SIZE_MAX is the selected page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 fs/buffer.c                 | 2 +-
 fs/ext4/move_extent.c       | 2 +-
 fs/ext4/readpage.c          | 2 +-
 fs/fat/dir.c                | 4 ++--
 fs/fat/fatent.c             | 4 ++--
 include/linux/buffer_head.h | 1 +
 6 files changed, 8 insertions(+), 7 deletions(-)
fs/buffer.c +1 -1
index e55ad471c5306..f00542ad43a5c 100644
@@ -2371,7 +2371,7 @@ int block_read_full_folio(struct folio *folio, get_block_t *get_block)
 {
 	struct inode *inode = folio->mapping->host;
 	sector_t iblock, lblock;
-	struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
+	struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE_SIZE_MAX];
 	size_t blocksize;
 	int nr, i;
 	int fully_mapped = 1;
fs/ext4/move_extent.c +1 -1
index 204f53b236229..68304426c6f45 100644
@@ -172,7 +172,7 @@ mext_page_mkuptodate(struct folio *folio, unsigned from, unsigned to)
 {
 	struct inode *inode = folio->mapping->host;
 	sector_t block;
-	struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
+	struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE_SIZE_MAX];
 	unsigned int blocksize, block_start, block_end;
 	int i, err,  nr = 0, partial = 0;
 	BUG_ON(!folio_test_locked(folio));
fs/ext4/readpage.c +1 -1
index 8494492582abe..5808d85096aeb 100644
@@ -221,7 +221,7 @@ int ext4_mpage_readpages(struct inode *inode,
 	sector_t block_in_file;
 	sector_t last_block;
 	sector_t last_block_in_file;
-	sector_t blocks[MAX_BUF_PER_PAGE];
+	sector_t blocks[MAX_BUF_PER_PAGE_SIZE_MAX];
 	unsigned page_block;
 	struct block_device *bdev = inode->i_sb->s_bdev;
 	int length;
fs/fat/dir.c +2 -2
index acbec5bdd5210..f3e96ecf21c92 100644
@@ -1146,7 +1146,7 @@ int fat_alloc_new_dir(struct inode *dir, struct timespec64 *ts)
 {
 	struct super_block *sb = dir->i_sb;
 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
-	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
+	struct buffer_head *bhs[MAX_BUF_PER_PAGE_SIZE_MAX];
 	struct msdos_dir_entry *de;
 	sector_t blknr;
 	__le16 date, time;
@@ -1213,7 +1213,7 @@ static int fat_add_new_entries(struct inode *dir, void *slots, int nr_slots,
 {
 	struct super_block *sb = dir->i_sb;
 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
-	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
+	struct buffer_head *bhs[MAX_BUF_PER_PAGE_SIZE_MAX];
 	sector_t blknr, start_blknr, last_blknr;
 	unsigned long size, copy;
 	int err, i, n, offset, cluster[2];
fs/fat/fatent.c +2 -2
index 1db348f8f887a..322cf5b8e5590 100644
@@ -469,7 +469,7 @@ int fat_alloc_clusters(struct inode *inode, int *cluster, int nr_cluster)
 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
 	const struct fatent_operations *ops = sbi->fatent_ops;
 	struct fat_entry fatent, prev_ent;
-	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
+	struct buffer_head *bhs[MAX_BUF_PER_PAGE_SIZE_MAX];
 	int i, count, err, nr_bhs, idx_clus;
 
 	BUG_ON(nr_cluster > (MAX_BUF_PER_PAGE / 2));	/* fixed limit */
@@ -557,7 +557,7 @@ int fat_free_clusters(struct inode *inode, int cluster)
 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
 	const struct fatent_operations *ops = sbi->fatent_ops;
 	struct fat_entry fatent;
-	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
+	struct buffer_head *bhs[MAX_BUF_PER_PAGE_SIZE_MAX];
 	int i, err, nr_bhs;
 	int first_cl = cluster, dirty_fsinfo = 0;
 
include/linux/buffer_head.h +1 -0
index 14acf1bbe0ce6..5dff4837b76cd 100644
@@ -41,6 +41,7 @@ enum bh_state_bits {
 };
 
 #define MAX_BUF_PER_PAGE (PAGE_SIZE / 512)
+#define MAX_BUF_PER_PAGE_SIZE_MAX (PAGE_SIZE_MAX / 512)
 
 struct page;
 struct buffer_head;
Signature · 1 line
2.43.0
author reviewer
#32 lore raw

RFC PATCH 8/57 fs: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

In binfmt_elf, convert CPP conditional to C ternary operator; this will be folded to the same code by the compiler when in compile-time page size mode, but will also work for runtime evaluation in boot-time page size mode.

In coredump, modify __dump_skip() to emit zeros in blocks of PAGE_SIZE_MIN. This resolves to the previous PAGE_SIZE for compile-time page size, but that doesn't work for boot-time page size. PAGE_SIZE_MIN is preferred here over PAGE_SIZE_MAX to save memory.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 fs/binfmt_elf.c | 11 ++++-------
 fs/coredump.c   |  8 ++++----
 2 files changed, 8 insertions(+), 11 deletions(-)
fs/binfmt_elf.c +4 -7
index 19fa49cd9907f..e439d36c43c7e 100644
@@ -84,11 +84,8 @@ static int elf_core_dump(struct coredump_params *cprm);
 #define elf_core_dump	NULL
 #endif
 
-#if ELF_EXEC_PAGESIZE > PAGE_SIZE
-#define ELF_MIN_ALIGN	ELF_EXEC_PAGESIZE
-#else
-#define ELF_MIN_ALIGN	PAGE_SIZE
-#endif
+#define ELF_MIN_ALIGN							\
+	(ELF_EXEC_PAGESIZE > PAGE_SIZE ? ELF_EXEC_PAGESIZE : PAGE_SIZE)
 
 #ifndef ELF_CORE_EFLAGS
 #define ELF_CORE_EFLAGS	0
@@ -98,7 +95,7 @@ static int elf_core_dump(struct coredump_params *cprm);
 #define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1))
 #define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1))
 
-static struct linux_binfmt elf_format = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(struct linux_binfmt, elf_format, {
 	.module		= THIS_MODULE,
 	.load_binary	= load_elf_binary,
 	.load_shlib	= load_elf_library,
@@ -106,7 +103,7 @@ static struct linux_binfmt elf_format = {
 	.core_dump	= elf_core_dump,
 	.min_coredump	= ELF_EXEC_PAGESIZE,
 #endif
-};
+});
 
 #define BAD_ADDR(x) (unlikely((unsigned long)(x) >= TASK_SIZE))
 
fs/coredump.c +4 -4
index 7f12ff6ad1d3e..203f2a158246e 100644
@@ -825,7 +825,7 @@ static int __dump_emit(struct coredump_params *cprm, const void *addr, int nr)
 
 static int __dump_skip(struct coredump_params *cprm, size_t nr)
 {
-	static char zeroes[PAGE_SIZE];
+	static char zeroes[PAGE_SIZE_MIN];
 	struct file *file = cprm->file;
 	if (file->f_mode & FMODE_LSEEK) {
 		if (dump_interrupted() ||
@@ -834,10 +834,10 @@ static int __dump_skip(struct coredump_params *cprm, size_t nr)
 		cprm->pos += nr;
 		return 1;
 	} else {
-		while (nr > PAGE_SIZE) {
-			if (!__dump_emit(cprm, zeroes, PAGE_SIZE))
+		while (nr > PAGE_SIZE_MIN) {
+			if (!__dump_emit(cprm, zeroes, PAGE_SIZE_MIN))
 				return 0;
-			nr -= PAGE_SIZE;
+			nr -= PAGE_SIZE_MIN;
 		}
 		return __dump_emit(cprm, zeroes, nr);
 	}
Signature · 1 line
2.43.0
author reviewer
#33 lore raw

RFC PATCH 9/57 fs/nfs: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Calculation of NFS4ACL_MAXPAGES and NFS4XATTR_MAXPAGES are modified to give max pages when page size is at the minimum.

BUILD_BUG_ON() is modified to test against the min page size, which implicitly also applies to all other page sizes.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 fs/nfs/nfs42proc.c  | 2 +-
 fs/nfs/nfs42xattr.c | 2 +-
 fs/nfs/nfs4proc.c   | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
fs/nfs/nfs42proc.c +1 -1
index 28704f924612c..c600574105c63 100644
@@ -1161,7 +1161,7 @@ int nfs42_proc_clone(struct file *src_f, struct file *dst_f,
 	return err;
 }
 
-#define NFS4XATTR_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE)
+#define NFS4XATTR_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE_MIN)
 
 static int _nfs42_proc_removexattr(struct inode *inode, const char *name)
 {
fs/nfs/nfs42xattr.c +1 -1
index b6e3d8f77b910..734177eb44889 100644
@@ -183,7 +183,7 @@ nfs4_xattr_alloc_entry(const char *name, const void *value,
 	uint32_t flags;
 
 	BUILD_BUG_ON(sizeof(struct nfs4_xattr_entry) +
-	    XATTR_NAME_MAX + 1 > PAGE_SIZE);
+	    XATTR_NAME_MAX + 1 > PAGE_SIZE_MIN);
 
 	alloclen = sizeof(struct nfs4_xattr_entry);
 	if (name != NULL) {
fs/nfs/nfs4proc.c +1 -1
index b8ffbe52ba15a..3c3622f46d3e0 100644
@@ -5928,7 +5928,7 @@ static bool nfs4_server_supports_acls(const struct nfs_server *server,
  * it's OK to put sizeof(void) * (XATTR_SIZE_MAX/PAGE_SIZE) bytes on
  * the stack.
  */
-#define NFS4ACL_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE)
+#define NFS4ACL_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE_MIN)
 
 int nfs4_buf_to_pages_noslab(const void *buf, size_t buflen,
 		struct page **pages)
Signature · 1 line
2.43.0
author reviewer
#34 lore raw

RFC PATCH 10/57 fs/ext4: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP PAGE_SIZE conditionals to C if/else. For compile-time page size, the compiler will strip the dead part, and for boot-time page size, the condition will be evaluated at run time.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 fs/ext4/ext4.h | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)
fs/ext4/ext4.h +18 -18
index 08acd152261ed..1a6dbd925024a 100644
@@ -2415,31 +2415,31 @@ ext4_rec_len_from_disk(__le16 dlen, unsigned blocksize)
 {
 	unsigned len = le16_to_cpu(dlen);
 
-#if (PAGE_SIZE >= 65536)
-	if (len == EXT4_MAX_REC_LEN || len == 0)
-		return blocksize;
-	return (len & 65532) | ((len & 3) << 16);
-#else
-	return len;
-#endif
+	if (PAGE_SIZE >= 65536) {
+		if (len == EXT4_MAX_REC_LEN || len == 0)
+			return blocksize;
+		return (len & 65532) | ((len & 3) << 16);
+	} else {
+		return len;
+	}
 }
 
 static inline __le16 ext4_rec_len_to_disk(unsigned len, unsigned blocksize)
 {
 	BUG_ON((len > blocksize) || (blocksize > (1 << 18)) || (len & 3));
-#if (PAGE_SIZE >= 65536)
-	if (len < 65536)
+	if (PAGE_SIZE >= 65536) {
+		if (len < 65536)
+			return cpu_to_le16(len);
+		if (len == blocksize) {
+			if (blocksize == 65536)
+				return cpu_to_le16(EXT4_MAX_REC_LEN);
+			else
+				return cpu_to_le16(0);
+		}
+		return cpu_to_le16((len & 65532) | ((len >> 16) & 3));
+	} else {
 		return cpu_to_le16(len);
-	if (len == blocksize) {
-		if (blocksize == 65536)
-			return cpu_to_le16(EXT4_MAX_REC_LEN);
-		else
-			return cpu_to_le16(0);
 	}
-	return cpu_to_le16((len & 65532) | ((len >> 16) & 3));
-#else
-	return cpu_to_le16(len);
-#endif
 }
 
 /*
Signature · 1 line
2.43.0
author reviewer
#35 lore raw

RFC PATCH 11/57 fork: Permit boot-time THREAD_SIZE determination

In reply to Ryan Roberts

THREAD_SIZE defines the size of a kernel thread stack. To date, it has been set at compile-time. However, when using vmap stacks, the size must be a multiple of PAGE_SIZE, and given we are in the process of supporting boot-time page size, we must also do the same for THREAD_SIZE.

The alternative would be to define THREAD_SIZE for the largest supported page size, but this would waste memory when using a smaller page size. For example, arm64 requires THREAD_SIZE to be 16K, but when using 64K pages and a vmap stack, we must increase the size to 64K. If we required 64K when 4K or 16K page size was in use, we would waste 48K per kernel thread.

So let's refactor to allow THREAD_SIZE to not be a compile-time constant. THREAD_SIZE_MAX (and THREAD_ALIGN_MAX) are introduced to manage the limits, as is done for PAGE_SIZE.

When THREAD_SIZE is a compile-time constant, behaviour and code size should be equivalent.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/asm-generic/vmlinux.lds.h |  6 ++-
 include/linux/sched.h             |  4 +-
 include/linux/thread_info.h       | 10 ++++-
 init/main.c                       |  2 +-
 kernel/fork.c                     | 67 +++++++++++--------------------
 mm/kasan/report.c                 |  3 +-
 6 files changed, 42 insertions(+), 50 deletions(-)
include/asm-generic/vmlinux.lds.h +5 -1
index 5727f883001bb..f19bab7a2e8f9 100644
@@ -56,6 +56,10 @@
 #define LOAD_OFFSET 0
 #endif
 
+#ifndef THREAD_SIZE_MAX
+#define THREAD_SIZE_MAX		THREAD_SIZE
+#endif
+
 /*
  * Only some architectures want to have the .notes segment visible in
  * a separate PT_NOTE ELF Program Header. When this happens, it needs
@@ -398,7 +402,7 @@
 	init_stack = .;							\
 	KEEP(*(.data..init_task))					\
 	KEEP(*(.data..init_thread_info))				\
-	. = __start_init_stack + THREAD_SIZE;				\
+	. = __start_init_stack + THREAD_SIZE_MAX;			\
 	__end_init_stack = .;
 
 #define JUMP_TABLE_DATA							\
include/linux/sched.h +2 -2
index f8d150343d42d..3de4f655ee492 100644
@@ -1863,14 +1863,14 @@ union thread_union {
 #ifndef CONFIG_THREAD_INFO_IN_TASK
 	struct thread_info thread_info;
 #endif
-	unsigned long stack[THREAD_SIZE/sizeof(long)];
+	unsigned long stack[THREAD_SIZE_MAX/sizeof(long)];
 };
 
 #ifndef CONFIG_THREAD_INFO_IN_TASK
 extern struct thread_info init_thread_info;
 #endif
 
-extern unsigned long init_stack[THREAD_SIZE / sizeof(unsigned long)];
+extern unsigned long init_stack[THREAD_SIZE_MAX / sizeof(unsigned long)];
 
 #ifdef CONFIG_THREAD_INFO_IN_TASK
 # define task_thread_info(task)	(&(task)->thread_info)
include/linux/thread_info.h +9 -1
index 9ea0b28068f49..a7ccc448cd298 100644
@@ -74,7 +74,15 @@ static inline long set_restart_fn(struct restart_block *restart,
 }
 
 #ifndef THREAD_ALIGN
-#define THREAD_ALIGN	THREAD_SIZE
+#define THREAD_ALIGN		THREAD_SIZE
+#endif
+
+#ifndef THREAD_SIZE_MAX
+#define THREAD_SIZE_MAX		THREAD_SIZE
+#endif
+
+#ifndef THREAD_ALIGN_MAX
+#define THREAD_ALIGN_MAX	max(THREAD_ALIGN, THREAD_SIZE_MAX)
 #endif
 
 #define THREADINFO_GFP		(GFP_KERNEL_ACCOUNT | __GFP_ZERO)
init/main.c +1 -1
index ba1515eb20b9d..4dc28115fdf57 100644
@@ -797,7 +797,7 @@ void __init __weak smp_prepare_boot_cpu(void)
 {
 }
 
-# if THREAD_SIZE >= PAGE_SIZE
+#ifdef CONFIG_VMAP_STACK
 void __init __weak thread_stack_cache_init(void)
 {
 }
kernel/fork.c +24 -43

103 lines not on this page · raw message

mm/kasan/report.c +1 -2
index b48c768acc84d..57c877852dbc6 100644
@@ -365,8 +365,7 @@ static inline bool kernel_or_module_addr(const void *addr)
 static inline bool init_task_stack_addr(const void *addr)
 {
 	return addr >= (void *)&init_thread_union.stack &&
-		(addr <= (void *)&init_thread_union.stack +
-			sizeof(init_thread_union.stack));
+		(addr <= (void *)&init_thread_union.stack + THREAD_SIZE);
 }
 
 static void print_address_description(void *addr, u8 tag,
Signature · 1 line
2.43.0
Acked-by on v1 11/57
#36 lore raw

Re: [RFC PATCH v1 11/57] fork: Permit boot-time THREAD_SIZE determination

Quoted 13 lines · Ryan Roberts

THREAD_SIZE defines the size of a kernel thread stack. To date, it has been set at compile-time. However, when using vmap stacks, the size must be a multiple of PAGE_SIZE, and given we are in the process of supporting boot-time page size, we must also do the same for THREAD_SIZE.

The alternative would be to define THREAD_SIZE for the largest supported page size, but this would waste memory when using a smaller page size. For example, arm64 requires THREAD_SIZE to be 16K, but when using 64K pages and a vmap stack, we must increase the size to 64K. If we required 64K when 4K or 16K page size was in use, we would waste 48K per kernel thread.

Quoted 8 lines

So let's refactor to allow THREAD_SIZE to not be a compile-time constant. THREAD_SIZE_MAX (and THREAD_ALIGN_MAX) are introduced to manage the limits, as is done for PAGE_SIZE.

When THREAD_SIZE is a compile-time constant, behaviour and code size should be equivalent.

author reviewer
#37 lore raw

RFC PATCH 12/57 cgroup: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/cgroup/cgroup.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
kernel/cgroup/cgroup.c +4 -4
index c8e4b62b436a4..1e9c96210821d 100644
@@ -4176,16 +4176,16 @@ static int cgroup_seqfile_show(struct seq_file *m, void *arg)
 	return 0;
 }
 
-static struct kernfs_ops cgroup_kf_single_ops = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(struct kernfs_ops, cgroup_kf_single_ops, {
 	.atomic_write_len	= PAGE_SIZE,
 	.open			= cgroup_file_open,
 	.release		= cgroup_file_release,
 	.write			= cgroup_file_write,
 	.poll			= cgroup_file_poll,
 	.seq_show		= cgroup_seqfile_show,
-};
+});
 
-static struct kernfs_ops cgroup_kf_ops = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(struct kernfs_ops, cgroup_kf_ops, {
 	.atomic_write_len	= PAGE_SIZE,
 	.open			= cgroup_file_open,
 	.release		= cgroup_file_release,
@@ -4195,7 +4195,7 @@ static struct kernfs_ops cgroup_kf_ops = {
 	.seq_next		= cgroup_seqfile_next,
 	.seq_stop		= cgroup_seqfile_stop,
 	.seq_show		= cgroup_seqfile_show,
-};
+});
 
 static void cgroup_file_notify_timer(struct timer_list *timer)
 {
Signature · 1 line
2.43.0
author reviewer
#38 lore raw

RFC PATCH 13/57 bpf: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct bpf_ringbuf" so that consumer_pos, producer_pos, pending_pos and data are no longer embedded at (static) page offsets within the struct. This can't work for boot-time page size because the page size isn't known at compile-time. Instead, only define the meta data in the struct, along with pointers to those values. At "struct bpf_ringbuf" allocation time, the extra pages are allocated at the end and the pointers are initialized to point to the correct locations.

Additionally, only expose the __PAGE_SIZE enum to BTF for compile-time page size builds. We don't know the page size at compile-time for boot-time builds. NOTE: This may need some extra thought; perhaps __PAGE_SIZE should be exposed as 0 in this case? And/or perhaps __PAGE_SIZE_MIN/__PAGE_SIZE_MAX should be exposed? And there would need to be a runtime mechanism for querying the page size (e.g. getpagesize()).

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/bpf/core.c    |  9 ++++++--
 kernel/bpf/ringbuf.c | 54 ++++++++++++++++++++++++--------------------
 2 files changed, 37 insertions(+), 26 deletions(-)
kernel/bpf/core.c +7 -2
index 7ee62e38faf0e..485875aa78e63 100644
@@ -89,10 +89,15 @@ void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, uns
 	return NULL;
 }
 
-/* tell bpf programs that include vmlinux.h kernel's PAGE_SIZE */
+/*
+ * tell bpf programs that include vmlinux.h kernel's PAGE_SIZE. We can only do
+ * this for compile-time PAGE_SIZE builds.
+ */
+#if PAGE_SIZE_MIN == PAGE_SIZE_MAX
 enum page_size_enum {
 	__PAGE_SIZE = PAGE_SIZE
 };
+#endif
 
 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
 {
@@ -100,7 +105,7 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	struct bpf_prog_aux *aux;
 	struct bpf_prog *fp;
 
-	size = round_up(size, __PAGE_SIZE);
+	size = round_up(size, PAGE_SIZE);
 	fp = __vmalloc(size, gfp_flags);
 	if (fp == NULL)
 		return NULL;
kernel/bpf/ringbuf.c +30 -24

148 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#39 lore raw

Re: [RFC PATCH v1 13/57] bpf: Remove PAGE_SIZE compile-time constant assumption

+ Andrii Nakryiko

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 227 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor "struct bpf_ringbuf" so that consumer_pos, producer_pos, pending_pos and data are no longer embedded at (static) page offsets within the struct. This can't work for boot-time page size because the page size isn't known at compile-time. Instead, only define the meta data in the struct, along with pointers to those values. At "struct bpf_ringbuf" allocation time, the extra pages are allocated at the end and the pointers are initialized to point to the correct locations.

Additionally, only expose the __PAGE_SIZE enum to BTF for compile-time page size builds. We don't know the page size at compile-time for boot-time builds. NOTE: This may need some extra thought; perhaps __PAGE_SIZE should be exposed as 0 in this case? And/or perhaps __PAGE_SIZE_MIN/__PAGE_SIZE_MAX should be exposed? And there would need to be a runtime mechanism for querying the page size (e.g. getpagesize()).

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/bpf/core.c    |  9 ++++++--
 kernel/bpf/ringbuf.c | 54 ++++++++++++++++++++++++--------------------
 2 files changed, 37 insertions(+), 26 deletions(-)
kernel/bpf/core.c +7 -2
index 7ee62e38faf0e..485875aa78e63 100644
@@ -89,10 +89,15 @@ void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, uns
 	return NULL;
 }
 
-/* tell bpf programs that include vmlinux.h kernel's PAGE_SIZE */
+/*
+ * tell bpf programs that include vmlinux.h kernel's PAGE_SIZE. We can only do
+ * this for compile-time PAGE_SIZE builds.
+ */
+#if PAGE_SIZE_MIN == PAGE_SIZE_MAX
 enum page_size_enum {
 	__PAGE_SIZE = PAGE_SIZE
 };
+#endif
 
 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
 {
@@ -100,7 +105,7 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	struct bpf_prog_aux *aux;
 	struct bpf_prog *fp;
 
-	size = round_up(size, __PAGE_SIZE);
+	size = round_up(size, PAGE_SIZE);
 	fp = __vmalloc(size, gfp_flags);
 	if (fp == NULL)
 		return NULL;
kernel/bpf/ringbuf.c +30 -24
index e20b90c361316..8e4093ddbc638 100644
@@ -14,9 +14,9 @@
 
 #define RINGBUF_CREATE_FLAG_MASK (BPF_F_NUMA_NODE)
 
-/* non-mmap()'able part of bpf_ringbuf (everything up to consumer page) */
+/* non-mmap()'able part of bpf_ringbuf (everything defined in struct) */
 #define RINGBUF_PGOFF \
-	(offsetof(struct bpf_ringbuf, consumer_pos) >> PAGE_SHIFT)
+	(PAGE_ALIGN(sizeof(struct bpf_ringbuf)) >> PAGE_SHIFT)
 /* consumer page and producer page */
 #define RINGBUF_POS_PAGES 2
 #define RINGBUF_NR_META_PAGES (RINGBUF_PGOFF + RINGBUF_POS_PAGES)
@@ -69,10 +69,10 @@ struct bpf_ringbuf {
 	 * validate each sample to ensure that they're correctly formatted, and
 	 * fully contained within the ring buffer.
 	 */
-	unsigned long consumer_pos __aligned(PAGE_SIZE);
-	unsigned long producer_pos __aligned(PAGE_SIZE);
-	unsigned long pending_pos;
-	char data[] __aligned(PAGE_SIZE);
+	unsigned long *consumer_pos;
+	unsigned long *producer_pos;
+	unsigned long *pending_pos;
+	char *data;
 };
 
 struct bpf_ringbuf_map {
@@ -134,9 +134,15 @@ static struct bpf_ringbuf *bpf_ringbuf_area_alloc(size_t data_sz, int numa_node)
 	rb = vmap(pages, nr_meta_pages + 2 * nr_data_pages,
 		  VM_MAP | VM_USERMAP, PAGE_KERNEL);
 	if (rb) {
+		void *base = rb;
+
 		kmemleak_not_leak(pages);
 		rb->pages = pages;
 		rb->nr_pages = nr_pages;
+		rb->consumer_pos = (unsigned long *)(base + PAGE_SIZE * RINGBUF_PGOFF);
+		rb->producer_pos = (unsigned long *)(base + PAGE_SIZE * (RINGBUF_PGOFF + 1));
+		rb->pending_pos = rb->producer_pos + 1;
+		rb->data = base + PAGE_SIZE * nr_meta_pages;
 		return rb;
 	}
 
@@ -179,9 +185,9 @@ static struct bpf_ringbuf *bpf_ringbuf_alloc(size_t data_sz, int numa_node)
 	init_irq_work(&rb->work, bpf_ringbuf_notify);
 
 	rb->mask = data_sz - 1;
-	rb->consumer_pos = 0;
-	rb->producer_pos = 0;
-	rb->pending_pos = 0;
+	*rb->consumer_pos = 0;
+	*rb->producer_pos = 0;
+	*rb->pending_pos = 0;
 
 	return rb;
 }
@@ -300,8 +306,8 @@ static unsigned long ringbuf_avail_data_sz(struct bpf_ringbuf *rb)
 {
 	unsigned long cons_pos, prod_pos;
 
-	cons_pos = smp_load_acquire(&rb->consumer_pos);
-	prod_pos = smp_load_acquire(&rb->producer_pos);
+	cons_pos = smp_load_acquire(rb->consumer_pos);
+	prod_pos = smp_load_acquire(rb->producer_pos);
 	return prod_pos - cons_pos;
 }
 
@@ -418,7 +424,7 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
 	if (len > ringbuf_total_data_sz(rb))
 		return NULL;
 
-	cons_pos = smp_load_acquire(&rb->consumer_pos);
+	cons_pos = smp_load_acquire(rb->consumer_pos);
 
 	if (in_nmi()) {
 		if (!spin_trylock_irqsave(&rb->spinlock, flags))
@@ -427,8 +433,8 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
 		spin_lock_irqsave(&rb->spinlock, flags);
 	}
 
-	pend_pos = rb->pending_pos;
-	prod_pos = rb->producer_pos;
+	pend_pos = *rb->pending_pos;
+	prod_pos = *rb->producer_pos;
 	new_prod_pos = prod_pos + len;
 
 	while (pend_pos < prod_pos) {
@@ -440,7 +446,7 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
 		tmp_size = round_up(tmp_size + BPF_RINGBUF_HDR_SZ, 8);
 		pend_pos += tmp_size;
 	}
-	rb->pending_pos = pend_pos;
+	*rb->pending_pos = pend_pos;
 
 	/* check for out of ringbuf space:
 	 * - by ensuring producer position doesn't advance more than
@@ -460,7 +466,7 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
 	hdr->pg_off = pg_off;
 
 	/* pairs with consumer's smp_load_acquire() */
-	smp_store_release(&rb->producer_pos, new_prod_pos);
+	smp_store_release(rb->producer_pos, new_prod_pos);
 
 	spin_unlock_irqrestore(&rb->spinlock, flags);
 
@@ -506,7 +512,7 @@ static void bpf_ringbuf_commit(void *sample, u64 flags, bool discard)
 	 * new data availability
 	 */
 	rec_pos = (void *)hdr - (void *)rb->data;
-	cons_pos = smp_load_acquire(&rb->consumer_pos) & rb->mask;
+	cons_pos = smp_load_acquire(rb->consumer_pos) & rb->mask;
 
 	if (flags & BPF_RB_FORCE_WAKEUP)
 		irq_work_queue(&rb->work);
@@ -580,9 +586,9 @@ BPF_CALL_2(bpf_ringbuf_query, struct bpf_map *, map, u64, flags)
 	case BPF_RB_RING_SIZE:
 		return ringbuf_total_data_sz(rb);
 	case BPF_RB_CONS_POS:
-		return smp_load_acquire(&rb->consumer_pos);
+		return smp_load_acquire(rb->consumer_pos);
 	case BPF_RB_PROD_POS:
-		return smp_load_acquire(&rb->producer_pos);
+		return smp_load_acquire(rb->producer_pos);
 	default:
 		return 0;
 	}
@@ -680,12 +686,12 @@ static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *s
 	u64 cons_pos, prod_pos;
 
 	/* Synchronizes with smp_store_release() in user-space producer. */
-	prod_pos = smp_load_acquire(&rb->producer_pos);
+	prod_pos = smp_load_acquire(rb->producer_pos);
 	if (prod_pos % 8)
 		return -EINVAL;
 
 	/* Synchronizes with smp_store_release() in __bpf_user_ringbuf_sample_release() */
-	cons_pos = smp_load_acquire(&rb->consumer_pos);
+	cons_pos = smp_load_acquire(rb->consumer_pos);
 	if (cons_pos >= prod_pos)
 		return -ENODATA;
 
@@ -715,7 +721,7 @@ static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *s
 		 * Update the consumer pos, and return -EAGAIN so the caller
 		 * knows to skip this sample and try to read the next one.
 		 */
-		smp_store_release(&rb->consumer_pos, cons_pos + total_len);
+		smp_store_release(rb->consumer_pos, cons_pos + total_len);
 		return -EAGAIN;
 	}
 
@@ -737,9 +743,9 @@ static void __bpf_user_ringbuf_sample_release(struct bpf_ringbuf *rb, size_t siz
 	 * prevents another task from writing to consumer_pos after it was read
 	 * by this task with smp_load_acquire() in __bpf_user_ringbuf_peek().
 	 */
-	consumer_pos = rb->consumer_pos;
+	consumer_pos = *rb->consumer_pos;
 	 /* Synchronizes with smp_load_acquire() in user-space producer. */
-	smp_store_release(&rb->consumer_pos, consumer_pos + rounded_size);
+	smp_store_release(rb->consumer_pos, consumer_pos + rounded_size);
 }
 
 BPF_CALL_4(bpf_user_ringbuf_drain, struct bpf_map *, map,
author reviewer
#40 lore raw

RFC PATCH 14/57 pm/hibernate: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

"struct linked_page", "struct swap_map_page" and "struct swsusp_header" were all previously sized to be exactly PAGE_SIZE. Refactor those structures to remove the padding, then superimpose them on a page at runtime.

"struct cmp_data" and "struct dec_data" previously contained embedded "unc" and "cmp" arrays, who's sizes were derived from PAGE_SIZE. We can't use flexible array approach here since there are 2 arrays in the structure, so convert to pointers and define an allocator and deallocator for each struct.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/power/power.h    |   2 +-
 kernel/power/snapshot.c |   2 +-
 kernel/power/swap.c     | 129 +++++++++++++++++++++++++++++++++-------
 3 files changed, 108 insertions(+), 25 deletions(-)
kernel/power/power.h +1 -1
index de0e6b1077f23..74af2eb8d48a4 100644
@@ -16,7 +16,7 @@ struct swsusp_info {
 	unsigned long		image_pages;
 	unsigned long		pages;
 	unsigned long		size;
-} __aligned(PAGE_SIZE);
+} __aligned(PAGE_SIZE_MAX);
 
 #ifdef CONFIG_HIBERNATION
 /* kernel/power/snapshot.c */
kernel/power/snapshot.c +1 -1
index 405eddbda4fc5..144e92f786e35 100644
@@ -155,7 +155,7 @@ struct pbe *restore_pblist;
 
 struct linked_page {
 	struct linked_page *next;
-	char data[LINKED_PAGE_DATA_SIZE];
+	char data[];
 } __packed;
 
 /*
kernel/power/swap.c +106 -23

255 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#41 lore raw

Re: [RFC PATCH v1 14/57] pm/hibernate: Remove PAGE_SIZE compile-time constant assumption

+ Rafael J. Wysocki, Len Brown, Pavel Machek

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 332 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

"struct linked_page", "struct swap_map_page" and "struct swsusp_header" were all previously sized to be exactly PAGE_SIZE. Refactor those structures to remove the padding, then superimpose them on a page at runtime.

"struct cmp_data" and "struct dec_data" previously contained embedded "unc" and "cmp" arrays, who's sizes were derived from PAGE_SIZE. We can't use flexible array approach here since there are 2 arrays in the structure, so convert to pointers and define an allocator and deallocator for each struct.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/power/power.h    |   2 +-
 kernel/power/snapshot.c |   2 +-
 kernel/power/swap.c     | 129 +++++++++++++++++++++++++++++++++-------
 3 files changed, 108 insertions(+), 25 deletions(-)
kernel/power/power.h +1 -1
index de0e6b1077f23..74af2eb8d48a4 100644
@@ -16,7 +16,7 @@ struct swsusp_info {
 	unsigned long		image_pages;
 	unsigned long		pages;
 	unsigned long		size;
-} __aligned(PAGE_SIZE);
+} __aligned(PAGE_SIZE_MAX);
 
 #ifdef CONFIG_HIBERNATION
 /* kernel/power/snapshot.c */
kernel/power/snapshot.c +1 -1
index 405eddbda4fc5..144e92f786e35 100644
@@ -155,7 +155,7 @@ struct pbe *restore_pblist;
 
 struct linked_page {
 	struct linked_page *next;
-	char data[LINKED_PAGE_DATA_SIZE];
+	char data[];
 } __packed;
 
 /*
kernel/power/swap.c +106 -23
index 82b884b67152f..ffd4c864acfa2 100644
@@ -59,6 +59,7 @@ static bool clean_pages_on_decompress;
  */
 
 #define MAP_PAGE_ENTRIES	(PAGE_SIZE / sizeof(sector_t) - 1)
+#define NEXT_SWAP_INDEX		MAP_PAGE_ENTRIES
 
 /*
  * Number of free pages that are not high.
@@ -78,8 +79,11 @@ static inline unsigned long reqd_free_pages(void)
 }
 
 struct swap_map_page {
-	sector_t entries[MAP_PAGE_ENTRIES];
-	sector_t next_swap;
+	/*
+	 * A PAGE_SIZE structure with (PAGE_SIZE / sizeof(sector_t)) entries.
+	 * The last entry, [NEXT_SWAP_INDEX], is `.next_swap`.
+	 */
+	sector_t entries[1];
 };
 
 struct swap_map_page_list {
@@ -103,8 +107,6 @@ struct swap_map_handle {
 };
 
 struct swsusp_header {
-	char reserved[PAGE_SIZE - 20 - sizeof(sector_t) - sizeof(int) -
-	              sizeof(u32) - sizeof(u32)];
 	u32	hw_sig;
 	u32	crc32;
 	sector_t image;
@@ -113,6 +115,7 @@ struct swsusp_header {
 	char	sig[10];
 } __packed;
 
+static char *swsusp_header_pg;
 static struct swsusp_header *swsusp_header;
 
 /*
@@ -315,7 +318,7 @@ static int mark_swapfiles(struct swap_map_handle *handle, unsigned int flags)
 {
 	int error;
 
-	hib_submit_io(REQ_OP_READ, swsusp_resume_block, swsusp_header, NULL);
+	hib_submit_io(REQ_OP_READ, swsusp_resume_block, swsusp_header_pg, NULL);
 	if (!memcmp("SWAP-SPACE",swsusp_header->sig, 10) ||
 	    !memcmp("SWAPSPACE2",swsusp_header->sig, 10)) {
 		memcpy(swsusp_header->orig_sig,swsusp_header->sig, 10);
@@ -329,7 +332,7 @@ static int mark_swapfiles(struct swap_map_handle *handle, unsigned int flags)
 		if (flags & SF_CRC32_MODE)
 			swsusp_header->crc32 = handle->crc32;
 		error = hib_submit_io(REQ_OP_WRITE | REQ_SYNC,
-				      swsusp_resume_block, swsusp_header, NULL);
+				      swsusp_resume_block, swsusp_header_pg, NULL);
 	} else {
 		pr_err("Swap header not found!\n");
 		error = -ENODEV;
@@ -466,7 +469,7 @@ static int swap_write_page(struct swap_map_handle *handle, void *buf,
 		offset = alloc_swapdev_block(root_swap);
 		if (!offset)
 			return -ENOSPC;
-		handle->cur->next_swap = offset;
+		handle->cur->entries[NEXT_SWAP_INDEX] = offset;
 		error = write_page(handle->cur, handle->cur_swap, hb);
 		if (error)
 			goto out;
@@ -643,8 +646,8 @@ struct cmp_data {
 	wait_queue_head_t done;                   /* compression done */
 	size_t unc_len;                           /* uncompressed length */
 	size_t cmp_len;                           /* compressed length */
-	unsigned char unc[UNC_SIZE];              /* uncompressed buffer */
-	unsigned char cmp[CMP_SIZE];              /* compressed buffer */
+	unsigned char *unc;                       /* uncompressed buffer */
+	unsigned char *cmp;                       /* compressed buffer */
 };
 
 /* Indicates the image size after compression */
@@ -683,6 +686,45 @@ static int compress_threadfn(void *data)
 	return 0;
 }
 
+static void free_cmp_data(struct cmp_data *data, unsigned nr_threads)
+{
+	int i;
+
+	if (!data)
+		return;
+
+	for (i = 0; i < nr_threads; i++) {
+		vfree(data[i].unc);
+		vfree(data[i].cmp);
+	}
+
+	vfree(data);
+}
+
+static struct cmp_data *alloc_cmp_data(unsigned nr_threads)
+{
+	struct cmp_data *data = NULL;
+	int i = -1;
+
+	data = vzalloc(array_size(nr_threads, sizeof(*data)));
+	if (!data)
+		goto fail;
+
+	for (i = 0; i < nr_threads; i++) {
+		data[i].unc = vzalloc(UNC_SIZE);
+		if (!data[i].unc)
+			goto fail;
+		data[i].cmp = vzalloc(CMP_SIZE);
+		if (!data[i].cmp)
+			goto fail;
+	}
+
+	return data;
+fail:
+	free_cmp_data(data, nr_threads);
+	return NULL;
+}
+
 /**
  * save_compressed_image - Save the suspend image data after compression.
  * @handle: Swap map handle to use for saving the image.
@@ -724,7 +766,7 @@ static int save_compressed_image(struct swap_map_handle *handle,
 		goto out_clean;
 	}
 
-	data = vzalloc(array_size(nr_threads, sizeof(*data)));
+	data = alloc_cmp_data(nr_threads);
 	if (!data) {
 		pr_err("Failed to allocate %s data\n", hib_comp_algo);
 		ret = -ENOMEM;
@@ -902,7 +944,7 @@ static int save_compressed_image(struct swap_map_handle *handle,
 			if (data[thr].cc)
 				crypto_free_comp(data[thr].cc);
 		}
-		vfree(data);
+		free_cmp_data(data, nr_threads);
 	}
 	if (page) free_page((unsigned long)page);
 
@@ -1036,7 +1078,7 @@ static int get_swap_reader(struct swap_map_handle *handle,
 			release_swap_reader(handle);
 			return error;
 		}
-		offset = tmp->map->next_swap;
+		offset = tmp->map->entries[NEXT_SWAP_INDEX];
 	}
 	handle->k = 0;
 	handle->cur = handle->maps->map;
@@ -1150,8 +1192,8 @@ struct dec_data {
 	wait_queue_head_t done;                   /* decompression done */
 	size_t unc_len;                           /* uncompressed length */
 	size_t cmp_len;                           /* compressed length */
-	unsigned char unc[UNC_SIZE];              /* uncompressed buffer */
-	unsigned char cmp[CMP_SIZE];              /* compressed buffer */
+	unsigned char *unc;                       /* uncompressed buffer */
+	unsigned char *cmp;                       /* compressed buffer */
 };
 
 /*
@@ -1189,6 +1231,45 @@ static int decompress_threadfn(void *data)
 	return 0;
 }
 
+static void free_dec_data(struct dec_data *data, unsigned nr_threads)
+{
+	int i;
+
+	if (!data)
+		return;
+
+	for (i = 0; i < nr_threads; i++) {
+		vfree(data[i].unc);
+		vfree(data[i].cmp);
+	}
+
+	vfree(data);
+}
+
+static struct dec_data *alloc_dec_data(unsigned nr_threads)
+{
+	struct dec_data *data = NULL;
+	int i = -1;
+
+	data = vzalloc(array_size(nr_threads, sizeof(*data)));
+	if (!data)
+		goto fail;
+
+	for (i = 0; i < nr_threads; i++) {
+		data[i].unc = vzalloc(UNC_SIZE);
+		if (!data[i].unc)
+			goto fail;
+		data[i].cmp = vzalloc(CMP_SIZE);
+		if (!data[i].cmp)
+			goto fail;
+	}
+
+	return data;
+fail:
+	free_dec_data(data, nr_threads);
+	return NULL;
+}
+
 /**
  * load_compressed_image - Load compressed image data and decompress it.
  * @handle: Swap map handle to use for loading data.
@@ -1231,7 +1312,7 @@ static int load_compressed_image(struct swap_map_handle *handle,
 		goto out_clean;
 	}
 
-	data = vzalloc(array_size(nr_threads, sizeof(*data)));
+	data = alloc_dec_data(nr_threads);
 	if (!data) {
 		pr_err("Failed to allocate %s data\n", hib_comp_algo);
 		ret = -ENOMEM;
@@ -1510,7 +1591,7 @@ static int load_compressed_image(struct swap_map_handle *handle,
 			if (data[thr].cc)
 				crypto_free_comp(data[thr].cc);
 		}
-		vfree(data);
+		free_dec_data(data, nr_threads);
 	}
 	vfree(page);
 
@@ -1569,9 +1650,9 @@ int swsusp_check(bool exclusive)
 	hib_resume_bdev_file = bdev_file_open_by_dev(swsusp_resume_device,
 				BLK_OPEN_READ, holder, NULL);
 	if (!IS_ERR(hib_resume_bdev_file)) {
-		clear_page(swsusp_header);
+		clear_page(swsusp_header_pg);
 		error = hib_submit_io(REQ_OP_READ, swsusp_resume_block,
-					swsusp_header, NULL);
+					swsusp_header_pg, NULL);
 		if (error)
 			goto put;
 
@@ -1581,7 +1662,7 @@ int swsusp_check(bool exclusive)
 			/* Reset swap signature now */
 			error = hib_submit_io(REQ_OP_WRITE | REQ_SYNC,
 						swsusp_resume_block,
-						swsusp_header, NULL);
+						swsusp_header_pg, NULL);
 		} else {
 			error = -EINVAL;
 		}
@@ -1631,12 +1712,12 @@ int swsusp_unmark(void)
 	int error;
 
 	hib_submit_io(REQ_OP_READ, swsusp_resume_block,
-			swsusp_header, NULL);
+			swsusp_header_pg, NULL);
 	if (!memcmp(HIBERNATE_SIG,swsusp_header->sig, 10)) {
 		memcpy(swsusp_header->sig,swsusp_header->orig_sig, 10);
 		error = hib_submit_io(REQ_OP_WRITE | REQ_SYNC,
 					swsusp_resume_block,
-					swsusp_header, NULL);
+					swsusp_header_pg, NULL);
 	} else {
 		pr_err("Cannot find swsusp signature!\n");
 		error = -ENODEV;
@@ -1653,9 +1734,11 @@ int swsusp_unmark(void)
 
 static int __init swsusp_header_init(void)
 {
-	swsusp_header = (struct swsusp_header*) __get_free_page(GFP_KERNEL);
-	if (!swsusp_header)
+	swsusp_header_pg = (char *)__get_free_page(GFP_KERNEL);
+	if (!swsusp_header_pg)
 		panic("Could not allocate memory for swsusp_header\n");
+	swsusp_header = (struct swsusp_header *)(swsusp_header_pg +
+				PAGE_SIZE - sizeof(struct swsusp_header));
 	return 0;
 }
 
author reviewer
#42 lore raw

RFC PATCH 15/57 stackdepot: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

"union handle_parts" previously calculated the number of bits required for its pool index and offset members based on PAGE_SHIFT. This is problematic for boot-time page size builds because the actual page size isn't known until boot-time.

We could use PAGE_SHIFT_MAX in calculating the worst case offset bits, but bits would be wasted that could be used for pool index when PAGE_SIZE is set smaller than MAX, the end result being that stack depot can address less memory than it should.

To avoid needing to dynamically define the offset and index bit widths, let's instead fix the pool size and derive the order at runtime based on the PAGE_SIZE. This means that the fields' widths can remain static, with the down side being slightly increased risk of failing to allocate the large folio.

This only affects boot-time page size builds. compile-time page size builds will still always allocate order-2 folios.

Additionally, wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/stackdepot.h | 6 +++---
 lib/stackdepot.c           | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)
include/linux/stackdepot.h +3 -3
index e9ec32fb97d4a..ac877a4e90406 100644
@@ -32,10 +32,10 @@ typedef u32 depot_stack_handle_t;
 
 #define DEPOT_HANDLE_BITS (sizeof(depot_stack_handle_t) * 8)
 
-#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages */
-#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT + DEPOT_POOL_ORDER))
+#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages of PAGE_SIZE_MAX */
+#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT_MAX + DEPOT_POOL_ORDER))
 #define DEPOT_STACK_ALIGN 4
-#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT - DEPOT_STACK_ALIGN)
+#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT_MAX - DEPOT_STACK_ALIGN)
 #define DEPOT_POOL_INDEX_BITS (DEPOT_HANDLE_BITS - DEPOT_OFFSET_BITS - \
 			       STACK_DEPOT_EXTRA_BITS)
 
lib/stackdepot.c +3 -3
index 5ed34cc963fc3..974351f0e9e3c 100644
@@ -68,7 +68,7 @@ static void *new_pool;
 /* Number of pools in stack_pools. */
 static int pools_num;
 /* Offset to the unused space in the currently used pool. */
-static size_t pool_offset = DEPOT_POOL_SIZE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(size_t, pool_offset, DEPOT_POOL_SIZE);
 /* Freelist of stack records within stack_pools. */
 static LIST_HEAD(free_stacks);
 /* The lock must be held when performing pool or freelist modifications. */
@@ -625,7 +625,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 	 */
 	if (unlikely(can_alloc && !READ_ONCE(new_pool))) {
 		page = alloc_pages(gfp_nested_mask(alloc_flags),
-				   DEPOT_POOL_ORDER);
+				   get_order(DEPOT_POOL_SIZE));
 		if (page)
 			prealloc = page_address(page);
 	}
@@ -663,7 +663,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 exit:
 	if (prealloc) {
 		/* Stack depot didn't use this memory, free it. */
-		free_pages((unsigned long)prealloc, DEPOT_POOL_ORDER);
+		free_pages((unsigned long)prealloc, get_order(DEPOT_POOL_SIZE));
 	}
 	if (found)
 		handle = found->handle.handle;
Signature · 1 line
2.43.0
Acked-by on v1 15/57
#43 lore raw

Re: [RFC PATCH v1 15/57] stackdepot: Remove PAGE_SIZE compile-time constant assumption

Quoted 20 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

"union handle_parts" previously calculated the number of bits required for its pool index and offset members based on PAGE_SHIFT. This is problematic for boot-time page size builds because the actual page size isn't known until boot-time.

We could use PAGE_SHIFT_MAX in calculating the worst case offset bits, but bits would be wasted that could be used for pool index when PAGE_SIZE is set smaller than MAX, the end result being that stack depot can address less memory than it should.

To avoid needing to dynamically define the offset and index bit widths, let's instead fix the pool size and derive the order at runtime based on the PAGE_SIZE. This means that the fields' widths can remain static, with the down side being slightly increased risk of failing to allocate the large folio.

Quoted 6 lines

This only affects boot-time page size builds. compile-time page size builds will still always allocate order-2 folios.

Additionally, wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

This is done for pool_offset but given it's initialized by DEPOT_POOL_SIZE, it doesn't look derived from PAGE_SIZE?

Quoted 2 lines

Other than that,

Quoted 59 lines

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/stackdepot.h | 6 +++---
 lib/stackdepot.c           | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)
include/linux/stackdepot.h +3 -3
index e9ec32fb97d4a..ac877a4e90406 100644
@@ -32,10 +32,10 @@ typedef u32 depot_stack_handle_t;
 
 #define DEPOT_HANDLE_BITS (sizeof(depot_stack_handle_t) * 8)
 
-#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages */
-#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT + DEPOT_POOL_ORDER))
+#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages of PAGE_SIZE_MAX */
+#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT_MAX + DEPOT_POOL_ORDER))
 #define DEPOT_STACK_ALIGN 4
-#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT - DEPOT_STACK_ALIGN)
+#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT_MAX - DEPOT_STACK_ALIGN)
 #define DEPOT_POOL_INDEX_BITS (DEPOT_HANDLE_BITS - DEPOT_OFFSET_BITS - \
 			       STACK_DEPOT_EXTRA_BITS)
 
lib/stackdepot.c +3 -3
index 5ed34cc963fc3..974351f0e9e3c 100644
@@ -68,7 +68,7 @@ static void *new_pool;
 /* Number of pools in stack_pools. */
 static int pools_num;
 /* Offset to the unused space in the currently used pool. */
-static size_t pool_offset = DEPOT_POOL_SIZE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(size_t, pool_offset, DEPOT_POOL_SIZE);
 /* Freelist of stack records within stack_pools. */
 static LIST_HEAD(free_stacks);
 /* The lock must be held when performing pool or freelist modifications. */
@@ -625,7 +625,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 	 */
 	if (unlikely(can_alloc && !READ_ONCE(new_pool))) {
 		page = alloc_pages(gfp_nested_mask(alloc_flags),
-				   DEPOT_POOL_ORDER);
+				   get_order(DEPOT_POOL_SIZE));
 		if (page)
 			prealloc = page_address(page);
 	}
@@ -663,7 +663,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 exit:
 	if (prealloc) {
 		/* Stack depot didn't use this memory, free it. */
-		free_pages((unsigned long)prealloc, DEPOT_POOL_ORDER);
+		free_pages((unsigned long)prealloc, get_order(DEPOT_POOL_SIZE));
 	}
 	if (found)
 		handle = found->handle.handle;
author reviewer
#44 lore raw

Re: [RFC PATCH v1 15/57] stackdepot: Remove PAGE_SIZE compile-time constant assumption

Quoted 24 lines · Vlastimil Babka
Quoted 23 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

"union handle_parts" previously calculated the number of bits required for its pool index and offset members based on PAGE_SHIFT. This is problematic for boot-time page size builds because the actual page size isn't known until boot-time.

We could use PAGE_SHIFT_MAX in calculating the worst case offset bits, but bits would be wasted that could be used for pool index when PAGE_SIZE is set smaller than MAX, the end result being that stack depot can address less memory than it should.

To avoid needing to dynamically define the offset and index bit widths, let's instead fix the pool size and derive the order at runtime based on the PAGE_SIZE. This means that the fields' widths can remain static, with the down side being slightly increased risk of failing to allocate the large folio.

This only affects boot-time page size builds. compile-time page size builds will still always allocate order-2 folios.

Quoted 6 lines
Quoted 3 lines

Additionally, wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

This is done for pool_offset but given it's initialized by DEPOT_POOL_SIZE, it doesn't look derived from PAGE_SIZE?

Good spot; I think I initially did this when DEPOT_POOL_SIZE was still based on PAGE_SIZE. But then I've subsequently re-defined DEPOT_POOL_SIZE to be independent of PAGE_SIZE. I'll remove this part of the change.

Quoted 6 lines
Quoted 3 lines

Other than that,

Thanks!

Quoted 62 lines
Quoted 61 lines

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/stackdepot.h | 6 +++---
 lib/stackdepot.c           | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)
include/linux/stackdepot.h +3 -3
index e9ec32fb97d4a..ac877a4e90406 100644
@@ -32,10 +32,10 @@ typedef u32 depot_stack_handle_t;
 
 #define DEPOT_HANDLE_BITS (sizeof(depot_stack_handle_t) * 8)
 
-#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages */
-#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT + DEPOT_POOL_ORDER))
+#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages of PAGE_SIZE_MAX */
+#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT_MAX + DEPOT_POOL_ORDER))
 #define DEPOT_STACK_ALIGN 4
-#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT - DEPOT_STACK_ALIGN)
+#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT_MAX - DEPOT_STACK_ALIGN)
 #define DEPOT_POOL_INDEX_BITS (DEPOT_HANDLE_BITS - DEPOT_OFFSET_BITS - \
 			       STACK_DEPOT_EXTRA_BITS)
 
lib/stackdepot.c +3 -3
index 5ed34cc963fc3..974351f0e9e3c 100644
@@ -68,7 +68,7 @@ static void *new_pool;
 /* Number of pools in stack_pools. */
 static int pools_num;
 /* Offset to the unused space in the currently used pool. */
-static size_t pool_offset = DEPOT_POOL_SIZE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(size_t, pool_offset, DEPOT_POOL_SIZE);
 /* Freelist of stack records within stack_pools. */
 static LIST_HEAD(free_stacks);
 /* The lock must be held when performing pool or freelist modifications. */
@@ -625,7 +625,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 	 */
 	if (unlikely(can_alloc && !READ_ONCE(new_pool))) {
 		page = alloc_pages(gfp_nested_mask(alloc_flags),
-				   DEPOT_POOL_ORDER);
+				   get_order(DEPOT_POOL_SIZE));
 		if (page)
 			prealloc = page_address(page);
 	}
@@ -663,7 +663,7 @@ depot_stack_handle_t stack_depot_save_flags(unsigned long *entries,
 exit:
 	if (prealloc) {
 		/* Stack depot didn't use this memory, free it. */
-		free_pages((unsigned long)prealloc, DEPOT_POOL_ORDER);
+		free_pages((unsigned long)prealloc, get_order(DEPOT_POOL_SIZE));
 	}
 	if (found)
 		handle = found->handle.handle;
author reviewer
#45 lore raw

RFC PATCH 16/57 perf: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor a BUILD_BUG_ON() so that we test against the limit; _format is invariant to page size so testing it is no bigger than the minimum supported size is sufficient.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/perf_event.h | 2 +-
 kernel/events/core.c       | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
include/linux/perf_event.h +1 -1
index 1a8942277ddad..b7972155f93eb 100644
@@ -1872,7 +1872,7 @@ _name##_show(struct device *dev,					\
 			       struct device_attribute *attr,		\
 			       char *page)				\
 {									\
-	BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE);			\
+	BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE_MIN);			\
 	return sprintf(page, _format "\n");				\
 }									\
 
kernel/events/core.c +1 -1
index 8a6c6bbcd658a..81149663ab7d8 100644
@@ -419,7 +419,7 @@ static struct kmem_cache *perf_event_cache;
 int sysctl_perf_event_paranoid __read_mostly = 2;
 
 /* Minimum for 512 kiB + 1 user control page */
-int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
+__DEFINE_GLOBAL_PAGE_SIZE_VAR(int, sysctl_perf_event_mlock, __read_mostly, 512 + (PAGE_SIZE / 1024)); /* 'free' kiB per user */
 
 /*
  * max perf event sample rate
Signature · 1 line
2.43.0
author reviewer
#46 lore raw

Re: [RFC PATCH v1 16/57] perf: Remove PAGE_SIZE compile-time constant assumption

+ Arnaldo Carvalho de Melo, Ingo Molnar, Namhyung Kim, Peter Zijlstra

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 49 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactor a BUILD_BUG_ON() so that we test against the limit; _format is invariant to page size so testing it is no bigger than the minimum supported size is sufficient.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/perf_event.h | 2 +-
 kernel/events/core.c       | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
include/linux/perf_event.h +1 -1
index 1a8942277ddad..b7972155f93eb 100644
@@ -1872,7 +1872,7 @@ _name##_show(struct device *dev,					\
 			       struct device_attribute *attr,		\
 			       char *page)				\
 {									\
-	BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE);			\
+	BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE_MIN);			\
 	return sprintf(page, _format "\n");				\
 }									\
 
kernel/events/core.c +1 -1
index 8a6c6bbcd658a..81149663ab7d8 100644
@@ -419,7 +419,7 @@ static struct kmem_cache *perf_event_cache;
 int sysctl_perf_event_paranoid __read_mostly = 2;
 
 /* Minimum for 512 kiB + 1 user control page */
-int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
+__DEFINE_GLOBAL_PAGE_SIZE_VAR(int, sysctl_perf_event_mlock, __read_mostly, 512 + (PAGE_SIZE / 1024)); /* 'free' kiB per user */
 
 /*
  * max perf event sample rate
author reviewer
#47 lore raw

RFC PATCH 17/57 kvm: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Modify BUILD_BUG_ON() to compare with page size limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 virt/kvm/kvm_main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
virt/kvm/kvm_main.c +1 -1
index cb2b78e92910f..6c862bc41a672 100644
@@ -4244,7 +4244,7 @@ static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id)
 		goto vcpu_decrement;
 	}
 
-	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
+	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE_MIN);
 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
 	if (!page) {
 		r = -ENOMEM;
Signature · 1 line
2.43.0
reviewer Reviewed-by on v1 17/57
#48 lore raw

Re: [RFC PATCH v1 17/57] kvm: Remove PAGE_SIZE compile-time constant assumption

Nit, "KVM:" for the scope.

Quoted 4 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Quoted 8 lines

Modify BUILD_BUG_ON() to compare with page size limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

The patch should still stand on its own. Most people can probably suss out what PAGE_SIZE_MIN is, but at the same time, it's quite easy to provide a more verbose changelog that's tailored to the actual patch. E.g.

To prepare for supporting boot-time page size selection, refactor KVM's check on the size of the kvm_run structure to assert that the size is less than the smallest possible page size, i.e. that kvm_run won't overflow its page regardless of what page size is chosen at boot time.

With something like the above,

author reviewer
#49 lore raw

Re: [RFC PATCH v1 17/57] kvm: Remove PAGE_SIZE compile-time constant assumption

Quoted 1 line · Sean Christopherson

Nit, "KVM:" for the scope.

Thanks, will fix.

Quoted 19 lines · Ryan Roberts
Quoted 4 lines

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Quoted 8 lines

Modify BUILD_BUG_ON() to compare with page size limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

The patch should still stand on its own. Most people can probably suss out what PAGE_SIZE_MIN is, but at the same time, it's quite easy to provide a more verbose changelog that's tailored to the actual patch. E.g.

Quoted 8 lines

To prepare for supporting boot-time page size selection, refactor KVM's check on the size of the kvm_run structure to assert that the size is less than the smallest possible page size, i.e. that kvm_run won't overflow its page regardless of what page size is chosen at boot time.

With something like the above,

Thanks! I'll update this for the next version.

author reviewer
#50 lore raw

Re: [RFC PATCH v1 17/57] kvm: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

+ Paolo Bonzini

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 29 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Modify BUILD_BUG_ON() to compare with page size limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 virt/kvm/kvm_main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
virt/kvm/kvm_main.c +1 -1
index cb2b78e92910f..6c862bc41a672 100644
@@ -4244,7 +4244,7 @@ static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id)
 		goto vcpu_decrement;
 	}
 
-	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
+	BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE_MIN);
 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
 	if (!page) {
 		r = -ENOMEM;
author reviewer
#51 lore raw

RFC PATCH 18/57 trace: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert BUILD_BUG_ON() BUG_ON() since the argument depends on PAGE_SIZE and its not trivial to test against a page size limit.

Redefine FTRACE_KSTACK_ENTRIES so that "struct ftrace_stacks" is always sized at 32K for 64-bit and 16K for 32-bit. It was previously defined in terms of PAGE_SIZE (and worked out at the quoted sizes for a 4K page size). But for 64K pages, the size expanded to 512K. Given the ftrace stacks should be invariant to page size, this seemed like a waste. As a side effect, it removes the PAGE_SIZE compile-time constant assumption from this code.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/trace/fgraph.c | 2 +-
 kernel/trace/trace.c  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
kernel/trace/fgraph.c +1 -1
index d7d4fb403f6f0..47aa5c8d8090e 100644
@@ -534,7 +534,7 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func,
 	if (!current->ret_stack)
 		return -EBUSY;
 
-	BUILD_BUG_ON(SHADOW_STACK_SIZE % sizeof(long));
+	BUG_ON(SHADOW_STACK_SIZE % sizeof(long));
 
 	/* Set val to "reserved" with the delta to the new fgraph frame */
 	val = (FGRAPH_TYPE_RESERVED << FGRAPH_TYPE_SHIFT) | FGRAPH_FRAME_OFFSET;
kernel/trace/trace.c +1 -1
index c3b2c7dfadef1..0f2ec3d30579f 100644
@@ -2887,7 +2887,7 @@ trace_function(struct trace_array *tr, unsigned long ip, unsigned long
 /* Allow 4 levels of nesting: normal, softirq, irq, NMI */
 #define FTRACE_KSTACK_NESTING	4
 
-#define FTRACE_KSTACK_ENTRIES	(PAGE_SIZE / FTRACE_KSTACK_NESTING)
+#define FTRACE_KSTACK_ENTRIES	(SZ_4K / FTRACE_KSTACK_NESTING)
 
 struct ftrace_stack {
 	unsigned long		calls[FTRACE_KSTACK_ENTRIES];
Signature · 1 line
2.43.0
maintainer
#52 lore raw

Re: [RFC PATCH v1 18/57] trace: Remove PAGE_SIZE compile-time constant assumption

Quoted 31 lines · On Mon, 14 Oct 2024 11:58:25 +0100 Ryan Roberts <[email protected]> wrote:

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert BUILD_BUG_ON() BUG_ON() since the argument depends on PAGE_SIZE and its not trivial to test against a page size limit.

Redefine FTRACE_KSTACK_ENTRIES so that "struct ftrace_stacks" is always sized at 32K for 64-bit and 16K for 32-bit. It was previously defined in terms of PAGE_SIZE (and worked out at the quoted sizes for a 4K page size). But for 64K pages, the size expanded to 512K. Given the ftrace stacks should be invariant to page size, this seemed like a waste. As a side effect, it removes the PAGE_SIZE compile-time constant assumption from this code.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/trace/fgraph.c | 2 +-
 kernel/trace/trace.c  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
kernel/trace/fgraph.c +0 -0
index d7d4fb403f6f0..47aa5c8d8090e 100644

kernel/trace/fgraph.c ftrace_push_return_trace(unsigned long ret, unsigned long func, · line 537

Quoted 5 lines
kernel/trace/fgraph.c +1 -1
@@ -534,7 +534,7 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func,
 	if (!current->ret_stack)
 		return -EBUSY;
 
-	BUILD_BUG_ON(SHADOW_STACK_SIZE % sizeof(long));
+	BUG_ON(SHADOW_STACK_SIZE % sizeof(long));

Absolutely not!

BUG_ON() is in no way a substitution of any BUILD_BUG_ON(). BUILD_BUG_ON() is a non intrusive way to see if something isn't lined up correctly, and can fix it before you execute any code. BUG_ON() is the most intrusive way to say something is wrong and you crash the system.

Not to mention, when function graph tracing is enabled, this gets triggered for *every* function call! So I do not want any runtime test done. Every nanosecond counts in this code path.

If anything, this needs to be moved to initialization and checked once, if it fails, gives a WARN_ON() and disables function graph tracing.

-- Steve

Quoted 16 lines
kernel/trace/fgraph.c +0 -0
 	/* Set val to "reserved" with the delta to the new fgraph frame */
 	val = (FGRAPH_TYPE_RESERVED << FGRAPH_TYPE_SHIFT) | FGRAPH_FRAME_OFFSET;
kernel/trace/trace.c +1 -1
index c3b2c7dfadef1..0f2ec3d30579f 100644
@@ -2887,7 +2887,7 @@ trace_function(struct trace_array *tr, unsigned long ip, unsigned long
 /* Allow 4 levels of nesting: normal, softirq, irq, NMI */
 #define FTRACE_KSTACK_NESTING	4
 
-#define FTRACE_KSTACK_ENTRIES	(PAGE_SIZE / FTRACE_KSTACK_NESTING)
+#define FTRACE_KSTACK_ENTRIES	(SZ_4K / FTRACE_KSTACK_NESTING)
 
 struct ftrace_stack {
 	unsigned long		calls[FTRACE_KSTACK_ENTRIES];
author reviewer
#53 lore raw

Re: [RFC PATCH v1 18/57] trace: Remove PAGE_SIZE compile-time constant assumption

Quoted 42 lines · Steven Rostedt
Quoted 31 lines · On Mon, 14 Oct 2024 11:58:25 +0100 Ryan Roberts <[email protected]> wrote:

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert BUILD_BUG_ON() BUG_ON() since the argument depends on PAGE_SIZE and its not trivial to test against a page size limit.

Redefine FTRACE_KSTACK_ENTRIES so that "struct ftrace_stacks" is always sized at 32K for 64-bit and 16K for 32-bit. It was previously defined in terms of PAGE_SIZE (and worked out at the quoted sizes for a 4K page size). But for 64K pages, the size expanded to 512K. Given the ftrace stacks should be invariant to page size, this seemed like a waste. As a side effect, it removes the PAGE_SIZE compile-time constant assumption from this code.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/trace/fgraph.c | 2 +-
 kernel/trace/trace.c  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
kernel/trace/fgraph.c +0 -0
index d7d4fb403f6f0..47aa5c8d8090e 100644

kernel/trace/fgraph.c ftrace_push_return_trace(unsigned long ret, unsigned long func, · line 537

Quoted 5 lines
kernel/trace/fgraph.c +1 -1
@@ -534,7 +534,7 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func,
 	if (!current->ret_stack)
 		return -EBUSY;
 
-	BUILD_BUG_ON(SHADOW_STACK_SIZE % sizeof(long));
+	BUG_ON(SHADOW_STACK_SIZE % sizeof(long));

Absolutely not!

Quoted 4 lines

BUG_ON() is in no way a substitution of any BUILD_BUG_ON(). BUILD_BUG_ON() is a non intrusive way to see if something isn't lined up correctly, and can fix it before you execute any code. BUG_ON() is the most intrusive way to say something is wrong and you crash the system.

Yep, totally agree. I'm afraid this was me being lazy, and there are a couple of other instances where I have done this in other patches that I'll need to fix. Most of the time, I've been able to keep BUILD_BUG_ON() and simply compare against a page size limit.

Looking at this again, perhaps the better solution is to define SHADOW_STACK_SIZE as PAGE_SIZE_MIN? Then it remains a compile-time constant. Is there any need for SHADOW_STACK_SIZE to increase with page size?

Quoted 7 lines

Not to mention, when function graph tracing is enabled, this gets triggered for *every* function call! So I do not want any runtime test done. Every nanosecond counts in this code path.

If anything, this needs to be moved to initialization and checked once, if it fails, gives a WARN_ON() and disables function graph tracing.

I'm hoping my suggestion above to decouple SHADOW_STACK_SIZE from PAGE_SIZE is acceptable and simpler? If not, happy to do as you suggest here.

Thanks,
Ryan

Quoted 21 lines

-- Steve

Quoted 16 lines
kernel/trace/fgraph.c +0 -0
 	/* Set val to "reserved" with the delta to the new fgraph frame */
 	val = (FGRAPH_TYPE_RESERVED << FGRAPH_TYPE_SHIFT) | FGRAPH_FRAME_OFFSET;
kernel/trace/trace.c +1 -1
index c3b2c7dfadef1..0f2ec3d30579f 100644
@@ -2887,7 +2887,7 @@ trace_function(struct trace_array *tr, unsigned long ip, unsigned long
 /* Allow 4 levels of nesting: normal, softirq, irq, NMI */
 #define FTRACE_KSTACK_NESTING	4
 
-#define FTRACE_KSTACK_ENTRIES	(PAGE_SIZE / FTRACE_KSTACK_NESTING)
+#define FTRACE_KSTACK_ENTRIES	(SZ_4K / FTRACE_KSTACK_NESTING)
 
 struct ftrace_stack {
 	unsigned long		calls[FTRACE_KSTACK_ENTRIES];
maintainer
#54 lore raw

Re: [RFC PATCH v1 18/57] trace: Remove PAGE_SIZE compile-time constant assumption

Quoted 10 lines · On Tue, 15 Oct 2024 12:09:38 +0100 Ryan Roberts <[email protected]> wrote:
Quoted 7 lines

Not to mention, when function graph tracing is enabled, this gets triggered for *every* function call! So I do not want any runtime test done. Every nanosecond counts in this code path.

If anything, this needs to be moved to initialization and checked once, if it fails, gives a WARN_ON() and disables function graph tracing.

I'm hoping my suggestion above to decouple SHADOW_STACK_SIZE from PAGE_SIZE is acceptable and simpler? If not, happy to do as you suggest here.

Yeah, I think we can do that. In fact, I'm thinking it should turn into a kmem_cache item that doesn't have to be a power of two (but must be evenly divisible by the size of long).

I'll write up a patch.

-- Steve

author reviewer
#55 lore raw

RFC PATCH 19/57 crash: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/crash_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/crash_core.c +1 -1
index 63cf89393c6eb..978c600a47ac8 100644
@@ -465,7 +465,7 @@ static int __init crash_notes_memory_init(void)
 	 * Break compile if size is bigger than PAGE_SIZE since crash_notes
 	 * definitely will be in 2 pages with that.
 	 */
-	BUILD_BUG_ON(size > PAGE_SIZE);
+	BUILD_BUG_ON(size > PAGE_SIZE_MIN);
 
 	crash_notes = __alloc_percpu(size, align);
 	if (!crash_notes) {
Signature · 1 line
2.43.0
Acked-by on v1 19/57
#56 lore raw

Re: [RFC PATCH v1 19/57] crash: Remove PAGE_SIZE compile-time constant assumption

Quoted 21 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/crash_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/crash_core.c +0 -0
index 63cf89393c6eb..978c600a47ac8 100644

kernel/crash_core.c static int __init crash_notes_memory_init(void) · line 468

Quoted 5 lines
kernel/crash_core.c +1 -1
@@ -465,7 +465,7 @@ static int __init crash_notes_memory_init(void)
 	 * Break compile if size is bigger than PAGE_SIZE since crash_notes
 	 * definitely will be in 2 pages with that.
 	 */
-	BUILD_BUG_ON(size > PAGE_SIZE);
+	BUILD_BUG_ON(size > PAGE_SIZE_MIN);

This should be OK. While one thing which could happen is if selected size is 64K, PAGE_SIZE_MIN is 4K, it will issue a false-positive warning when compiling while actual it's not a problem during running. Not sure if that could happen on arm64. Anyway, we can check the crash_notes to get why it's so big when it really happens. So,

Quoted 7 lines
kernel/crash_core.c +0 -0
 	crash_notes = __alloc_percpu(size, align);
 	if (!crash_notes) {
Signature · 1 line
2.43.0
author reviewer
#57 lore raw

Re: [RFC PATCH v1 19/57] crash: Remove PAGE_SIZE compile-time constant assumption

Quoted 17 lines · Baoquan He
Quoted 16 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/crash_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Quoted 14 lines

kernel/crash_core.c static int __init crash_notes_memory_init(void) · line 468

Quoted 10 lines
kernel/crash_core.c +1 -1
index 63cf89393c6eb..978c600a47ac8 100644
@@ -465,7 +465,7 @@ static int __init crash_notes_memory_init(void)
 	 * Break compile if size is bigger than PAGE_SIZE since crash_notes
 	 * definitely will be in 2 pages with that.
 	 */
-	BUILD_BUG_ON(size > PAGE_SIZE);
+	BUILD_BUG_ON(size > PAGE_SIZE_MIN);

This should be OK. While one thing which could happen is if selected size is 64K, PAGE_SIZE_MIN is 4K, it will issue a false-positive warning when compiling while actual it's not a problem during running.

PAGE_SIZE can only ever be bigger than PAGE_SIZE_MIN if compiling a "boot-time page size" build. And in this case, you need to know that size is small enough to work with any of the boot-time selectable page sizes. Since size (=sizeof(note_buf_t)) is invariant to PAGE_SIZE, we can do this by checking against PAGE_SIZE_MIN.

So I don't think this could ever lead to a false-positive.

Not sure if

Quoted 4 lines

that could happen on arm64. Anyway, we can check the crash_notes to get why it's so big when it really happens. So,

Thanks!

Quoted 9 lines
Quoted 8 lines
kernel/crash_core.c +0 -0
 	crash_notes = __alloc_percpu(size, align);
 	if (!crash_notes) {
Signature · 1 line
2.43.0
#58 lore raw

Re: [RFC PATCH v1 19/57] crash: Remove PAGE_SIZE compile-time constant assumption

Quoted 33 lines · Ryan Roberts
Quoted 17 lines · Baoquan He
Quoted 16 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 kernel/crash_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Quoted 14 lines

kernel/crash_core.c static int __init crash_notes_memory_init(void) · line 468

Quoted 10 lines
kernel/crash_core.c +1 -1
index 63cf89393c6eb..978c600a47ac8 100644
@@ -465,7 +465,7 @@ static int __init crash_notes_memory_init(void)
 	 * Break compile if size is bigger than PAGE_SIZE since crash_notes
 	 * definitely will be in 2 pages with that.
 	 */
-	BUILD_BUG_ON(size > PAGE_SIZE);
+	BUILD_BUG_ON(size > PAGE_SIZE_MIN);

This should be OK. While one thing which could happen is if selected size is 64K, PAGE_SIZE_MIN is 4K, it will issue a false-positive warning when compiling while actual it's not a problem during running.

Quoted 7 lines

PAGE_SIZE can only ever be bigger than PAGE_SIZE_MIN if compiling a "boot-time page size" build. And in this case, you need to know that size is small enough to work with any of the boot-time selectable page sizes. Since size (=sizeof(note_buf_t)) is invariant to PAGE_SIZE, we can do this by checking against PAGE_SIZE_MIN.

So I don't think this could ever lead to a false-positive.

Makes sense, thanks for your explanation.

Quoted 20 lines

Not sure if

Quoted 4 lines

that could happen on arm64. Anyway, we can check the crash_notes to get why it's so big when it really happens. So,

Thanks!

Quoted 9 lines
Quoted 8 lines
kernel/crash_core.c +0 -0
 	crash_notes = __alloc_percpu(size, align);
 	if (!crash_notes) {
Signature · 1 line
2.43.0
author reviewer
#59 lore raw

RFC PATCH 20/57 crypto: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 crypto/lskcipher.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
crypto/lskcipher.c +2 -2
index cdb4897c63e6f..2b84cefba7cd1 100644
@@ -79,8 +79,8 @@ static int crypto_lskcipher_crypt_unaligned(
 	u8 *tiv;
 	u8 *p;
 
-	BUILD_BUG_ON(MAX_CIPHER_BLOCKSIZE > PAGE_SIZE ||
-		     MAX_CIPHER_ALIGNMASK >= PAGE_SIZE);
+	BUILD_BUG_ON(MAX_CIPHER_BLOCKSIZE > PAGE_SIZE_MIN ||
+		     MAX_CIPHER_ALIGNMASK >= PAGE_SIZE_MIN);
 
 	tiv = kmalloc(PAGE_SIZE, GFP_ATOMIC);
 	if (!tiv)
Signature · 1 line
2.43.0
maintainer Acked-by on v1 20/57
#60 lore raw

Re: [RFC PATCH v1 20/57] crypto: Remove PAGE_SIZE compile-time constant assumption

Quoted 7 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

Quoted 8 lines

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 crypto/lskcipher.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author reviewer
#61 lore raw

RFC PATCH 21/57 sunrpc: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated array sizes in various structs to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/sunrpc/svc.h      | 8 +++++---
 include/linux/sunrpc/svc_rdma.h | 4 ++--
 include/linux/sunrpc/svcsock.h  | 2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)
include/linux/sunrpc/svc.h +5 -3
index a7d0406b9ef59..dda44018b8f36 100644
@@ -160,6 +160,8 @@ extern u32 svc_max_payload(const struct svc_rqst *rqstp);
  */
 #define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE-1)/PAGE_SIZE \
 				+ 2 + 1)
+#define RPCSVC_MAXPAGES_MAX	((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/PAGE_SIZE_MIN \
+				+ 2 + 1)
 
 /*
  * The context of a single thread, including the request currently being
@@ -190,14 +192,14 @@ struct svc_rqst {
 	struct xdr_stream	rq_res_stream;
 	struct page		*rq_scratch_page;
 	struct xdr_buf		rq_res;
-	struct page		*rq_pages[RPCSVC_MAXPAGES + 1];
+	struct page		*rq_pages[RPCSVC_MAXPAGES_MAX + 1];
 	struct page *		*rq_respages;	/* points into rq_pages */
 	struct page *		*rq_next_page; /* next reply page to use */
 	struct page *		*rq_page_end;  /* one past the last page */
 
 	struct folio_batch	rq_fbatch;
-	struct kvec		rq_vec[RPCSVC_MAXPAGES]; /* generally useful.. */
-	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES];
+	struct kvec		rq_vec[RPCSVC_MAXPAGES_MAX]; /* generally useful.. */
+	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES_MAX];
 
 	__be32			rq_xid;		/* transmission id */
 	u32			rq_prog;	/* program number */
include/linux/sunrpc/svc_rdma.h +2 -2
index d33bab33099ab..7c6441e8d6f7a 100644
@@ -200,7 +200,7 @@ struct svc_rdma_recv_ctxt {
 	struct svc_rdma_pcl	rc_reply_pcl;
 
 	unsigned int		rc_page_count;
-	struct page		*rc_pages[RPCSVC_MAXPAGES];
+	struct page		*rc_pages[RPCSVC_MAXPAGES_MAX];
 };
 
 /*
@@ -242,7 +242,7 @@ struct svc_rdma_send_ctxt {
 	void			*sc_xprt_buf;
 	int			sc_page_count;
 	int			sc_cur_sge_no;
-	struct page		*sc_pages[RPCSVC_MAXPAGES];
+	struct page		*sc_pages[RPCSVC_MAXPAGES_MAX];
 	struct ib_sge		sc_sges[];
 };
 
include/linux/sunrpc/svcsock.h +1 -1
index 7c78ec6356b92..6c6bcc82685a3 100644
@@ -40,7 +40,7 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
-	struct page *		sk_pages[RPCSVC_MAXPAGES];	/* received data */
+	struct page *		sk_pages[RPCSVC_MAXPAGES_MAX];	/* received data */
 };
 
 static inline u32 svc_sock_reclen(struct svc_sock *svsk)
Signature · 1 line
2.43.0
author reviewer
#62 lore raw

Re: [RFC PATCH v1 21/57] sunrpc: Remove PAGE_SIZE compile-time constant assumption

+ Chuck Lever, Jeff Layton

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 85 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated array sizes in various structs to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/sunrpc/svc.h      | 8 +++++---
 include/linux/sunrpc/svc_rdma.h | 4 ++--
 include/linux/sunrpc/svcsock.h  | 2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)
include/linux/sunrpc/svc.h +5 -3
index a7d0406b9ef59..dda44018b8f36 100644
@@ -160,6 +160,8 @@ extern u32 svc_max_payload(const struct svc_rqst *rqstp);
  */
 #define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE-1)/PAGE_SIZE \
 				+ 2 + 1)
+#define RPCSVC_MAXPAGES_MAX	((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/PAGE_SIZE_MIN \
+				+ 2 + 1)
 
 /*
  * The context of a single thread, including the request currently being
@@ -190,14 +192,14 @@ struct svc_rqst {
 	struct xdr_stream	rq_res_stream;
 	struct page		*rq_scratch_page;
 	struct xdr_buf		rq_res;
-	struct page		*rq_pages[RPCSVC_MAXPAGES + 1];
+	struct page		*rq_pages[RPCSVC_MAXPAGES_MAX + 1];
 	struct page *		*rq_respages;	/* points into rq_pages */
 	struct page *		*rq_next_page; /* next reply page to use */
 	struct page *		*rq_page_end;  /* one past the last page */
 
 	struct folio_batch	rq_fbatch;
-	struct kvec		rq_vec[RPCSVC_MAXPAGES]; /* generally useful.. */
-	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES];
+	struct kvec		rq_vec[RPCSVC_MAXPAGES_MAX]; /* generally useful.. */
+	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES_MAX];
 
 	__be32			rq_xid;		/* transmission id */
 	u32			rq_prog;	/* program number */
include/linux/sunrpc/svc_rdma.h +2 -2
index d33bab33099ab..7c6441e8d6f7a 100644
@@ -200,7 +200,7 @@ struct svc_rdma_recv_ctxt {
 	struct svc_rdma_pcl	rc_reply_pcl;
 
 	unsigned int		rc_page_count;
-	struct page		*rc_pages[RPCSVC_MAXPAGES];
+	struct page		*rc_pages[RPCSVC_MAXPAGES_MAX];
 };
 
 /*
@@ -242,7 +242,7 @@ struct svc_rdma_send_ctxt {
 	void			*sc_xprt_buf;
 	int			sc_page_count;
 	int			sc_cur_sge_no;
-	struct page		*sc_pages[RPCSVC_MAXPAGES];
+	struct page		*sc_pages[RPCSVC_MAXPAGES_MAX];
 	struct ib_sge		sc_sges[];
 };
 
include/linux/sunrpc/svcsock.h +1 -1
index 7c78ec6356b92..6c6bcc82685a3 100644
@@ -40,7 +40,7 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
-	struct page *		sk_pages[RPCSVC_MAXPAGES];	/* received data */
+	struct page *		sk_pages[RPCSVC_MAXPAGES_MAX];	/* received data */
 };
 
 static inline u32 svc_sock_reclen(struct svc_sock *svsk)
#63 lore raw

Re: [RFC PATCH v1 21/57] sunrpc: Remove PAGE_SIZE compile-time constant assumption

Quoted 30 lines · Ryan Roberts

+ Chuck Lever, Jeff Layton

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 19 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated array sizes in various structs to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/sunrpc/svc.h      | 8 +++++---
 include/linux/sunrpc/svc_rdma.h | 4 ++--
 include/linux/sunrpc/svcsock.h  | 2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)
Quoted 10 lines

include/linux/sunrpc/svc.h extern u32 svc_max_payload(const struct svc_rqst *rqstp); · line 164

Quoted 10 lines
include/linux/sunrpc/svc.h +2 -0
index a7d0406b9ef59..dda44018b8f36 100644
@@ -160,6 +160,8 @@ extern u32 svc_max_payload(const struct svc_rqst *rqstp);
  */
 #define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE-1)/PAGE_SIZE \
 				+ 2 + 1)
+#define RPCSVC_MAXPAGES_MAX	((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/PAGE_SIZE_MIN \
+				+ 2 + 1)

There is already a "MAX" in the name, so adding this new macro seems superfluous to me. Can we get away with simply updating the "RPCSVC_MAXPAGES" macro, instead of adding this new one?

Quoted 56 lines
Quoted 55 lines
include/linux/sunrpc/svc.h +3 -3
 /*
  * The context of a single thread, including the request currently being
@@ -190,14 +192,14 @@ struct svc_rqst {
 	struct xdr_stream	rq_res_stream;
 	struct page		*rq_scratch_page;
 	struct xdr_buf		rq_res;
-	struct page		*rq_pages[RPCSVC_MAXPAGES + 1];
+	struct page		*rq_pages[RPCSVC_MAXPAGES_MAX + 1];
 	struct page *		*rq_respages;	/* points into rq_pages */
 	struct page *		*rq_next_page; /* next reply page to use */
 	struct page *		*rq_page_end;  /* one past the last page */
 
 	struct folio_batch	rq_fbatch;
-	struct kvec		rq_vec[RPCSVC_MAXPAGES]; /* generally useful.. */
-	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES];
+	struct kvec		rq_vec[RPCSVC_MAXPAGES_MAX]; /* generally useful.. */
+	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES_MAX];
 
 	__be32			rq_xid;		/* transmission id */
 	u32			rq_prog;	/* program number */
include/linux/sunrpc/svc_rdma.h +2 -2
index d33bab33099ab..7c6441e8d6f7a 100644
@@ -200,7 +200,7 @@ struct svc_rdma_recv_ctxt {
 	struct svc_rdma_pcl	rc_reply_pcl;
 
 	unsigned int		rc_page_count;
-	struct page		*rc_pages[RPCSVC_MAXPAGES];
+	struct page		*rc_pages[RPCSVC_MAXPAGES_MAX];
 };
 
 /*
@@ -242,7 +242,7 @@ struct svc_rdma_send_ctxt {
 	void			*sc_xprt_buf;
 	int			sc_page_count;
 	int			sc_cur_sge_no;
-	struct page		*sc_pages[RPCSVC_MAXPAGES];
+	struct page		*sc_pages[RPCSVC_MAXPAGES_MAX];
 	struct ib_sge		sc_sges[];
 };
 
include/linux/sunrpc/svcsock.h +1 -1
index 7c78ec6356b92..6c6bcc82685a3 100644
@@ -40,7 +40,7 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
-	struct page *		sk_pages[RPCSVC_MAXPAGES];	/* received data */
+	struct page *		sk_pages[RPCSVC_MAXPAGES_MAX];	/* received data */
 };
 
 static inline u32 svc_sock_reclen(struct svc_sock *svsk)
Signature · 1 line
Chuck Lever
maintainer
#64 lore raw

Re: [RFC PATCH v1 21/57] sunrpc: Remove PAGE_SIZE compile-time constant assumption

Quoted 31 lines · Chuck Lever
Quoted 30 lines · Ryan Roberts

+ Chuck Lever, Jeff Layton

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 19 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated array sizes in various structs to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/sunrpc/svc.h      | 8 +++++---
 include/linux/sunrpc/svc_rdma.h | 4 ++--
 include/linux/sunrpc/svcsock.h  | 2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)
Quoted 15 lines
Quoted 10 lines

include/linux/sunrpc/svc.h extern u32 svc_max_payload(const struct svc_rqst *rqstp); · line 164

Quoted 10 lines
include/linux/sunrpc/svc.h +2 -0
index a7d0406b9ef59..dda44018b8f36 100644
@@ -160,6 +160,8 @@ extern u32 svc_max_payload(const struct svc_rqst *rqstp);
  */
 #define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE-1)/PAGE_SIZE \
 				+ 2 + 1)
+#define RPCSVC_MAXPAGES_MAX	((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/PAGE_SIZE_MIN \
+				+ 2 + 1)

There is already a "MAX" in the name, so adding this new macro seems superfluous to me. Can we get away with simply updating the "RPCSVC_MAXPAGES" macro, instead of adding this new one?

+1 that was my thinking too. This is mostly just used to size arrays, so we might as well just change the existing macro.

With 64k pages we probably wouldn't need arrays as long as these will be. Fixing those array sizes to be settable at runtime though is not a trivial project though.

Quoted 58 lines
Quoted 57 lines
Quoted 56 lines
include/linux/sunrpc/svc.h +3 -3
 /*
  * The context of a single thread, including the request currently being
@@ -190,14 +192,14 @@ struct svc_rqst {
 	struct xdr_stream	rq_res_stream;
 	struct page		*rq_scratch_page;
 	struct xdr_buf		rq_res;
-	struct page		*rq_pages[RPCSVC_MAXPAGES + 1];
+	struct page		*rq_pages[RPCSVC_MAXPAGES_MAX + 1];
 	struct page *		*rq_respages;	/* points into rq_pages */
 	struct page *		*rq_next_page; /* next reply page to use */
 	struct page *		*rq_page_end;  /* one past the last page */
 
 	struct folio_batch	rq_fbatch;
-	struct kvec		rq_vec[RPCSVC_MAXPAGES]; /* generally useful.. */
-	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES];
+	struct kvec		rq_vec[RPCSVC_MAXPAGES_MAX]; /* generally useful.. */
+	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES_MAX];
 
 	__be32			rq_xid;		/* transmission id */
 	u32			rq_prog;	/* program number */
include/linux/sunrpc/svc_rdma.h +2 -2
index d33bab33099ab..7c6441e8d6f7a 100644
@@ -200,7 +200,7 @@ struct svc_rdma_recv_ctxt {
 	struct svc_rdma_pcl	rc_reply_pcl;
 
 	unsigned int		rc_page_count;
-	struct page		*rc_pages[RPCSVC_MAXPAGES];
+	struct page		*rc_pages[RPCSVC_MAXPAGES_MAX];
 };
 
 /*
@@ -242,7 +242,7 @@ struct svc_rdma_send_ctxt {
 	void			*sc_xprt_buf;
 	int			sc_page_count;
 	int			sc_cur_sge_no;
-	struct page		*sc_pages[RPCSVC_MAXPAGES];
+	struct page		*sc_pages[RPCSVC_MAXPAGES_MAX];
 	struct ib_sge		sc_sges[];
 };
 
include/linux/sunrpc/svcsock.h +1 -1
index 7c78ec6356b92..6c6bcc82685a3 100644
@@ -40,7 +40,7 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
-	struct page *		sk_pages[RPCSVC_MAXPAGES];	/* received data */
+	struct page *		sk_pages[RPCSVC_MAXPAGES_MAX];	/* received data */
 };
 
 static inline u32 svc_sock_reclen(struct svc_sock *svsk)
Signature · 1 line
Jeff Layton <[email protected]>
author reviewer
#65 lore raw

Re: [RFC PATCH v1 21/57] sunrpc: Remove PAGE_SIZE compile-time constant assumption

Quoted 48 lines · Jeff Layton
Quoted 31 lines · Chuck Lever
Quoted 30 lines · Ryan Roberts

+ Chuck Lever, Jeff Layton

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 19 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated array sizes in various structs to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/sunrpc/svc.h      | 8 +++++---
 include/linux/sunrpc/svc_rdma.h | 4 ++--
 include/linux/sunrpc/svcsock.h  | 2 +-
 3 files changed, 8 insertions(+), 6 deletions(-)
Quoted 15 lines
Quoted 10 lines

include/linux/sunrpc/svc.h extern u32 svc_max_payload(const struct svc_rqst *rqstp); · line 164

Quoted 10 lines
include/linux/sunrpc/svc.h +2 -0
index a7d0406b9ef59..dda44018b8f36 100644
@@ -160,6 +160,8 @@ extern u32 svc_max_payload(const struct svc_rqst *rqstp);
  */
 #define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE-1)/PAGE_SIZE \
 				+ 2 + 1)
+#define RPCSVC_MAXPAGES_MAX	((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/PAGE_SIZE_MIN \
+				+ 2 + 1)

There is already a "MAX" in the name, so adding this new macro seems superfluous to me. Can we get away with simply updating the "RPCSVC_MAXPAGES" macro, instead of adding this new one?

Quoted 2 lines

+1 that was my thinking too. This is mostly just used to size arrays, so we might as well just change the existing macro.

I agree, its not the prettiest. I was (incorrectly) assuming you would want to continue to limit the number of actual pages at runtime based on the in-use page size. That said, looking again at the code, RPCSVC_MAXPAGES never actually gets used to dynamically allocate any memory. So I propose to just do the following:

#define RPCSVC_MAXPAGES		((RPCSVC_MAXPAYLOAD+PAGE_SIZE_MIN-1)/
						PAGE_SIZE_MIN + 2 + 1)

That will be 259 in practice (assuming PAGE_SIZE_MIN=4K).

Quoted 4 lines

With 64k pages we probably wouldn't need arrays as long as these will be. Fixing those array sizes to be settable at runtime though is not a trivial project though.

Indeed. Hopefully the above is sufficient.

Thanks for the review!
Ryan

Quoted 60 lines
Quoted 59 lines
Quoted 58 lines
Quoted 57 lines
include/linux/sunrpc/svc.h +3 -3
 /*
  * The context of a single thread, including the request currently being
@@ -190,14 +192,14 @@ struct svc_rqst {
 	struct xdr_stream	rq_res_stream;
 	struct page		*rq_scratch_page;
 	struct xdr_buf		rq_res;
-	struct page		*rq_pages[RPCSVC_MAXPAGES + 1];
+	struct page		*rq_pages[RPCSVC_MAXPAGES_MAX + 1];
 	struct page *		*rq_respages;	/* points into rq_pages */
 	struct page *		*rq_next_page; /* next reply page to use */
 	struct page *		*rq_page_end;  /* one past the last page */
 
 	struct folio_batch	rq_fbatch;
-	struct kvec		rq_vec[RPCSVC_MAXPAGES]; /* generally useful.. */
-	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES];
+	struct kvec		rq_vec[RPCSVC_MAXPAGES_MAX]; /* generally useful.. */
+	struct bio_vec		rq_bvec[RPCSVC_MAXPAGES_MAX];
 
 	__be32			rq_xid;		/* transmission id */
 	u32			rq_prog;	/* program number */
include/linux/sunrpc/svc_rdma.h +2 -2
index d33bab33099ab..7c6441e8d6f7a 100644
@@ -200,7 +200,7 @@ struct svc_rdma_recv_ctxt {
 	struct svc_rdma_pcl	rc_reply_pcl;
 
 	unsigned int		rc_page_count;
-	struct page		*rc_pages[RPCSVC_MAXPAGES];
+	struct page		*rc_pages[RPCSVC_MAXPAGES_MAX];
 };
 
 /*
@@ -242,7 +242,7 @@ struct svc_rdma_send_ctxt {
 	void			*sc_xprt_buf;
 	int			sc_page_count;
 	int			sc_cur_sge_no;
-	struct page		*sc_pages[RPCSVC_MAXPAGES];
+	struct page		*sc_pages[RPCSVC_MAXPAGES_MAX];
 	struct ib_sge		sc_sges[];
 };
 
include/linux/sunrpc/svcsock.h +1 -1
index 7c78ec6356b92..6c6bcc82685a3 100644
@@ -40,7 +40,7 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
-	struct page *		sk_pages[RPCSVC_MAXPAGES];	/* received data */
+	struct page *		sk_pages[RPCSVC_MAXPAGES_MAX];	/* received data */
 };
 
 static inline u32 svc_sock_reclen(struct svc_sock *svsk)
author reviewer
#66 lore raw

RFC PATCH 22/57 sound: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 sound/soc/soc-utils.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/soc-utils.c +2 -2
index 303823dc45d7a..74e1bc1087de4 100644
@@ -98,7 +98,7 @@ int snd_soc_tdm_params_to_bclk(const struct snd_pcm_hw_params *params,
 }
 EXPORT_SYMBOL_GPL(snd_soc_tdm_params_to_bclk);
 
-static const struct snd_pcm_hardware dummy_dma_hardware = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct snd_pcm_hardware, dummy_dma_hardware, {
 	/* Random values to keep userspace happy when checking constraints */
 	.info			= SNDRV_PCM_INFO_INTERLEAVED |
 				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
@@ -107,7 +107,7 @@ static const struct snd_pcm_hardware dummy_dma_hardware = {
 	.period_bytes_max	= PAGE_SIZE*2,
 	.periods_min		= 2,
 	.periods_max		= 128,
-};
+});
 
 
 static const struct snd_soc_component_driver dummy_platform;
Signature · 1 line
2.43.0
maintainer
#67 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

Quoted 3 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Please submit patches using subject lines reflecting the style for the subsystem, this makes it easier for people to identify relevant patches. Look at what existing commits in the area you're changing are doing and make sure your subject lines visually resemble what they're doing. There's no need to resubmit to fix this alone.

Quoted 3 lines

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

As documented in submitting-patches.rst please send patches to the maintainers for the code you would like to change. The normal kernel workflow is that people apply patches from their inboxes, if they aren't copied they are likely to not see the patch at all and it is much more difficult to apply patches.

sound/soc/soc-utils.c static const struct snd_pcm_hardware dummy_dma_hardware = { · line 110

Quoted 11 lines
sound/soc/soc-utils.c +2 -2
-static const struct snd_pcm_hardware dummy_dma_hardware = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct snd_pcm_hardware, dummy_dma_hardware, {
 	/* Random values to keep userspace happy when checking constraints */
 	.info			= SNDRV_PCM_INFO_INTERLEAVED |
 				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
@@ -107,7 +107,7 @@ static const struct snd_pcm_hardware dummy_dma_hardware = {
 	.period_bytes_max	= PAGE_SIZE*2,
 	.periods_min		= 2,
 	.periods_max		= 128,
-};
+});

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

author reviewer
#68 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

Quoted 10 lines · Mark Brown
Quoted 3 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Please submit patches using subject lines reflecting the style for the subsystem, this makes it easier for people to identify relevant patches. Look at what existing commits in the area you're changing are doing and make sure your subject lines visually resemble what they're doing. There's no need to resubmit to fix this alone.

No problem, will fix this in the next round (where I anticipate sending more targetted serieses to maintainers).

Quoted 10 lines
Quoted 4 lines

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

As documented in submitting-patches.rst please send patches to the maintainers for the code you would like to change. The normal kernel workflow is that people apply patches from their inboxes, if they aren't copied they are likely to not see the patch at all and it is much more difficult to apply patches.

Sure. I think you're implying that you would have liked to be in To: for this patch? I went to quite a lot of trouble to ensure all maintainers were at least in the To: field for patches touching their code. But get_maintainer.pl lists you as a supporter, not a maintainer when I ran this patch through. Could you clarify what would have been the correct thing to do? I could include all reviewers and supporters as well as maintainers but then I'd be banging up against the limits for some of the patches.

Or perhaps I've misunderstood the point you're making here.

Quoted 16 lines

sound/soc/soc-utils.c static const struct snd_pcm_hardware dummy_dma_hardware = { · line 110

Quoted 12 lines
sound/soc/soc-utils.c +2 -2
-static const struct snd_pcm_hardware dummy_dma_hardware = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct snd_pcm_hardware, dummy_dma_hardware, {
 	/* Random values to keep userspace happy when checking constraints */
 	.info			= SNDRV_PCM_INFO_INTERLEAVED |
 				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
@@ -107,7 +107,7 @@ static const struct snd_pcm_hardware dummy_dma_hardware = {
 	.period_bytes_max	= PAGE_SIZE*2,
 	.periods_min		= 2,
 	.periods_max		= 128,
-};
+});

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

OK, so would that be:

	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE_MAX,      <<<<<
	.period_bytes_max	= PAGE_SIZE_MAX*2,    <<<<<
	.periods_min		= 2,
	.periods_max		= 128,

?

It's not really clear to me how all the parameters interact; the buffer size 128K, which, if PAGE_SIZE_MAX is 64K, would hold 1 period of the maximum size. But periods_min is 2. So not sure that works? Or perhaps I'm trying to apply too much meaning to the param names...

Thanks,
Ryan

#69 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

Quoted 27 lines · Ryan Roberts
Quoted 16 lines · Mark Brown

sound/soc/soc-utils.c static const struct snd_pcm_hardware dummy_dma_hardware = { · line 110

Quoted 11 lines · Ryan Roberts
sound/soc/soc-utils.c +2 -2
-static const struct snd_pcm_hardware dummy_dma_hardware = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct snd_pcm_hardware, dummy_dma_hardware, {
 	/* Random values to keep userspace happy when checking constraints */
 	.info			= SNDRV_PCM_INFO_INTERLEAVED |
 				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
@@ -107,7 +107,7 @@ static const struct snd_pcm_hardware dummy_dma_hardware = {
 	.period_bytes_max	= PAGE_SIZE*2,
 	.periods_min		= 2,
 	.periods_max		= 128,
-};
+});

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

OK, so would that be:

	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE_MAX,      <<<<<
	.period_bytes_max	= PAGE_SIZE_MAX*2,    <<<<<
	.periods_min		= 2,
	.periods_max		= 128,
Quoted 6 lines

?

It's not really clear to me how all the parameters interact; the buffer size 128K, which, if PAGE_SIZE_MAX is 64K, would hold 1 period of the maximum size. But periods_min is 2. So not sure that works? Or perhaps I'm trying to apply too much meaning to the param names...

Right, when PAGE_SIZE_MAX is 64k, 128k won't be used because of the constrant of periods_min=2.

As Mark mentioned, here the actual size itself doesn't matter much. So I suppose it'd be even simpler to define just 4096 and 4096 * 2 for period_bytes_min and *_max instead of sticking with PAGE_SIZE. Then it would become platform-agnostic, too.

thanks,

Takashi

author reviewer
#70 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

Quoted 36 lines · Takashi Iwai
Quoted 27 lines · Ryan Roberts
Quoted 16 lines · Mark Brown

sound/soc/soc-utils.c static const struct snd_pcm_hardware dummy_dma_hardware = { · line 110

Quoted 11 lines · Ryan Roberts
sound/soc/soc-utils.c +2 -2
-static const struct snd_pcm_hardware dummy_dma_hardware = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct snd_pcm_hardware, dummy_dma_hardware, {
 	/* Random values to keep userspace happy when checking constraints */
 	.info			= SNDRV_PCM_INFO_INTERLEAVED |
 				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
@@ -107,7 +107,7 @@ static const struct snd_pcm_hardware dummy_dma_hardware = {
 	.period_bytes_max	= PAGE_SIZE*2,
 	.periods_min		= 2,
 	.periods_max		= 128,
-};
+});

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

OK, so would that be:

	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE_MAX,      <<<<<
	.period_bytes_max	= PAGE_SIZE_MAX*2,    <<<<<
	.periods_min		= 2,
	.periods_max		= 128,
Quoted 6 lines

?

It's not really clear to me how all the parameters interact; the buffer size 128K, which, if PAGE_SIZE_MAX is 64K, would hold 1 period of the maximum size. But periods_min is 2. So not sure that works? Or perhaps I'm trying to apply too much meaning to the param names...

Quoted 7 lines

Right, when PAGE_SIZE_MAX is 64k, 128k won't be used because of the constrant of periods_min=2.

As Mark mentioned, here the actual size itself doesn't matter much. So I suppose it'd be even simpler to define just 4096 and 4096 * 2 for period_bytes_min and *_max instead of sticking with PAGE_SIZE. Then it would become platform-agnostic, too.

OK great I'll set these to 4096 and 4096*2 for the next version.

Thanks for the feedback!

Quoted 5 lines

thanks,

Takashi

maintainer
#71 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts
Quoted 13 lines · Ryan Roberts
Quoted 11 lines · Mark Brown
Quoted 3 lines · Ryan Roberts

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

As documented in submitting-patches.rst please send patches to the maintainers for the code you would like to change. The normal kernel workflow is that people apply patches from their inboxes, if they aren't copied they are likely to not see the patch at all and it is much more difficult to apply patches.

Quoted 7 lines

Sure. I think you're implying that you would have liked to be in To: for this patch? I went to quite a lot of trouble to ensure all maintainers were at least in the To: field for patches touching their code. But get_maintainer.pl lists you as a supporter, not a maintainer when I ran this patch through. Could you clarify what would have been the correct thing to do? I could include all reviewers and supporters as well as maintainers but then I'd be banging up against the limits for some of the patches.

The entry in MAINTAINERS for me is a M:, supporter is just the usual get_maintainers noise. Supported is exactly equivalent to a maintainer. Generally if you're going to filter people you should be filtering less specific matches out rather than more and if you're looking to filter very aggressively look at who actually commits changes to whatever you're trying to change, less specific maintainers will generally delegate down to the more specific ones.

Quoted 12 lines
Quoted 3 lines

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

OK, so would that be:

	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE_MAX,      <<<<<
	.period_bytes_max	= PAGE_SIZE_MAX*2,    <<<<<
	.periods_min		= 2,
	.periods_max		= 128,
Quoted 4 lines

It's not really clear to me how all the parameters interact; the buffer size 128K, which, if PAGE_SIZE_MAX is 64K, would hold 1 period of the maximum size. But periods_min is 2. So not sure that works? Or perhaps I'm trying to apply too much meaning to the param names...

Like Takashi says just using absolute numbers here is probably just as sensible, the numbers are there to stop userspace tripping over itself but like I say it shouldn't ever get as far as actually using them for anything. So long as we end up with some numbers that don't need any late init patching the specifics aren't super important, the use of PAGE_SIZE was kind of random.

author reviewer
#72 lore raw

Re: [RFC PATCH v1 22/57] sound: Remove PAGE_SIZE compile-time constant assumption

Quoted 22 lines · Mark Brown
Quoted 13 lines · Ryan Roberts
Quoted 11 lines · Mark Brown
Quoted 3 lines · Ryan Roberts

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

As documented in submitting-patches.rst please send patches to the maintainers for the code you would like to change. The normal kernel workflow is that people apply patches from their inboxes, if they aren't copied they are likely to not see the patch at all and it is much more difficult to apply patches.

Quoted 7 lines

Sure. I think you're implying that you would have liked to be in To: for this patch? I went to quite a lot of trouble to ensure all maintainers were at least in the To: field for patches touching their code. But get_maintainer.pl lists you as a supporter, not a maintainer when I ran this patch through. Could you clarify what would have been the correct thing to do? I could include all reviewers and supporters as well as maintainers but then I'd be banging up against the limits for some of the patches.

Quoted 2 lines

The entry in MAINTAINERS for me is a M:, supporter is just the usual get_maintainers noise. Supported is exactly equivalent to a maintainer.

Ugh, In my head I always thought "supporter" was somebody who engaged with the subsystem but did not have an official role (like a football supporter). But now that I've gone and read the MAINTAINERS file, I see it's actually referring to status (supported vs maintained). Sorry about this. Due to this buggy filtering, I've missed a few others off other patches in this series. I'll fix that by forwarding to them.

Quoted 23 lines

Generally if you're going to filter people you should be filtering less specific matches out rather than more and if you're looking to filter very aggressively look at who actually commits changes to whatever you're trying to change, less specific maintainers will generally delegate down to the more specific ones.

Quoted 12 lines
Quoted 3 lines

It's probably better to just use PAGE_SIZE_MAX here and avoid the deferred patching, like the comment says we don't particularly care what the value actually is here given that it's a dummy.

OK, so would that be:

	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE_MAX,      <<<<<
	.period_bytes_max	= PAGE_SIZE_MAX*2,    <<<<<
	.periods_min		= 2,
	.periods_max		= 128,
Quoted 4 lines

It's not really clear to me how all the parameters interact; the buffer size 128K, which, if PAGE_SIZE_MAX is 64K, would hold 1 period of the maximum size. But periods_min is 2. So not sure that works? Or perhaps I'm trying to apply too much meaning to the param names...

Quoted 6 lines

Like Takashi says just using absolute numbers here is probably just as sensible, the numbers are there to stop userspace tripping over itself but like I say it shouldn't ever get as far as actually using them for anything. So long as we end up with some numbers that don't need any late init patching the specifics aren't super important, the use of PAGE_SIZE was kind of random.

OK, I'll post a respin of this patch independently of the rest of the series, given it no longer has a dependency.

Thanks,
Ryan

author reviewer
#73 lore raw

RFC PATCH 23/57 net: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Define NLMSG_GOODSIZE using min() instead of ifdeffery. This will now evaluate to a compile-time constant for compile-time page size, but evaluate at run-time when using boot-time page size.

Rework NAPI small page frag infrastructure so that for boot-time page size it is compiled in if 4K page size is in the possible range, but defer deciding to use it to run time when the page size is known. No change for compile-time page size case.

Resize cache_defer_hash[] array for PAGE_SIZE_MAX.

Convert a complex BUILD_BUG_ON() to runtime BUG_ON().

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/netlink.h    | 6 +-----
 net/core/hotdata.c         | 4 ++--
 net/core/skbuff.c          | 4 ++--
 net/core/sysctl_net_core.c | 2 +-
 net/sunrpc/cache.c         | 3 ++-
 net/unix/af_unix.c         | 2 +-
 6 files changed, 9 insertions(+), 12 deletions(-)
include/linux/netlink.h +1 -5
index b332c2048c755..ffa1e94111f89 100644
@@ -267,11 +267,7 @@ netlink_skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
  *	use enormous buffer sizes on recvmsg() calls just to avoid
  *	MSG_TRUNC when PAGE_SIZE is very large.
  */
-#if PAGE_SIZE < 8192UL
-#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(PAGE_SIZE)
-#else
-#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(8192UL)
-#endif
+#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(min(PAGE_SIZE, 8192UL))
 
 #define NLMSG_DEFAULT_SIZE (NLMSG_GOODSIZE - NLMSG_HDRLEN)
 
net/core/hotdata.c +2 -2
index d0aaaaa556f22..e1f30e87ba6e9 100644
@@ -5,7 +5,7 @@
 #include <net/hotdata.h>
 #include <net/proto_memory.h>
 
-struct net_hotdata net_hotdata __cacheline_aligned = {
+__DEFINE_GLOBAL_PAGE_SIZE_VAR(struct net_hotdata, net_hotdata, __cacheline_aligned, {
 	.offload_base = LIST_HEAD_INIT(net_hotdata.offload_base),
 	.ptype_all = LIST_HEAD_INIT(net_hotdata.ptype_all),
 	.gro_normal_batch = 8,
@@ -21,5 +21,5 @@ struct net_hotdata net_hotdata __cacheline_aligned = {
 	.sysctl_max_skb_frags = MAX_SKB_FRAGS,
 	.sysctl_skb_defer_max = 64,
 	.sysctl_mem_pcpu_rsv = SK_MEMORY_PCPU_RESERVE
-};
+});
 EXPORT_SYMBOL(net_hotdata);
net/core/skbuff.c +2 -2
index 83f8cd8aa2d16..b6c8eee0cc74b 100644
@@ -219,9 +219,9 @@ static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
 #define NAPI_SKB_CACHE_BULK	16
 #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
 
-#if PAGE_SIZE == SZ_4K
+#if PAGE_SIZE_MIN <= SZ_4K && SZ_4K <= PAGE_SIZE_MAX
 
-#define NAPI_HAS_SMALL_PAGE_FRAG	1
+#define NAPI_HAS_SMALL_PAGE_FRAG	(PAGE_SIZE == SZ_4K)
 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	((nc).pfmemalloc)
 
 /* specialized page frag allocator using a single order 0 page
net/core/sysctl_net_core.c +1 -1
index 86a2476678c48..a7a2eb7581bd1 100644
@@ -33,7 +33,7 @@ static int int_3600 = 3600;
 static int min_sndbuf = SOCK_MIN_SNDBUF;
 static int min_rcvbuf = SOCK_MIN_RCVBUF;
 static int max_skb_frags = MAX_SKB_FRAGS;
-static int min_mem_pcpu_rsv = SK_MEMORY_PCPU_RESERVE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(int, min_mem_pcpu_rsv, SK_MEMORY_PCPU_RESERVE);
 
 static int net_msg_warn;	/* Unused, but still a sysctl */
 
net/sunrpc/cache.c +2 -1
index 95ff747061046..4e682c0cd7586 100644
@@ -573,13 +573,14 @@ EXPORT_SYMBOL_GPL(cache_purge);
  */
 
 #define	DFR_HASHSIZE	(PAGE_SIZE/sizeof(struct list_head))
+#define	DFR_HASHSIZE_MAX (PAGE_SIZE_MAX/sizeof(struct list_head))
 #define	DFR_HASH(item)	((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)
 
 #define	DFR_MAX	300	/* ??? */
 
 static DEFINE_SPINLOCK(cache_defer_lock);
 static LIST_HEAD(cache_defer_list);
-static struct hlist_head cache_defer_hash[DFR_HASHSIZE];
+static struct hlist_head cache_defer_hash[DFR_HASHSIZE_MAX];
 static int cache_defer_cnt;
 
 static void __unhash_deferred_req(struct cache_deferred_req *dreq)
net/unix/af_unix.c +1 -1
index 0be0dcb07f7b6..1cf9f583358af 100644
@@ -2024,7 +2024,7 @@ static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
 				 MAX_SKB_FRAGS * PAGE_SIZE);
 		data_len = PAGE_ALIGN(data_len);
 
-		BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
+		BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
 	}
 
 	skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
Signature · 1 line
2.43.0
author reviewer
#74 lore raw

Re: [RFC PATCH v1 23/57] net: Remove PAGE_SIZE compile-time constant assumption

+ Chuck Lever, Jeff Layton

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 135 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Define NLMSG_GOODSIZE using min() instead of ifdeffery. This will now evaluate to a compile-time constant for compile-time page size, but evaluate at run-time when using boot-time page size.

Rework NAPI small page frag infrastructure so that for boot-time page size it is compiled in if 4K page size is in the possible range, but defer deciding to use it to run time when the page size is known. No change for compile-time page size case.

Resize cache_defer_hash[] array for PAGE_SIZE_MAX.

Convert a complex BUILD_BUG_ON() to runtime BUG_ON().

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 include/linux/netlink.h    | 6 +-----
 net/core/hotdata.c         | 4 ++--
 net/core/skbuff.c          | 4 ++--
 net/core/sysctl_net_core.c | 2 +-
 net/sunrpc/cache.c         | 3 ++-
 net/unix/af_unix.c         | 2 +-
 6 files changed, 9 insertions(+), 12 deletions(-)
include/linux/netlink.h +1 -5
index b332c2048c755..ffa1e94111f89 100644
@@ -267,11 +267,7 @@ netlink_skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
  *	use enormous buffer sizes on recvmsg() calls just to avoid
  *	MSG_TRUNC when PAGE_SIZE is very large.
  */
-#if PAGE_SIZE < 8192UL
-#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(PAGE_SIZE)
-#else
-#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(8192UL)
-#endif
+#define NLMSG_GOODSIZE	SKB_WITH_OVERHEAD(min(PAGE_SIZE, 8192UL))
 
 #define NLMSG_DEFAULT_SIZE (NLMSG_GOODSIZE - NLMSG_HDRLEN)
 
net/core/hotdata.c +2 -2
index d0aaaaa556f22..e1f30e87ba6e9 100644
@@ -5,7 +5,7 @@
 #include <net/hotdata.h>
 #include <net/proto_memory.h>
 
-struct net_hotdata net_hotdata __cacheline_aligned = {
+__DEFINE_GLOBAL_PAGE_SIZE_VAR(struct net_hotdata, net_hotdata, __cacheline_aligned, {
 	.offload_base = LIST_HEAD_INIT(net_hotdata.offload_base),
 	.ptype_all = LIST_HEAD_INIT(net_hotdata.ptype_all),
 	.gro_normal_batch = 8,
@@ -21,5 +21,5 @@ struct net_hotdata net_hotdata __cacheline_aligned = {
 	.sysctl_max_skb_frags = MAX_SKB_FRAGS,
 	.sysctl_skb_defer_max = 64,
 	.sysctl_mem_pcpu_rsv = SK_MEMORY_PCPU_RESERVE
-};
+});
 EXPORT_SYMBOL(net_hotdata);
net/core/skbuff.c +2 -2
index 83f8cd8aa2d16..b6c8eee0cc74b 100644
@@ -219,9 +219,9 @@ static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
 #define NAPI_SKB_CACHE_BULK	16
 #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
 
-#if PAGE_SIZE == SZ_4K
+#if PAGE_SIZE_MIN <= SZ_4K && SZ_4K <= PAGE_SIZE_MAX
 
-#define NAPI_HAS_SMALL_PAGE_FRAG	1
+#define NAPI_HAS_SMALL_PAGE_FRAG	(PAGE_SIZE == SZ_4K)
 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	((nc).pfmemalloc)
 
 /* specialized page frag allocator using a single order 0 page
net/core/sysctl_net_core.c +1 -1
index 86a2476678c48..a7a2eb7581bd1 100644
@@ -33,7 +33,7 @@ static int int_3600 = 3600;
 static int min_sndbuf = SOCK_MIN_SNDBUF;
 static int min_rcvbuf = SOCK_MIN_RCVBUF;
 static int max_skb_frags = MAX_SKB_FRAGS;
-static int min_mem_pcpu_rsv = SK_MEMORY_PCPU_RESERVE;
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(int, min_mem_pcpu_rsv, SK_MEMORY_PCPU_RESERVE);
 
 static int net_msg_warn;	/* Unused, but still a sysctl */
 
net/sunrpc/cache.c +2 -1
index 95ff747061046..4e682c0cd7586 100644
@@ -573,13 +573,14 @@ EXPORT_SYMBOL_GPL(cache_purge);
  */
 
 #define	DFR_HASHSIZE	(PAGE_SIZE/sizeof(struct list_head))
+#define	DFR_HASHSIZE_MAX (PAGE_SIZE_MAX/sizeof(struct list_head))
 #define	DFR_HASH(item)	((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)
 
 #define	DFR_MAX	300	/* ??? */
 
 static DEFINE_SPINLOCK(cache_defer_lock);
 static LIST_HEAD(cache_defer_list);
-static struct hlist_head cache_defer_hash[DFR_HASHSIZE];
+static struct hlist_head cache_defer_hash[DFR_HASHSIZE_MAX];
 static int cache_defer_cnt;
 
 static void __unhash_deferred_req(struct cache_deferred_req *dreq)
net/unix/af_unix.c +1 -1
index 0be0dcb07f7b6..1cf9f583358af 100644
@@ -2024,7 +2024,7 @@ static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
 				 MAX_SKB_FRAGS * PAGE_SIZE);
 		data_len = PAGE_ALIGN(data_len);
 
-		BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
+		BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
 	}
 
 	skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
author reviewer
#75 lore raw

RFC PATCH 24/57 net: fec: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Refactored "struct fec_enet_priv_rx_q" to use a flexible array member for "rx_skb_info", since its length depends on PAGE_SIZE.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/freescale/fec.h      | 3 ++-
 drivers/net/ethernet/freescale/fec_main.c | 5 +++--
 2 files changed, 5 insertions(+), 3 deletions(-)
drivers/net/ethernet/freescale/fec.h +2 -1
index a19cb2a786fd2..afc8b3f360555 100644
@@ -571,7 +571,6 @@ struct fec_enet_priv_tx_q {
 
 struct fec_enet_priv_rx_q {
 	struct bufdesc_prop bd;
-	struct  fec_enet_priv_txrx_info rx_skb_info[RX_RING_SIZE];
 
 	/* page_pool */
 	struct page_pool *page_pool;
@@ -580,6 +579,8 @@ struct fec_enet_priv_rx_q {
 
 	/* rx queue number, in the range 0-7 */
 	u8 id;
+
+	struct  fec_enet_priv_txrx_info rx_skb_info[];
 };
 
 struct fec_stop_mode_gpr {
drivers/net/ethernet/freescale/fec_main.c +3 -2
index a923cb95cdc62..b9214c12d537e 100644
@@ -3339,6 +3339,8 @@ static int fec_enet_alloc_queue(struct net_device *ndev)
 	int i;
 	int ret = 0;
 	struct fec_enet_priv_tx_q *txq;
+	size_t rxq_sz = struct_size(fep->rx_queue[0], rx_skb_info, RX_RING_SIZE);
+
 
 	for (i = 0; i < fep->num_tx_queues; i++) {
 		txq = kzalloc(sizeof(*txq), GFP_KERNEL);
@@ -3364,8 +3366,7 @@ static int fec_enet_alloc_queue(struct net_device *ndev)
 	}
 
 	for (i = 0; i < fep->num_rx_queues; i++) {
-		fep->rx_queue[i] = kzalloc(sizeof(*fep->rx_queue[i]),
-					   GFP_KERNEL);
+		fep->rx_queue[i] = kzalloc(rxq_sz, GFP_KERNEL);
 		if (!fep->rx_queue[i]) {
 			ret = -ENOMEM;
 			goto alloc_failed;
Signature · 1 line
2.43.0
author reviewer
#76 lore raw

RFC PATCH 25/57 net: marvell: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated sky2 "struct rx_ring_info" member frag_addr[] to contain enough entries for the smallest supported page size.

Updated mvneta "struct mvneta_tx_queue" members tso_hdrs[] and tso_hdrs_phys[] to contain enough entries for the smallest supported page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/marvell/mvneta.c | 9 ++++++---
 drivers/net/ethernet/marvell/sky2.h   | 2 +-
 2 files changed, 7 insertions(+), 4 deletions(-)
drivers/net/ethernet/marvell/mvneta.c +6 -3
index 41894834fb53c..f3ac371d8f3a7 100644
@@ -346,12 +346,15 @@
 
 /* The size of a TSO header page */
 #define MVNETA_TSO_PAGE_SIZE (2 * PAGE_SIZE)
+#define MVNETA_TSO_PAGE_SIZE_MIN (2 * PAGE_SIZE_MIN)
 
 /* Number of TSO headers per page. This should be a power of 2 */
 #define MVNETA_TSO_PER_PAGE (MVNETA_TSO_PAGE_SIZE / TSO_HEADER_SIZE)
+#define MVNETA_TSO_PER_PAGE_MIN (MVNETA_TSO_PAGE_SIZE_MIN / TSO_HEADER_SIZE)
 
 /* Maximum number of TSO header pages */
 #define MVNETA_MAX_TSO_PAGES (MVNETA_MAX_TXD / MVNETA_TSO_PER_PAGE)
+#define MVNETA_MAX_TSO_PAGES_MAX (MVNETA_MAX_TXD / MVNETA_TSO_PER_PAGE_MIN)
 
 /* descriptor aligned size */
 #define MVNETA_DESC_ALIGNED_SIZE	32
@@ -696,10 +699,10 @@ struct mvneta_tx_queue {
 	int next_desc_to_proc;
 
 	/* DMA buffers for TSO headers */
-	char *tso_hdrs[MVNETA_MAX_TSO_PAGES];
+	char *tso_hdrs[MVNETA_MAX_TSO_PAGES_MAX];
 
 	/* DMA address of TSO headers */
-	dma_addr_t tso_hdrs_phys[MVNETA_MAX_TSO_PAGES];
+	dma_addr_t tso_hdrs_phys[MVNETA_MAX_TSO_PAGES_MAX];
 
 	/* Affinity mask for CPUs*/
 	cpumask_t affinity_mask;
@@ -5895,7 +5898,7 @@ static int __init mvneta_driver_init(void)
 {
 	int ret;
 
-	BUILD_BUG_ON_NOT_POWER_OF_2(MVNETA_TSO_PER_PAGE);
+	BUILD_BUG_ON_NOT_POWER_OF_2(MVNETA_TSO_PER_PAGE_MIN);
 
 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "net/mvneta:online",
 				      mvneta_cpu_online,
drivers/net/ethernet/marvell/sky2.h +1 -1
index 8d0bacf4e49cc..8ee73ae087dfc 100644
@@ -2195,7 +2195,7 @@ struct rx_ring_info {
 	struct sk_buff	*skb;
 	dma_addr_t	data_addr;
 	DEFINE_DMA_UNMAP_LEN(data_size);
-	dma_addr_t	frag_addr[ETH_JUMBO_MTU >> PAGE_SHIFT ?: 1];
+	dma_addr_t	frag_addr[ETH_JUMBO_MTU >> PAGE_SHIFT_MIN ?: 1];
 };
 
 enum flow_control {
Signature · 1 line
2.43.0
author reviewer
#77 lore raw

RFC PATCH 26/57 net: hns3: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert a CPP conditional to a C conditional. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/hisilicon/hns3/hns3_enet.h | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/net/ethernet/hisilicon/hns3/hns3_enet.h +1 -3
index d36c4ed16d8dd..5e675721b7364 100644
@@ -681,10 +681,8 @@ static inline bool hns3_nic_resetting(struct net_device *netdev)
 
 static inline unsigned int hns3_page_order(struct hns3_enet_ring *ring)
 {
-#if (PAGE_SIZE < 8192)
-	if (ring->buf_size > (PAGE_SIZE / 2))
+	if (PAGE_SIZE < 8192 && ring->buf_size > (PAGE_SIZE / 2))
 		return 1;
-#endif
 	return 0;
 }
 
Signature · 1 line
2.43.0
author reviewer
#78 lore raw

RFC PATCH 27/57 net: e1000: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/e1000/e1000_main.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/intel/e1000/e1000_main.c +2 -4
index ab7ae418d2948..cc14788f5bb04 100644
@@ -3553,12 +3553,10 @@ static int e1000_change_mtu(struct net_device *netdev, int new_mtu)
 
 	if (max_frame <= E1000_RXBUFFER_2048)
 		adapter->rx_buffer_len = E1000_RXBUFFER_2048;
-	else
-#if (PAGE_SIZE >= E1000_RXBUFFER_16384)
+	else if (PAGE_SIZE >= E1000_RXBUFFER_16384)
 		adapter->rx_buffer_len = E1000_RXBUFFER_16384;
-#elif (PAGE_SIZE >= E1000_RXBUFFER_4096)
+	else if (PAGE_SIZE >= E1000_RXBUFFER_4096)
 		adapter->rx_buffer_len = PAGE_SIZE;
-#endif
 
 	/* adjust allocation if LPE protects us, and we aren't using SBP */
 	if (!hw->tbi_compatibility_on &&
Signature · 1 line
2.43.0
author reviewer
#79 lore raw

Re: [RFC PATCH v1 27/57] net: e1000: Remove PAGE_SIZE compile-time constant assumption

+ Przemek Kitszel, Tony Nguyen

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 37 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/e1000/e1000_main.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/intel/e1000/e1000_main.c +2 -4
index ab7ae418d2948..cc14788f5bb04 100644
@@ -3553,12 +3553,10 @@ static int e1000_change_mtu(struct net_device *netdev, int new_mtu)
 
 	if (max_frame <= E1000_RXBUFFER_2048)
 		adapter->rx_buffer_len = E1000_RXBUFFER_2048;
-	else
-#if (PAGE_SIZE >= E1000_RXBUFFER_16384)
+	else if (PAGE_SIZE >= E1000_RXBUFFER_16384)
 		adapter->rx_buffer_len = E1000_RXBUFFER_16384;
-#elif (PAGE_SIZE >= E1000_RXBUFFER_4096)
+	else if (PAGE_SIZE >= E1000_RXBUFFER_4096)
 		adapter->rx_buffer_len = PAGE_SIZE;
-#endif
 
 	/* adjust allocation if LPE protects us, and we aren't using SBP */
 	if (!hw->tbi_compatibility_on &&
author reviewer
#80 lore raw

RFC PATCH 28/57 net: igbvf: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/igbvf/netdev.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/intel/igbvf/netdev.c +2 -4
index 925d7286a8ee4..2e11d999168de 100644
@@ -2419,12 +2419,10 @@ static int igbvf_change_mtu(struct net_device *netdev, int new_mtu)
 		adapter->rx_buffer_len = 1024;
 	else if (max_frame <= 2048)
 		adapter->rx_buffer_len = 2048;
-	else
-#if (PAGE_SIZE / 2) > 16384
+	else if ((PAGE_SIZE / 2) > 16384)
 		adapter->rx_buffer_len = 16384;
-#else
+	else
 		adapter->rx_buffer_len = PAGE_SIZE / 2;
-#endif
 
 	/* adjust allocation if LPE protects us, and we aren't using SBP */
 	if ((max_frame == ETH_FRAME_LEN + ETH_FCS_LEN) ||
Signature · 1 line
2.43.0
author reviewer
#81 lore raw

Re: [RFC PATCH v1 28/57] net: igbvf: Remove PAGE_SIZE compile-time constant assumption

+ Przemek Kitszel, Tony Nguyen

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 37 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/igbvf/netdev.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/intel/igbvf/netdev.c +2 -4
index 925d7286a8ee4..2e11d999168de 100644
@@ -2419,12 +2419,10 @@ static int igbvf_change_mtu(struct net_device *netdev, int new_mtu)
 		adapter->rx_buffer_len = 1024;
 	else if (max_frame <= 2048)
 		adapter->rx_buffer_len = 2048;
-	else
-#if (PAGE_SIZE / 2) > 16384
+	else if ((PAGE_SIZE / 2) > 16384)
 		adapter->rx_buffer_len = 16384;
-#else
+	else
 		adapter->rx_buffer_len = PAGE_SIZE / 2;
-#endif
 
 	/* adjust allocation if LPE protects us, and we aren't using SBP */
 	if ((max_frame == ETH_FRAME_LEN + ETH_FCS_LEN) ||
author reviewer
#82 lore raw

RFC PATCH 29/57 net: igb: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/igb/igb.h      |  25 ++--
 drivers/net/ethernet/intel/igb/igb_main.c | 149 +++++++++++-----------
 2 files changed, 82 insertions(+), 92 deletions(-)
drivers/net/ethernet/intel/igb/igb.h +11 -14
index 3c2dc7bdebb50..04aeebcd363b3 100644
@@ -158,7 +158,6 @@ struct vf_mac_filter {
  *	 up negative.  In these cases we should fall back to the 3K
  *	 buffers.
  */
-#if (PAGE_SIZE < 8192)
 #define IGB_MAX_FRAME_BUILD_SKB (IGB_RXBUFFER_1536 - NET_IP_ALIGN)
 #define IGB_2K_TOO_SMALL_WITH_PADDING \
 ((NET_SKB_PAD + IGB_TS_HDR_LEN + IGB_RXBUFFER_1536) > SKB_WITH_OVERHEAD(IGB_RXBUFFER_2048))
@@ -177,6 +176,9 @@ static inline int igb_skb_pad(void)
 {
 	int rx_buf_len;
 
+	if (PAGE_SIZE >= 8192)
+		return NET_SKB_PAD + NET_IP_ALIGN;
+
 	/* If a 2K buffer cannot handle a standard Ethernet frame then
 	 * optimize padding for a 3K buffer instead of a 1.5K buffer.
 	 *
@@ -196,9 +198,6 @@ static inline int igb_skb_pad(void)
 }
 
 #define IGB_SKB_PAD	igb_skb_pad()
-#else
-#define IGB_SKB_PAD	(NET_SKB_PAD + NET_IP_ALIGN)
-#endif
 
 /* How many Rx Buffers do we bundle into one write to the hardware ? */
 #define IGB_RX_BUFFER_WRITE	16 /* Must be power of 2 */
@@ -280,7 +279,7 @@ struct igb_tx_buffer {
 struct igb_rx_buffer {
 	dma_addr_t dma;
 	struct page *page;
-#if (BITS_PER_LONG > 32) || (PAGE_SIZE >= 65536)
+#if (BITS_PER_LONG > 32) || (PAGE_SIZE_MAX >= 65536)
 	__u32 page_offset;
 #else
 	__u16 page_offset;
@@ -403,22 +402,20 @@ enum e1000_ring_flags_t {
 
 static inline unsigned int igb_rx_bufsz(struct igb_ring *ring)
 {
-#if (PAGE_SIZE < 8192)
-	if (ring_uses_large_buffer(ring))
-		return IGB_RXBUFFER_3072;
+	if (PAGE_SIZE < 8192) {
+		if (ring_uses_large_buffer(ring))
+			return IGB_RXBUFFER_3072;
 
-	if (ring_uses_build_skb(ring))
-		return IGB_MAX_FRAME_BUILD_SKB;
-#endif
+		if (ring_uses_build_skb(ring))
+			return IGB_MAX_FRAME_BUILD_SKB;
+	}
 	return IGB_RXBUFFER_2048;
 }
 
 static inline unsigned int igb_rx_pg_order(struct igb_ring *ring)
 {
-#if (PAGE_SIZE < 8192)
-	if (ring_uses_large_buffer(ring))
+	if (PAGE_SIZE < 8192 && ring_uses_large_buffer(ring))
 		return 1;
-#endif
 	return 0;
 }
 
drivers/net/ethernet/intel/igb/igb_main.c +71 -78

262 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#83 lore raw

Re: [RFC PATCH v1 29/57] net: igb: Remove PAGE_SIZE compile-time constant assumption

+ Alexei Starovoitov, Daniel Borkmann, Jesper Dangaard Brouer, John Fastabend, Przemek Kitszel, Tony Nguyen

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 371 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert CPP conditionals to C conditionals. The compiler will dead code strip when doing a compile-time page size build, for the same end effect. But this will also work with boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/net/ethernet/intel/igb/igb.h      |  25 ++--
 drivers/net/ethernet/intel/igb/igb_main.c | 149 +++++++++++-----------
 2 files changed, 82 insertions(+), 92 deletions(-)
drivers/net/ethernet/intel/igb/igb.h +11 -14
index 3c2dc7bdebb50..04aeebcd363b3 100644
@@ -158,7 +158,6 @@ struct vf_mac_filter {
  *	 up negative.  In these cases we should fall back to the 3K
  *	 buffers.
  */
-#if (PAGE_SIZE < 8192)
 #define IGB_MAX_FRAME_BUILD_SKB (IGB_RXBUFFER_1536 - NET_IP_ALIGN)
 #define IGB_2K_TOO_SMALL_WITH_PADDING \
 ((NET_SKB_PAD + IGB_TS_HDR_LEN + IGB_RXBUFFER_1536) > SKB_WITH_OVERHEAD(IGB_RXBUFFER_2048))
@@ -177,6 +176,9 @@ static inline int igb_skb_pad(void)
 {
 	int rx_buf_len;
 
+	if (PAGE_SIZE >= 8192)
+		return NET_SKB_PAD + NET_IP_ALIGN;
+
 	/* If a 2K buffer cannot handle a standard Ethernet frame then
 	 * optimize padding for a 3K buffer instead of a 1.5K buffer.
 	 *
@@ -196,9 +198,6 @@ static inline int igb_skb_pad(void)
 }
 
 #define IGB_SKB_PAD	igb_skb_pad()
-#else
-#define IGB_SKB_PAD	(NET_SKB_PAD + NET_IP_ALIGN)
-#endif
 
 /* How many Rx Buffers do we bundle into one write to the hardware ? */
 #define IGB_RX_BUFFER_WRITE	16 /* Must be power of 2 */
@@ -280,7 +279,7 @@ struct igb_tx_buffer {
 struct igb_rx_buffer {
 	dma_addr_t dma;
 	struct page *page;
-#if (BITS_PER_LONG > 32) || (PAGE_SIZE >= 65536)
+#if (BITS_PER_LONG > 32) || (PAGE_SIZE_MAX >= 65536)
 	__u32 page_offset;
 #else
 	__u16 page_offset;
@@ -403,22 +402,20 @@ enum e1000_ring_flags_t {
 
 static inline unsigned int igb_rx_bufsz(struct igb_ring *ring)
 {
-#if (PAGE_SIZE < 8192)
-	if (ring_uses_large_buffer(ring))
-		return IGB_RXBUFFER_3072;
+	if (PAGE_SIZE < 8192) {
+		if (ring_uses_large_buffer(ring))
+			return IGB_RXBUFFER_3072;
 
-	if (ring_uses_build_skb(ring))
-		return IGB_MAX_FRAME_BUILD_SKB;
-#endif
+		if (ring_uses_build_skb(ring))
+			return IGB_MAX_FRAME_BUILD_SKB;
+	}
 	return IGB_RXBUFFER_2048;
 }
 
 static inline unsigned int igb_rx_pg_order(struct igb_ring *ring)
 {
-#if (PAGE_SIZE < 8192)
-	if (ring_uses_large_buffer(ring))
+	if (PAGE_SIZE < 8192 && ring_uses_large_buffer(ring))
 		return 1;
-#endif
 	return 0;
 }
 
drivers/net/ethernet/intel/igb/igb_main.c +71 -78
index 1ef4cb871452a..4f2c53dece1a2 100644
@@ -4797,9 +4797,7 @@ void igb_configure_rx_ring(struct igb_adapter *adapter,
 static void igb_set_rx_buffer_len(struct igb_adapter *adapter,
 				  struct igb_ring *rx_ring)
 {
-#if (PAGE_SIZE < 8192)
 	struct e1000_hw *hw = &adapter->hw;
-#endif
 
 	/* set build_skb and buffer size flags */
 	clear_ring_build_skb_enabled(rx_ring);
@@ -4810,12 +4808,11 @@ static void igb_set_rx_buffer_len(struct igb_adapter *adapter,
 
 	set_ring_build_skb_enabled(rx_ring);
 
-#if (PAGE_SIZE < 8192)
-	if (adapter->max_frame_size > IGB_MAX_FRAME_BUILD_SKB ||
+	if (PAGE_SIZE < 8192 &&
+	    (adapter->max_frame_size > IGB_MAX_FRAME_BUILD_SKB ||
 	    IGB_2K_TOO_SMALL_WITH_PADDING ||
-	    rd32(E1000_RCTL) & E1000_RCTL_SBP)
+	    rd32(E1000_RCTL) & E1000_RCTL_SBP))
 		set_ring_uses_large_buffer(rx_ring);
-#endif
 }
 
 /**
@@ -5314,12 +5311,10 @@ static void igb_set_rx_mode(struct net_device *netdev)
 				     E1000_RCTL_VFE);
 	wr32(E1000_RCTL, rctl);
 
-#if (PAGE_SIZE < 8192)
-	if (!adapter->vfs_allocated_count) {
+	if (PAGE_SIZE < 8192 && !adapter->vfs_allocated_count) {
 		if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
 			rlpml = IGB_MAX_FRAME_BUILD_SKB;
 	}
-#endif
 	wr32(E1000_RLPML, rlpml);
 
 	/* In order to support SR-IOV and eventually VMDq it is necessary to set
@@ -5338,11 +5333,10 @@ static void igb_set_rx_mode(struct net_device *netdev)
 
 	/* enable Rx jumbo frames, restrict as needed to support build_skb */
 	vmolr &= ~E1000_VMOLR_RLPML_MASK;
-#if (PAGE_SIZE < 8192)
-	if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
+	if (PAGE_SIZE < 8192 &&
+	    adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
 		vmolr |= IGB_MAX_FRAME_BUILD_SKB;
 	else
-#endif
 		vmolr |= MAX_JUMBO_FRAME_SIZE;
 	vmolr |= E1000_VMOLR_LPE;
 
@@ -8435,17 +8429,17 @@ static bool igb_can_reuse_rx_page(struct igb_rx_buffer *rx_buffer,
 	if (!dev_page_is_reusable(page))
 		return false;
 
-#if (PAGE_SIZE < 8192)
-	/* if we are only owner of page we can reuse it */
-	if (unlikely((rx_buf_pgcnt - pagecnt_bias) > 1))
-		return false;
-#else
+	if (PAGE_SIZE < 8192) {
+		/* if we are only owner of page we can reuse it */
+		if (unlikely((rx_buf_pgcnt - pagecnt_bias) > 1))
+			return false;
+	} else {
 #define IGB_LAST_OFFSET \
 	(SKB_WITH_OVERHEAD(PAGE_SIZE) - IGB_RXBUFFER_2048)
 
-	if (rx_buffer->page_offset > IGB_LAST_OFFSET)
-		return false;
-#endif
+		if (rx_buffer->page_offset > IGB_LAST_OFFSET)
+			return false;
+	}
 
 	/* If we have drained the page fragment pool we need to update
 	 * the pagecnt_bias and page count so that we fully restock the
@@ -8473,20 +8467,22 @@ static void igb_add_rx_frag(struct igb_ring *rx_ring,
 			    struct sk_buff *skb,
 			    unsigned int size)
 {
-#if (PAGE_SIZE < 8192)
-	unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
-#else
-	unsigned int truesize = ring_uses_build_skb(rx_ring) ?
+	unsigned int truesize;
+
+	if (PAGE_SIZE < 8192)
+		truesize = igb_rx_pg_size(rx_ring) / 2;
+	else
+		truesize = ring_uses_build_skb(rx_ring) ?
 				SKB_DATA_ALIGN(IGB_SKB_PAD + size) :
 				SKB_DATA_ALIGN(size);
-#endif
+
 	skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page,
 			rx_buffer->page_offset, size, truesize);
-#if (PAGE_SIZE < 8192)
-	rx_buffer->page_offset ^= truesize;
-#else
-	rx_buffer->page_offset += truesize;
-#endif
+
+	if (PAGE_SIZE < 8192)
+		rx_buffer->page_offset ^= truesize;
+	else
+		rx_buffer->page_offset += truesize;
 }
 
 static struct sk_buff *igb_construct_skb(struct igb_ring *rx_ring,
@@ -8494,16 +8490,16 @@ static struct sk_buff *igb_construct_skb(struct igb_ring *rx_ring,
 					 struct xdp_buff *xdp,
 					 ktime_t timestamp)
 {
-#if (PAGE_SIZE < 8192)
-	unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
-#else
-	unsigned int truesize = SKB_DATA_ALIGN(xdp->data_end -
-					       xdp->data_hard_start);
-#endif
 	unsigned int size = xdp->data_end - xdp->data;
+	unsigned int truesize;
 	unsigned int headlen;
 	struct sk_buff *skb;
 
+	if (PAGE_SIZE < 8192)
+		truesize = igb_rx_pg_size(rx_ring) / 2;
+	else
+		truesize = SKB_DATA_ALIGN(xdp->data_end - xdp->data_hard_start);
+
 	/* prefetch first cache line of first page */
 	net_prefetch(xdp->data);
 
@@ -8529,11 +8525,10 @@ static struct sk_buff *igb_construct_skb(struct igb_ring *rx_ring,
 		skb_add_rx_frag(skb, 0, rx_buffer->page,
 				(xdp->data + headlen) - page_address(rx_buffer->page),
 				size, truesize);
-#if (PAGE_SIZE < 8192)
-		rx_buffer->page_offset ^= truesize;
-#else
-		rx_buffer->page_offset += truesize;
-#endif
+		if (PAGE_SIZE < 8192)
+			rx_buffer->page_offset ^= truesize;
+		else
+			rx_buffer->page_offset += truesize;
 	} else {
 		rx_buffer->pagecnt_bias++;
 	}
@@ -8546,16 +8541,17 @@ static struct sk_buff *igb_build_skb(struct igb_ring *rx_ring,
 				     struct xdp_buff *xdp,
 				     ktime_t timestamp)
 {
-#if (PAGE_SIZE < 8192)
-	unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
-#else
-	unsigned int truesize = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) +
-				SKB_DATA_ALIGN(xdp->data_end -
-					       xdp->data_hard_start);
-#endif
 	unsigned int metasize = xdp->data - xdp->data_meta;
+	unsigned int truesize;
 	struct sk_buff *skb;
 
+	if (PAGE_SIZE < 8192)
+		truesize = igb_rx_pg_size(rx_ring) / 2;
+	else
+		truesize = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) +
+			   SKB_DATA_ALIGN(xdp->data_end -
+					  xdp->data_hard_start);
+
 	/* prefetch first cache line of first page */
 	net_prefetch(xdp->data_meta);
 
@@ -8575,11 +8571,10 @@ static struct sk_buff *igb_build_skb(struct igb_ring *rx_ring,
 		skb_hwtstamps(skb)->hwtstamp = timestamp;
 
 	/* update buffer offset */
-#if (PAGE_SIZE < 8192)
-	rx_buffer->page_offset ^= truesize;
-#else
-	rx_buffer->page_offset += truesize;
-#endif
+	if (PAGE_SIZE < 8192)
+		rx_buffer->page_offset ^= truesize;
+	else
+		rx_buffer->page_offset += truesize;
 
 	return skb;
 }
@@ -8634,14 +8629,14 @@ static unsigned int igb_rx_frame_truesize(struct igb_ring *rx_ring,
 {
 	unsigned int truesize;
 
-#if (PAGE_SIZE < 8192)
-	truesize = igb_rx_pg_size(rx_ring) / 2; /* Must be power-of-2 */
-#else
-	truesize = ring_uses_build_skb(rx_ring) ?
-		SKB_DATA_ALIGN(IGB_SKB_PAD + size) +
-		SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) :
-		SKB_DATA_ALIGN(size);
-#endif
+	if (PAGE_SIZE < 8192)
+		truesize = igb_rx_pg_size(rx_ring) / 2; /* Must be power-of-2 */
+	else
+		truesize = ring_uses_build_skb(rx_ring) ?
+			SKB_DATA_ALIGN(IGB_SKB_PAD + size) +
+			SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) :
+			SKB_DATA_ALIGN(size);
+
 	return truesize;
 }
 
@@ -8650,11 +8645,11 @@ static void igb_rx_buffer_flip(struct igb_ring *rx_ring,
 			       unsigned int size)
 {
 	unsigned int truesize = igb_rx_frame_truesize(rx_ring, size);
-#if (PAGE_SIZE < 8192)
-	rx_buffer->page_offset ^= truesize;
-#else
-	rx_buffer->page_offset += truesize;
-#endif
+
+	if (PAGE_SIZE < 8192)
+		rx_buffer->page_offset ^= truesize;
+	else
+		rx_buffer->page_offset += truesize;
 }
 
 static inline void igb_rx_checksum(struct igb_ring *ring,
@@ -8825,12 +8820,12 @@ static struct igb_rx_buffer *igb_get_rx_buffer(struct igb_ring *rx_ring,
 	struct igb_rx_buffer *rx_buffer;
 
 	rx_buffer = &rx_ring->rx_buffer_info[rx_ring->next_to_clean];
-	*rx_buf_pgcnt =
-#if (PAGE_SIZE < 8192)
-		page_count(rx_buffer->page);
-#else
-		0;
-#endif
+
+	if (PAGE_SIZE < 8192)
+		*rx_buf_pgcnt = page_count(rx_buffer->page);
+	else
+		*rx_buf_pgcnt = 0;
+
 	prefetchw(rx_buffer->page);
 
 	/* we are reusing so sync this buffer for CPU use */
@@ -8881,9 +8876,8 @@ static int igb_clean_rx_irq(struct igb_q_vector *q_vector, const int budget)
 	int rx_buf_pgcnt;
 
 	/* Frame size depend on rx_ring setup when PAGE_SIZE=4K */
-#if (PAGE_SIZE < 8192)
-	frame_sz = igb_rx_frame_truesize(rx_ring, 0);
-#endif
+	if (PAGE_SIZE < 8192)
+		frame_sz = igb_rx_frame_truesize(rx_ring, 0);
 	xdp_init_buff(&xdp, frame_sz, &rx_ring->xdp_rxq);
 
 	while (likely(total_packets < budget)) {
@@ -8932,10 +8926,9 @@ static int igb_clean_rx_irq(struct igb_q_vector *q_vector, const int budget)
 
 			xdp_prepare_buff(&xdp, hard_start, offset, size, true);
 			xdp_buff_clear_frags_flag(&xdp);
-#if (PAGE_SIZE > 4096)
 			/* At larger PAGE_SIZE, frame_sz depend on len size */
-			xdp.frame_sz = igb_rx_frame_truesize(rx_ring, size);
-#endif
+			if (PAGE_SIZE > 4096)
+				xdp.frame_sz = igb_rx_frame_truesize(rx_ring, size);
 			skb = igb_run_xdp(adapter, rx_ring, &xdp);
 		}
 
author reviewer
#84 lore raw

RFC PATCH 30/57 drivers/base: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Update BUILD_BUG_ON() to test against page size limits.

CPUMAP_FILE_MAX_BYTES and CPULIST_FILE_MAX_BYTES are both defined relative to PAGE_SIZE, so when these values are assigned to global variables via BIN_ATTR_RO(), let's wrap them with DEFINE_GLOBAL_PAGE_SIZE_VAR() so that their assignment can be deferred until boot-time.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/base/node.c     |  6 +++---
 drivers/base/topology.c | 32 ++++++++++++++++----------------
 include/linux/cpumask.h |  5 +++++
 3 files changed, 24 insertions(+), 19 deletions(-)
drivers/base/node.c +3 -3
index eb72580288e62..30e6549e4c438 100644
@@ -45,7 +45,7 @@ static inline ssize_t cpumap_read(struct file *file, struct kobject *kobj,
 	return n;
 }
 
-static BIN_ATTR_RO(cpumap, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cpumap, CPUMAP_FILE_MAX_BYTES);
 
 static inline ssize_t cpulist_read(struct file *file, struct kobject *kobj,
 				   struct bin_attribute *attr, char *buf,
@@ -66,7 +66,7 @@ static inline ssize_t cpulist_read(struct file *file, struct kobject *kobj,
 	return n;
 }
 
-static BIN_ATTR_RO(cpulist, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cpulist, CPULIST_FILE_MAX_BYTES);
 
 /**
  * struct node_access_nodes - Access class device to hold user visible
@@ -558,7 +558,7 @@ static ssize_t node_read_distance(struct device *dev,
 	 * buf is currently PAGE_SIZE in length and each node needs 4 chars
 	 * at the most (distance + space or newline).
 	 */
-	BUILD_BUG_ON(MAX_NUMNODES * 4 > PAGE_SIZE);
+	BUILD_BUG_ON(MAX_NUMNODES * 4 > PAGE_SIZE_MIN);
 
 	for_each_online_node(i) {
 		len += sysfs_emit_at(buf, len, "%s%d",
drivers/base/topology.c +16 -16
index 89f98be5c5b99..bdbdbefd95b15 100644
@@ -62,47 +62,47 @@ define_id_show_func(ppin, "0x%llx");
 static DEVICE_ATTR_ADMIN_RO(ppin);
 
 define_siblings_read_func(thread_siblings, sibling_cpumask);
-static BIN_ATTR_RO(thread_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(thread_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(thread_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(thread_siblings_list, CPULIST_FILE_MAX_BYTES);
 
 define_siblings_read_func(core_cpus, sibling_cpumask);
-static BIN_ATTR_RO(core_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(core_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_cpus_list, CPULIST_FILE_MAX_BYTES);
 
 define_siblings_read_func(core_siblings, core_cpumask);
-static BIN_ATTR_RO(core_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(core_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_siblings_list, CPULIST_FILE_MAX_BYTES);
 
 #ifdef TOPOLOGY_CLUSTER_SYSFS
 define_siblings_read_func(cluster_cpus, cluster_cpumask);
-static BIN_ATTR_RO(cluster_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(cluster_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cluster_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cluster_cpus_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 #ifdef TOPOLOGY_DIE_SYSFS
 define_siblings_read_func(die_cpus, die_cpumask);
-static BIN_ATTR_RO(die_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(die_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(die_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(die_cpus_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 define_siblings_read_func(package_cpus, core_cpumask);
-static BIN_ATTR_RO(package_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(package_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(package_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(package_cpus_list, CPULIST_FILE_MAX_BYTES);
 
 #ifdef TOPOLOGY_BOOK_SYSFS
 define_id_show_func(book_id, "%d");
 static DEVICE_ATTR_RO(book_id);
 define_siblings_read_func(book_siblings, book_cpumask);
-static BIN_ATTR_RO(book_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(book_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(book_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(book_siblings_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 #ifdef TOPOLOGY_DRAWER_SYSFS
 define_id_show_func(drawer_id, "%d");
 static DEVICE_ATTR_RO(drawer_id);
 define_siblings_read_func(drawer_siblings, drawer_cpumask);
-static BIN_ATTR_RO(drawer_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(drawer_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(drawer_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(drawer_siblings_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 static struct bin_attribute *bin_attrs[] = {
include/linux/cpumask.h +5 -0
index 53158de44b837..f654b4198abc2 100644
@@ -1292,4 +1292,9 @@ cpumap_print_list_to_buf(char *buf, const struct cpumask *mask,
 					? (NR_CPUS * 9)/32 - 1 : PAGE_SIZE)
 #define CPULIST_FILE_MAX_BYTES  (((NR_CPUS * 7)/2 > PAGE_SIZE) ? (NR_CPUS * 7)/2 : PAGE_SIZE)
 
+#define CPU_FILE_BIN_ATTR_RO(_name, _size)				\
+	DEFINE_GLOBAL_PAGE_SIZE_VAR(struct bin_attribute,		\
+				    bin_attr_##_name,			\
+				    __BIN_ATTR_RO(_name, _size))
+
 #endif /* __LINUX_CPUMASK_H */
Signature · 1 line
2.43.0
author reviewer
#85 lore raw

Re: [RFC PATCH v1 30/57] drivers/base: Remove PAGE_SIZE compile-time constant assumption

+ Greg Kroah-Hartman

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 137 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Update BUILD_BUG_ON() to test against page size limits.

CPUMAP_FILE_MAX_BYTES and CPULIST_FILE_MAX_BYTES are both defined relative to PAGE_SIZE, so when these values are assigned to global variables via BIN_ATTR_RO(), let's wrap them with DEFINE_GLOBAL_PAGE_SIZE_VAR() so that their assignment can be deferred until boot-time.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/base/node.c     |  6 +++---
 drivers/base/topology.c | 32 ++++++++++++++++----------------
 include/linux/cpumask.h |  5 +++++
 3 files changed, 24 insertions(+), 19 deletions(-)
drivers/base/node.c +3 -3
index eb72580288e62..30e6549e4c438 100644
@@ -45,7 +45,7 @@ static inline ssize_t cpumap_read(struct file *file, struct kobject *kobj,
 	return n;
 }
 
-static BIN_ATTR_RO(cpumap, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cpumap, CPUMAP_FILE_MAX_BYTES);
 
 static inline ssize_t cpulist_read(struct file *file, struct kobject *kobj,
 				   struct bin_attribute *attr, char *buf,
@@ -66,7 +66,7 @@ static inline ssize_t cpulist_read(struct file *file, struct kobject *kobj,
 	return n;
 }
 
-static BIN_ATTR_RO(cpulist, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cpulist, CPULIST_FILE_MAX_BYTES);
 
 /**
  * struct node_access_nodes - Access class device to hold user visible
@@ -558,7 +558,7 @@ static ssize_t node_read_distance(struct device *dev,
 	 * buf is currently PAGE_SIZE in length and each node needs 4 chars
 	 * at the most (distance + space or newline).
 	 */
-	BUILD_BUG_ON(MAX_NUMNODES * 4 > PAGE_SIZE);
+	BUILD_BUG_ON(MAX_NUMNODES * 4 > PAGE_SIZE_MIN);
 
 	for_each_online_node(i) {
 		len += sysfs_emit_at(buf, len, "%s%d",
drivers/base/topology.c +16 -16
index 89f98be5c5b99..bdbdbefd95b15 100644
@@ -62,47 +62,47 @@ define_id_show_func(ppin, "0x%llx");
 static DEVICE_ATTR_ADMIN_RO(ppin);
 
 define_siblings_read_func(thread_siblings, sibling_cpumask);
-static BIN_ATTR_RO(thread_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(thread_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(thread_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(thread_siblings_list, CPULIST_FILE_MAX_BYTES);
 
 define_siblings_read_func(core_cpus, sibling_cpumask);
-static BIN_ATTR_RO(core_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(core_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_cpus_list, CPULIST_FILE_MAX_BYTES);
 
 define_siblings_read_func(core_siblings, core_cpumask);
-static BIN_ATTR_RO(core_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(core_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(core_siblings_list, CPULIST_FILE_MAX_BYTES);
 
 #ifdef TOPOLOGY_CLUSTER_SYSFS
 define_siblings_read_func(cluster_cpus, cluster_cpumask);
-static BIN_ATTR_RO(cluster_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(cluster_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cluster_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(cluster_cpus_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 #ifdef TOPOLOGY_DIE_SYSFS
 define_siblings_read_func(die_cpus, die_cpumask);
-static BIN_ATTR_RO(die_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(die_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(die_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(die_cpus_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 define_siblings_read_func(package_cpus, core_cpumask);
-static BIN_ATTR_RO(package_cpus, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(package_cpus_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(package_cpus, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(package_cpus_list, CPULIST_FILE_MAX_BYTES);
 
 #ifdef TOPOLOGY_BOOK_SYSFS
 define_id_show_func(book_id, "%d");
 static DEVICE_ATTR_RO(book_id);
 define_siblings_read_func(book_siblings, book_cpumask);
-static BIN_ATTR_RO(book_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(book_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(book_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(book_siblings_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 #ifdef TOPOLOGY_DRAWER_SYSFS
 define_id_show_func(drawer_id, "%d");
 static DEVICE_ATTR_RO(drawer_id);
 define_siblings_read_func(drawer_siblings, drawer_cpumask);
-static BIN_ATTR_RO(drawer_siblings, CPUMAP_FILE_MAX_BYTES);
-static BIN_ATTR_RO(drawer_siblings_list, CPULIST_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(drawer_siblings, CPUMAP_FILE_MAX_BYTES);
+static CPU_FILE_BIN_ATTR_RO(drawer_siblings_list, CPULIST_FILE_MAX_BYTES);
 #endif
 
 static struct bin_attribute *bin_attrs[] = {
include/linux/cpumask.h +5 -0
index 53158de44b837..f654b4198abc2 100644
@@ -1292,4 +1292,9 @@ cpumap_print_list_to_buf(char *buf, const struct cpumask *mask,
 					? (NR_CPUS * 9)/32 - 1 : PAGE_SIZE)
 #define CPULIST_FILE_MAX_BYTES  (((NR_CPUS * 7)/2 > PAGE_SIZE) ? (NR_CPUS * 7)/2 : PAGE_SIZE)
 
+#define CPU_FILE_BIN_ATTR_RO(_name, _size)				\
+	DEFINE_GLOBAL_PAGE_SIZE_VAR(struct bin_attribute,		\
+				    bin_attr_##_name,			\
+				    __BIN_ATTR_RO(_name, _size))
+
 #endif /* __LINUX_CPUMASK_H */
#86 lore raw

Re: [RFC PATCH v1 30/57] drivers/base: Remove PAGE_SIZE compile-time constant assumption

Quoted 5 lines · Ryan Roberts

+ Greg Kroah-Hartman

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

"supporter" is actually a much stronger "signal" than "maintainer" according to the MAINTAINERS file:
Supported: Someone is actually paid to look after this.
Maintained: Someone actually looks after it.

Quoted 2 lines

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Ick, good luck!

greg k-h

author reviewer
#87 lore raw

Re: [RFC PATCH v1 30/57] drivers/base: Remove PAGE_SIZE compile-time constant assumption

Quoted 11 lines · Greg Kroah-Hartman
Quoted 5 lines · Ryan Roberts

+ Greg Kroah-Hartman

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

"supporter" is actually a much stronger "signal" than "maintainer" according to the MAINTAINERS file:
Supported: Someone is actually paid to look after this.
Maintained: Someone actually looks after it.

Yes, consider me educated now. For some reason my brain always thought "supporter" was someone who was active in the subsystem but without an official affiliation.

Quoted 7 lines
Quoted 3 lines

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Ick, good luck!

greg k-h

author reviewer
#88 lore raw

RFC PATCH 31/57 edac: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert PAGES_TO_MiB() and MiB_TO_PAGES() to use the ternary operator so that they continue to work with boot-time page size; Boot-time page size can't be used with CPP because it's value is not known at compile time. For compile-time page size builds, the compiler will dead code strip for the same result.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/edac/edac_mc.h | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
drivers/edac/edac_mc.h +6 -7
index 881b00eadf7a5..22132ee86e953 100644
@@ -37,13 +37,12 @@
 #include <linux/workqueue.h>
 #include <linux/edac.h>
 
-#if PAGE_SHIFT < 20
-#define PAGES_TO_MiB(pages)	((pages) >> (20 - PAGE_SHIFT))
-#define MiB_TO_PAGES(mb)	((mb) << (20 - PAGE_SHIFT))
-#else				/* PAGE_SHIFT > 20 */
-#define PAGES_TO_MiB(pages)	((pages) << (PAGE_SHIFT - 20))
-#define MiB_TO_PAGES(mb)	((mb) >> (PAGE_SHIFT - 20))
-#endif
+#define PAGES_TO_MiB(pages)	(PAGE_SHIFT < 20 ?			\
+					((pages) >> (20 - PAGE_SHIFT)) :\
+					((pages) << (PAGE_SHIFT - 20)))
+#define MiB_TO_PAGES(mb)	(PAGE_SHIFT < 20 ?			\
+					((mb) << (20 - PAGE_SHIFT)) :	\
+					((mb) >> (PAGE_SHIFT - 20)))
 
 #define edac_printk(level, prefix, fmt, arg...) \
 	printk(level "EDAC " prefix ": " fmt, ##arg)
Signature · 1 line
2.43.0
author reviewer
#89 lore raw

Re: [RFC PATCH v1 31/57] edac: Remove PAGE_SIZE compile-time constant assumption

+ Borislav Petkov, Tony Luck

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 44 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert PAGES_TO_MiB() and MiB_TO_PAGES() to use the ternary operator so that they continue to work with boot-time page size; Boot-time page size can't be used with CPP because it's value is not known at compile time. For compile-time page size builds, the compiler will dead code strip for the same result.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/edac/edac_mc.h | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
drivers/edac/edac_mc.h +6 -7
index 881b00eadf7a5..22132ee86e953 100644
@@ -37,13 +37,12 @@
 #include <linux/workqueue.h>
 #include <linux/edac.h>
 
-#if PAGE_SHIFT < 20
-#define PAGES_TO_MiB(pages)	((pages) >> (20 - PAGE_SHIFT))
-#define MiB_TO_PAGES(mb)	((mb) << (20 - PAGE_SHIFT))
-#else				/* PAGE_SHIFT > 20 */
-#define PAGES_TO_MiB(pages)	((pages) << (PAGE_SHIFT - 20))
-#define MiB_TO_PAGES(mb)	((mb) >> (PAGE_SHIFT - 20))
-#endif
+#define PAGES_TO_MiB(pages)	(PAGE_SHIFT < 20 ?			\
+					((pages) >> (20 - PAGE_SHIFT)) :\
+					((pages) << (PAGE_SHIFT - 20)))
+#define MiB_TO_PAGES(mb)	(PAGE_SHIFT < 20 ?			\
+					((mb) << (20 - PAGE_SHIFT)) :	\
+					((mb) >> (PAGE_SHIFT - 20)))
 
 #define edac_printk(level, prefix, fmt, arg...) \
 	printk(level "EDAC " prefix ": " fmt, ##arg)
author reviewer
#90 lore raw

RFC PATCH 32/57 optee: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated BUILD_BUG_ON() to test against limit.

Refactored "struct optee_shm_arg_entry" to use a flexible array member for "map", since its length depends on PAGE_SIZE.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/20241014105514.3206191-1-ryan.roberts(a)arm.com/

 drivers/tee/optee/call.c    | 7 +++++--
 drivers/tee/optee/smc_abi.c | 2 +-
 2 files changed, 6 insertions(+), 3 deletions(-)
drivers/tee/optee/call.c +5 -2
index 16eb953e14bb6..41bd7ace6606e 100644
@@ -36,7 +36,7 @@
 struct optee_shm_arg_entry {
 	struct list_head list_node;
 	struct tee_shm *shm;
-	DECLARE_BITMAP(map, MAX_ARG_COUNT_PER_ENTRY);
+	unsigned long map[];
 };
 
 void optee_cq_init(struct optee_call_queue *cq, int thread_count)
@@ -271,6 +271,7 @@ struct optee_msg_arg *optee_get_msg_arg(struct tee_context *ctx,
 	struct optee_shm_arg_entry *entry;
 	struct optee_msg_arg *ma;
 	size_t args_per_entry;
+	size_t entry_sz;
 	u_long bit;
 	u_int offs;
 	void *res;
@@ -293,7 +294,9 @@ struct optee_msg_arg *optee_get_msg_arg(struct tee_context *ctx,
 	/*
 	 * No entry was found, let's allocate a new.
 	 */
-	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
+	entry_sz = struct_size(entry, map,
+			       BITS_TO_LONGS(MAX_ARG_COUNT_PER_ENTRY));
+	entry = kzalloc(entry_sz, GFP_KERNEL);
 	if (!entry) {
 		res = ERR_PTR(-ENOMEM);
 		goto out;
drivers/tee/optee/smc_abi.c +1 -1
index 844285d4f03c1..005689380d848 100644
@@ -418,7 +418,7 @@ static void optee_fill_pages_list(u64 *dst, struct page **pages, int num_pages,
 	 * code heavily relies on this assumption, so it is better be
 	 * safe than sorry.
 	 */
-	BUILD_BUG_ON(PAGE_SIZE < OPTEE_MSG_NONCONTIG_PAGE_SIZE);
+	BUILD_BUG_ON(PAGE_SIZE_MIN < OPTEE_MSG_NONCONTIG_PAGE_SIZE);
 
 	pages_data = (void *)dst;
 	/*
Signature · 1 line
2.43.0
author reviewer
#91 lore raw

RFC PATCH 33/57 random: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Update BUILD_BUG_ON()s to test against page size limits.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/char/random.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/char/random.c +2 -2
index 87fe61295ea1f..49d6c4ef16df4 100644
@@ -466,7 +466,7 @@ static ssize_t get_random_bytes_user(struct iov_iter *iter)
 		if (!iov_iter_count(iter) || copied != sizeof(block))
 			break;
 
-		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
+		BUILD_BUG_ON(PAGE_SIZE_MIN % sizeof(block) != 0);
 		if (ret % PAGE_SIZE == 0) {
 			if (signal_pending(current))
 				break;
@@ -1428,7 +1428,7 @@ static ssize_t write_pool_user(struct iov_iter *iter)
 		if (!iov_iter_count(iter) || copied != sizeof(block))
 			break;
 
-		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
+		BUILD_BUG_ON(PAGE_SIZE_MIN % sizeof(block) != 0);
 		if (ret % PAGE_SIZE == 0) {
 			if (signal_pending(current))
 				break;
Signature · 1 line
2.43.0
author reviewer
#92 lore raw

RFC PATCH 34/57 sata_sil24: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert "struct sil24_ata_block" and "struct sil24_atapi_block" to use a flexible array member for their sge[] array. The previous static size of SIL24_MAX_SGE depends on PAGE_SIZE so doesn't work for boot-time page size.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/ata/sata_sil24.c | 46 +++++++++++++++++++---------------------
 1 file changed, 22 insertions(+), 24 deletions(-)
drivers/ata/sata_sil24.c +22 -24
index 72c03cbdaff43..85c6382976626 100644
@@ -42,26 +42,25 @@ struct sil24_sge {
 	__le32	flags;
 };
 
+/*
+ * sil24 fetches in chunks of 64bytes.  The first block
+ * contains the PRB and two SGEs.  From the second block, it's
+ * consisted of four SGEs and called SGT.  Calculate the
+ * number of SGTs that fit into one page.
+ */
+#define SIL24_PRB_SZ	(sizeof(struct sil24_prb) + 2 * sizeof(struct sil24_sge))
+#define SIL24_MAX_SGT	((PAGE_SIZE - SIL24_PRB_SZ) / (4 * sizeof(struct sil24_sge)))
+
+/*
+ * This will give us one unused SGEs for ATA.  This extra SGE
+ * will be used to store CDB for ATAPI devices.
+ */
+#define SIL24_MAX_SGE	(4 * SIL24_MAX_SGT + 1)
 
 enum {
 	SIL24_HOST_BAR		= 0,
 	SIL24_PORT_BAR		= 2,
 
-	/* sil24 fetches in chunks of 64bytes.  The first block
-	 * contains the PRB and two SGEs.  From the second block, it's
-	 * consisted of four SGEs and called SGT.  Calculate the
-	 * number of SGTs that fit into one page.
-	 */
-	SIL24_PRB_SZ		= sizeof(struct sil24_prb)
-				  + 2 * sizeof(struct sil24_sge),
-	SIL24_MAX_SGT		= (PAGE_SIZE - SIL24_PRB_SZ)
-				  / (4 * sizeof(struct sil24_sge)),
-
-	/* This will give us one unused SGEs for ATA.  This extra SGE
-	 * will be used to store CDB for ATAPI devices.
-	 */
-	SIL24_MAX_SGE		= 4 * SIL24_MAX_SGT + 1,
-
 	/*
 	 * Global controller registers (128 bytes @ BAR0)
 	 */
@@ -244,13 +243,13 @@ enum {
 
 struct sil24_ata_block {
 	struct sil24_prb prb;
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 struct sil24_atapi_block {
 	struct sil24_prb prb;
 	u8 cdb[16];
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 union sil24_cmd_block {
@@ -373,7 +372,7 @@ static struct pci_driver sil24_pci_driver = {
 #endif
 };
 
-static const struct scsi_host_template sil24_sht = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct scsi_host_template, sil24_sht, {
 	__ATA_BASE_SHT(DRV_NAME),
 	.can_queue		= SIL24_MAX_CMDS,
 	.sg_tablesize		= SIL24_MAX_SGE,
@@ -382,7 +381,7 @@ static const struct scsi_host_template sil24_sht = {
 	.sdev_groups		= ata_ncq_sdev_groups,
 	.change_queue_depth	= ata_scsi_change_queue_depth,
 	.device_configure	= ata_scsi_device_configure
-};
+});
 
 static struct ata_port_operations sil24_ops = {
 	.inherits		= &sata_pmp_port_ops,
@@ -1193,7 +1192,7 @@ static int sil24_port_start(struct ata_port *ap)
 	struct device *dev = ap->host->dev;
 	struct sil24_port_priv *pp;
 	union sil24_cmd_block *cb;
-	size_t cb_size = sizeof(*cb) * SIL24_MAX_CMDS;
+	size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
 	dma_addr_t cb_dma;
 
 	pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1258,7 +1257,6 @@ static void sil24_init_controller(struct ata_host *host)
 
 static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 {
-	extern int __MARKER__sil24_cmd_block_is_sized_wrongly;
 	struct ata_port_info pi = sil24_port_info[ent->driver_data];
 	const struct ata_port_info *ppi[] = { &pi, NULL };
 	void __iomem * const *iomap;
@@ -1266,9 +1264,9 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 	int rc;
 	u32 tmp;
 
-	/* cause link error if sil24_cmd_block is sized wrongly */
-	if (sizeof(union sil24_cmd_block) != PAGE_SIZE)
-		__MARKER__sil24_cmd_block_is_sized_wrongly = 1;
+	/* union sil24_cmd_block must be PAGE_SIZE */
+	BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
+	BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
 
 	ata_print_version_once(&pdev->dev, DRV_VERSION);
 
Signature · 1 line
2.43.0
maintainer
#93 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Hello Ryan,

While I realize that this has not always been consistent, please prefix the subject with "ata: ", so that it becomes "ata: sata_sil24: ".

Quoted 135 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert "struct sil24_ata_block" and "struct sil24_atapi_block" to use a flexible array member for their sge[] array. The previous static size of SIL24_MAX_SGE depends on PAGE_SIZE so doesn't work for boot-time page size.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/ata/sata_sil24.c | 46 +++++++++++++++++++---------------------
 1 file changed, 22 insertions(+), 24 deletions(-)
drivers/ata/sata_sil24.c +22 -24
index 72c03cbdaff43..85c6382976626 100644
@@ -42,26 +42,25 @@ struct sil24_sge {
 	__le32	flags;
 };
 
+/*
+ * sil24 fetches in chunks of 64bytes.  The first block
+ * contains the PRB and two SGEs.  From the second block, it's
+ * consisted of four SGEs and called SGT.  Calculate the
+ * number of SGTs that fit into one page.
+ */
+#define SIL24_PRB_SZ	(sizeof(struct sil24_prb) + 2 * sizeof(struct sil24_sge))
+#define SIL24_MAX_SGT	((PAGE_SIZE - SIL24_PRB_SZ) / (4 * sizeof(struct sil24_sge)))
+
+/*
+ * This will give us one unused SGEs for ATA.  This extra SGE
+ * will be used to store CDB for ATAPI devices.
+ */
+#define SIL24_MAX_SGE	(4 * SIL24_MAX_SGT + 1)
 
 enum {
 	SIL24_HOST_BAR		= 0,
 	SIL24_PORT_BAR		= 2,
 
-	/* sil24 fetches in chunks of 64bytes.  The first block
-	 * contains the PRB and two SGEs.  From the second block, it's
-	 * consisted of four SGEs and called SGT.  Calculate the
-	 * number of SGTs that fit into one page.
-	 */
-	SIL24_PRB_SZ		= sizeof(struct sil24_prb)
-				  + 2 * sizeof(struct sil24_sge),
-	SIL24_MAX_SGT		= (PAGE_SIZE - SIL24_PRB_SZ)
-				  / (4 * sizeof(struct sil24_sge)),
-
-	/* This will give us one unused SGEs for ATA.  This extra SGE
-	 * will be used to store CDB for ATAPI devices.
-	 */
-	SIL24_MAX_SGE		= 4 * SIL24_MAX_SGT + 1,
-
 	/*
 	 * Global controller registers (128 bytes @ BAR0)
 	 */
@@ -244,13 +243,13 @@ enum {
 
 struct sil24_ata_block {
 	struct sil24_prb prb;
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 struct sil24_atapi_block {
 	struct sil24_prb prb;
 	u8 cdb[16];
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 union sil24_cmd_block {
@@ -373,7 +372,7 @@ static struct pci_driver sil24_pci_driver = {
 #endif
 };
 
-static const struct scsi_host_template sil24_sht = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct scsi_host_template, sil24_sht, {
 	__ATA_BASE_SHT(DRV_NAME),
 	.can_queue		= SIL24_MAX_CMDS,
 	.sg_tablesize		= SIL24_MAX_SGE,
@@ -382,7 +381,7 @@ static const struct scsi_host_template sil24_sht = {
 	.sdev_groups		= ata_ncq_sdev_groups,
 	.change_queue_depth	= ata_scsi_change_queue_depth,
 	.device_configure	= ata_scsi_device_configure
-};
+});
 
 static struct ata_port_operations sil24_ops = {
 	.inherits		= &sata_pmp_port_ops,
@@ -1193,7 +1192,7 @@ static int sil24_port_start(struct ata_port *ap)
 	struct device *dev = ap->host->dev;
 	struct sil24_port_priv *pp;
 	union sil24_cmd_block *cb;
-	size_t cb_size = sizeof(*cb) * SIL24_MAX_CMDS;
+	size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
 	dma_addr_t cb_dma;
 
 	pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1258,7 +1257,6 @@ static void sil24_init_controller(struct ata_host *host)
 
 static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 {
-	extern int __MARKER__sil24_cmd_block_is_sized_wrongly;
 	struct ata_port_info pi = sil24_port_info[ent->driver_data];
 	const struct ata_port_info *ppi[] = { &pi, NULL };
 	void __iomem * const *iomap;
@@ -1266,9 +1264,9 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 	int rc;
 	u32 tmp;
 
-	/* cause link error if sil24_cmd_block is sized wrongly */
-	if (sizeof(union sil24_cmd_block) != PAGE_SIZE)
-		__MARKER__sil24_cmd_block_is_sized_wrongly = 1;
+	/* union sil24_cmd_block must be PAGE_SIZE */
+	BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
+	BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
 
 	ata_print_version_once(&pdev->dev, DRV_VERSION);
 
Signature · 1 line
2.43.0

As you might know, there is an effort to annotate all flexible array members with their run-time size information, see commit:
dd06e72e68bc ("Compiler Attributes: Add __counted_by macro")

I haven't looked at the DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST macro, but since sge[] now becomes a flexible array member, I think it would be nice if it would be possible to somehow use the __counted_by macro.

Other than that, this looks good to me.

Kind regards,
Niklas

author reviewer
#94 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 5 lines · Niklas Cassel

Hello Ryan,

While I realize that this has not always been consistent, please prefix the subject with "ata: ", so that it becomes "ata: sata_sil24: ".

Noted; I'll fix this in the next version.

Quoted 134 lines · Ryan Roberts
Quoted 132 lines

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Convert "struct sil24_ata_block" and "struct sil24_atapi_block" to use a flexible array member for their sge[] array. The previous static size of SIL24_MAX_SGE depends on PAGE_SIZE so doesn't work for boot-time page size.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/ata/sata_sil24.c | 46 +++++++++++++++++++---------------------
 1 file changed, 22 insertions(+), 24 deletions(-)
drivers/ata/sata_sil24.c +22 -24
index 72c03cbdaff43..85c6382976626 100644
@@ -42,26 +42,25 @@ struct sil24_sge {
 	__le32	flags;
 };
 
+/*
+ * sil24 fetches in chunks of 64bytes.  The first block
+ * contains the PRB and two SGEs.  From the second block, it's
+ * consisted of four SGEs and called SGT.  Calculate the
+ * number of SGTs that fit into one page.
+ */
+#define SIL24_PRB_SZ	(sizeof(struct sil24_prb) + 2 * sizeof(struct sil24_sge))
+#define SIL24_MAX_SGT	((PAGE_SIZE - SIL24_PRB_SZ) / (4 * sizeof(struct sil24_sge)))
+
+/*
+ * This will give us one unused SGEs for ATA.  This extra SGE
+ * will be used to store CDB for ATAPI devices.
+ */
+#define SIL24_MAX_SGE	(4 * SIL24_MAX_SGT + 1)
 
 enum {
 	SIL24_HOST_BAR		= 0,
 	SIL24_PORT_BAR		= 2,
 
-	/* sil24 fetches in chunks of 64bytes.  The first block
-	 * contains the PRB and two SGEs.  From the second block, it's
-	 * consisted of four SGEs and called SGT.  Calculate the
-	 * number of SGTs that fit into one page.
-	 */
-	SIL24_PRB_SZ		= sizeof(struct sil24_prb)
-				  + 2 * sizeof(struct sil24_sge),
-	SIL24_MAX_SGT		= (PAGE_SIZE - SIL24_PRB_SZ)
-				  / (4 * sizeof(struct sil24_sge)),
-
-	/* This will give us one unused SGEs for ATA.  This extra SGE
-	 * will be used to store CDB for ATAPI devices.
-	 */
-	SIL24_MAX_SGE		= 4 * SIL24_MAX_SGT + 1,
-
 	/*
 	 * Global controller registers (128 bytes @ BAR0)
 	 */
@@ -244,13 +243,13 @@ enum {
 
 struct sil24_ata_block {
 	struct sil24_prb prb;
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 struct sil24_atapi_block {
 	struct sil24_prb prb;
 	u8 cdb[16];
-	struct sil24_sge sge[SIL24_MAX_SGE];
+	struct sil24_sge sge[];
 };
 
 union sil24_cmd_block {
@@ -373,7 +372,7 @@ static struct pci_driver sil24_pci_driver = {
 #endif
 };
 
-static const struct scsi_host_template sil24_sht = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(struct scsi_host_template, sil24_sht, {
 	__ATA_BASE_SHT(DRV_NAME),
 	.can_queue		= SIL24_MAX_CMDS,
 	.sg_tablesize		= SIL24_MAX_SGE,
@@ -382,7 +381,7 @@ static const struct scsi_host_template sil24_sht = {
 	.sdev_groups		= ata_ncq_sdev_groups,
 	.change_queue_depth	= ata_scsi_change_queue_depth,
 	.device_configure	= ata_scsi_device_configure
-};
+});
 
 static struct ata_port_operations sil24_ops = {
 	.inherits		= &sata_pmp_port_ops,
@@ -1193,7 +1192,7 @@ static int sil24_port_start(struct ata_port *ap)
 	struct device *dev = ap->host->dev;
 	struct sil24_port_priv *pp;
 	union sil24_cmd_block *cb;
-	size_t cb_size = sizeof(*cb) * SIL24_MAX_CMDS;
+	size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
 	dma_addr_t cb_dma;
 
 	pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1258,7 +1257,6 @@ static void sil24_init_controller(struct ata_host *host)
 
 static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 {
-	extern int __MARKER__sil24_cmd_block_is_sized_wrongly;
 	struct ata_port_info pi = sil24_port_info[ent->driver_data];
 	const struct ata_port_info *ppi[] = { &pi, NULL };
 	void __iomem * const *iomap;
@@ -1266,9 +1264,9 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
 	int rc;
 	u32 tmp;
 
-	/* cause link error if sil24_cmd_block is sized wrongly */
-	if (sizeof(union sil24_cmd_block) != PAGE_SIZE)
-		__MARKER__sil24_cmd_block_is_sized_wrongly = 1;
+	/* union sil24_cmd_block must be PAGE_SIZE */
+	BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
+	BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
 
 	ata_print_version_once(&pdev->dev, DRV_VERSION);
 
Quoted 7 lines
Quoted 3 lines
Signature · 1 line
2.43.0

As you might know, there is an effort to annotate all flexible array members with their run-time size information, see commit:
dd06e72e68bc ("Compiler Attributes: Add __counted_by macro")

I'm vaguely aware of it. But as I understand it, __counted_by() nominates another member in the struct which keeps the count? In this case, there is no such member, it's size is implicit based on the value of PAGE_SIZE. So I'm not sure if it's practical to use it here?

Quoted 2 lines

I haven't looked at the DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST macro, but since

DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(), when doing a boot-time page size build, defers the initialization of the global variable to kernel init time, when PAGE_SIZE is known. Because SIL24_MAX_SGE is defined in terms of PAGE_SIZE, this deferral is required.

Quoted 4 lines

sge[] now becomes a flexible array member, I think it would be nice if it would be possible to somehow use the __counted_by macro.

Other than that, this looks good to me.

Thanks for the review!

Quoted 4 lines

Kind regards,
Niklas

maintainer
#95 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 1 line · Ryan Roberts

On 17/10/2024 10:09, Niklas Cassel wrote:

(snip)

Quoted 8 lines
Quoted 3 lines

As you might know, there is an effort to annotate all flexible array members with their run-time size information, see commit:
dd06e72e68bc ("Compiler Attributes: Add __counted_by macro")

I'm vaguely aware of it. But as I understand it, __counted_by() nominates another member in the struct which keeps the count? In this case, there is no such member, it's size is implicit based on the value of PAGE_SIZE. So I'm not sure if it's practical to use it here?

Neither am I :)

Perhaps some of the flexible array member experts like Kees Cook or Gustavo A. R. Silva could help us out here.

Would it make sense to add another struct member and simply initialize it to PAGE_SIZE, in order to be able to use the __counted_by macro?

Quoted 12 lines
Quoted 3 lines

I haven't looked at the DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST macro, but since

DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(), when doing a boot-time page size build, defers the initialization of the global variable to kernel init time, when PAGE_SIZE is known. Because SIL24_MAX_SGE is defined in terms of PAGE_SIZE, this deferral is required.

Quoted 3 lines

sge[] now becomes a flexible array member, I think it would be nice if it would be possible to somehow use the __counted_by macro.

author reviewer
#96 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 14 lines · Niklas Cassel
Quoted 1 line · Ryan Roberts

On 17/10/2024 10:09, Niklas Cassel wrote:

(snip)

Quoted 8 lines
Quoted 3 lines

As you might know, there is an effort to annotate all flexible array members with their run-time size information, see commit:
dd06e72e68bc ("Compiler Attributes: Add __counted_by macro")

I'm vaguely aware of it. But as I understand it, __counted_by() nominates another member in the struct which keeps the count? In this case, there is no such member, it's size is implicit based on the value of PAGE_SIZE. So I'm not sure if it's practical to use it here?

Quoted 4 lines

Neither am I :)

Perhaps some of the flexible array member experts like Kees Cook or Gustavo A. R. Silva could help us out here.

The GCC feature request is clear that it is explicitly to mark a member as the count variable: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896

But, yes, would be good to hear from Kees or Gustavo if there is an alternative mechanism for what we are doing here.

Quoted 3 lines

Would it make sense to add another struct member and simply initialize it to PAGE_SIZE, in order to be able to use the __counted_by macro?

I guess that _could_ be done. But the way the driver is currently structured takes the sge array pointer and passes that around for DMA, so I think the value of this tag within the struct would be lost anyway. It would also require reducing the number of sge entries to make space for the count, and given I'm not really familiar with the driver or HW, I'd be concerned that this could cause a performance regression. Overall, my preference is to leave it as is.

That said, while investigating this, I've spotted a bug in my change. paddr calculation in sil24_qc_issue() is incorrect since sizeof(*pp->cmd_block) is no longer PAGE_SIZE. Based on feedback in another patch, I'm also converting the BUG_ONs to WARN_ON_ONCEs.

Additional proposed change, which I'll plan to include in the next version:

---8<---

drivers/ata/sata_sil24.c +8 -5
index 85c6382976626..c402bf998c4ee 100644
@@ -257,6 +257,10 @@ union sil24_cmd_block {
        struct sil24_atapi_block atapi;
 };
 
+#define SIL24_ATA_BLOCK_SIZE   struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE)
+#define SIL24_ATAPI_BLOCK_SIZE struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE)
+#define SIL24_CMD_BLOCK_SIZE   max(SIL24_ATA_BLOCK_SIZE, SIL24_ATAPI_BLOCK_SIZE)
+
 static const struct sil24_cerr_info {
        unsigned int err_mask, action;
        const char *desc;
@@ -886,7 +890,7 @@ static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc)
        dma_addr_t paddr;
        void __iomem *activate;
 
-       paddr = pp->cmd_block_dma + tag * sizeof(*pp->cmd_block);
+       paddr = pp->cmd_block_dma + tag * SIL24_CMD_BLOCK_SIZE;
        activate = port + PORT_CMD_ACTIVATE + tag * 8;
 
        /*
@@ -1192,7 +1196,7 @@ static int sil24_port_start(struct ata_port *ap)
        struct device *dev = ap->host->dev;
        struct sil24_port_priv *pp;
        union sil24_cmd_block *cb;
-       size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
+       size_t cb_size = SIL24_CMD_BLOCK_SIZE * SIL24_MAX_CMDS;
        dma_addr_t cb_dma;
 
        pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1265,8 +1269,8 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
        u32 tmp;
 
        /* union sil24_cmd_block must be PAGE_SIZE */
-       BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
-       BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATAPI_BLOCK_SIZE != PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATA_BLOCK_SIZE != PAGE_SIZE - 16);
 
        ata_print_version_once(&pdev->dev, DRV_VERSION);
---8<---
Quoted 14 lines
Quoted 14 lines
Quoted 5 lines

I haven't looked at the DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST macro, but since

DEFINE_GLOBAL_PAGE_SIZE_VAR_CONST(), when doing a boot-time page size build, defers the initialization of the global variable to kernel init time, when PAGE_SIZE is known. Because SIL24_MAX_SGE is defined in terms of PAGE_SIZE, this deferral is required.

Quoted 3 lines

sge[] now becomes a flexible array member, I think it would be nice if it would be possible to somehow use the __counted_by macro.

maintainer
#97 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 2 lines · Ryan Roberts
Quoted 1 line · Niklas Cassel

On Thu, Oct 17, 2024 at 01:42:22PM +0100, Ryan Roberts wrote:

(snip)

Quoted 1 line

That said, while investigating this, I've spotted a bug in my change. paddr calculation in sil24_qc_issue() is incorrect since sizeof(*pp->cmd_block) is no longer PAGE_SIZE. Based on feedback in another patch, I'm also converting the BUG_ONs to WARN_ON_ONCEs.

Side note: Please wrap you lines to 80 characters max.

Quoted 38 lines

Additional proposed change, which I'll plan to include in the next version:

---8<---

drivers/ata/sata_sil24.c +6 -2
index 85c6382976626..c402bf998c4ee 100644
@@ -257,6 +257,10 @@ union sil24_cmd_block {
        struct sil24_atapi_block atapi;
 };
 
+#define SIL24_ATA_BLOCK_SIZE   struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE)
+#define SIL24_ATAPI_BLOCK_SIZE struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE)
+#define SIL24_CMD_BLOCK_SIZE   max(SIL24_ATA_BLOCK_SIZE, SIL24_ATAPI_BLOCK_SIZE)
+
 static const struct sil24_cerr_info {
        unsigned int err_mask, action;
        const char *desc;
@@ -886,7 +890,7 @@ static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc)
        dma_addr_t paddr;
        void __iomem *activate;
 
-       paddr = pp->cmd_block_dma + tag * sizeof(*pp->cmd_block);
+       paddr = pp->cmd_block_dma + tag * SIL24_CMD_BLOCK_SIZE;
        activate = port + PORT_CMD_ACTIVATE + tag * 8;
 
        /*
@@ -1192,7 +1196,7 @@ static int sil24_port_start(struct ata_port *ap)
        struct device *dev = ap->host->dev;
        struct sil24_port_priv *pp;
        union sil24_cmd_block *cb;
-       size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
+       size_t cb_size = SIL24_CMD_BLOCK_SIZE * SIL24_MAX_CMDS;
        dma_addr_t cb_dma;
 
        pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);

drivers/ata/sata_sil24.c static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) · line 1271

Quoted 3 lines
drivers/ata/sata_sil24.c +0 -0
@@ -1265,8 +1269,8 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
        u32 tmp;
 
        /* union sil24_cmd_block must be PAGE_SIZE */

This comment should probably be rephrased to be more clear then, since like you said sizeof(union sil24_cmd_block) will no longer be PAGE_SIZE.

Quoted 7 lines
drivers/ata/sata_sil24.c +2 -3
-       BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
-       BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATAPI_BLOCK_SIZE != PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATA_BLOCK_SIZE != PAGE_SIZE - 16);
 
        ata_print_version_once(&pdev->dev, DRV_VERSION);
---8<---
author reviewer
#98 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 9 lines · Niklas Cassel
Quoted 2 lines · Ryan Roberts
Quoted 1 line · Niklas Cassel

On Thu, Oct 17, 2024 at 01:42:22PM +0100, Ryan Roberts wrote:

(snip)

Quoted 1 line

That said, while investigating this, I've spotted a bug in my change. paddr calculation in sil24_qc_issue() is incorrect since sizeof(*pp->cmd_block) is no longer PAGE_SIZE. Based on feedback in another patch, I'm also converting the BUG_ONs to WARN_ON_ONCEs.

Side note: Please wrap you lines to 80 characters max.

Yes sorry, I turned off line wrapping for that last mail because I didn't want it to wrap the copy/pasted patch. I'll figure out how to mix and match for future.

Quoted 38 lines
Quoted 38 lines

Additional proposed change, which I'll plan to include in the next version:

---8<---

drivers/ata/sata_sil24.c +6 -2
index 85c6382976626..c402bf998c4ee 100644
@@ -257,6 +257,10 @@ union sil24_cmd_block {
        struct sil24_atapi_block atapi;
 };
 
+#define SIL24_ATA_BLOCK_SIZE   struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE)
+#define SIL24_ATAPI_BLOCK_SIZE struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE)
+#define SIL24_CMD_BLOCK_SIZE   max(SIL24_ATA_BLOCK_SIZE, SIL24_ATAPI_BLOCK_SIZE)
+
 static const struct sil24_cerr_info {
        unsigned int err_mask, action;
        const char *desc;
@@ -886,7 +890,7 @@ static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc)
        dma_addr_t paddr;
        void __iomem *activate;
 
-       paddr = pp->cmd_block_dma + tag * sizeof(*pp->cmd_block);
+       paddr = pp->cmd_block_dma + tag * SIL24_CMD_BLOCK_SIZE;
        activate = port + PORT_CMD_ACTIVATE + tag * 8;
 
        /*
@@ -1192,7 +1196,7 @@ static int sil24_port_start(struct ata_port *ap)
        struct device *dev = ap->host->dev;
        struct sil24_port_priv *pp;
        union sil24_cmd_block *cb;
-       size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
+       size_t cb_size = SIL24_CMD_BLOCK_SIZE * SIL24_MAX_CMDS;
        dma_addr_t cb_dma;
 
Quoted 8 lines

drivers/ata/sata_sil24.c static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) · line 1271

Quoted 5 lines
drivers/ata/sata_sil24.c +0 -0
        pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1265,8 +1269,8 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
        u32 tmp;
 
        /* union sil24_cmd_block must be PAGE_SIZE */

This comment should probably be rephrased to be more clear then, since like you said sizeof(union sil24_cmd_block) will no longer be PAGE_SIZE.

How about:

/*
* union sil24_cmd_block must be PAGE_SIZE once taking into account the 'sge'
* flexible array members in struct sil24_atapi_block and struct sil24_ata_block */

Quoted 9 lines
Quoted 9 lines
drivers/ata/sata_sil24.c +2 -3
-       BUG_ON(struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE) != PAGE_SIZE);
-       BUG_ON(struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE) > PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATAPI_BLOCK_SIZE != PAGE_SIZE);
+       WARN_ON_ONCE(SIL24_ATA_BLOCK_SIZE != PAGE_SIZE - 16);
 
        ata_print_version_once(&pdev->dev, DRV_VERSION);
---8<---
maintainer
#99 lore raw

Re: [RFC PATCH v1 34/57] sata_sil24: Remove PAGE_SIZE compile-time constant assumption

Quoted 61 lines · Ryan Roberts
Quoted 9 lines · Niklas Cassel
Quoted 2 lines · Ryan Roberts
Quoted 1 line · Niklas Cassel

On Thu, Oct 17, 2024 at 01:42:22PM +0100, Ryan Roberts wrote:

(snip)

Quoted 1 line

That said, while investigating this, I've spotted a bug in my change. paddr calculation in sil24_qc_issue() is incorrect since sizeof(*pp->cmd_block) is no longer PAGE_SIZE. Based on feedback in another patch, I'm also converting the BUG_ONs to WARN_ON_ONCEs.

Side note: Please wrap you lines to 80 characters max.

Yes sorry, I turned off line wrapping for that last mail because I didn't want it to wrap the copy/pasted patch. I'll figure out how to mix and match for future.

Quoted 38 lines
Quoted 38 lines

Additional proposed change, which I'll plan to include in the next version:

---8<---

drivers/ata/sata_sil24.c +6 -2
index 85c6382976626..c402bf998c4ee 100644
@@ -257,6 +257,10 @@ union sil24_cmd_block {
        struct sil24_atapi_block atapi;
 };
 
+#define SIL24_ATA_BLOCK_SIZE   struct_size_t(struct sil24_ata_block, sge, SIL24_MAX_SGE)
+#define SIL24_ATAPI_BLOCK_SIZE struct_size_t(struct sil24_atapi_block, sge, SIL24_MAX_SGE)
+#define SIL24_CMD_BLOCK_SIZE   max(SIL24_ATA_BLOCK_SIZE, SIL24_ATAPI_BLOCK_SIZE)
+
 static const struct sil24_cerr_info {
        unsigned int err_mask, action;
        const char *desc;
@@ -886,7 +890,7 @@ static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc)
        dma_addr_t paddr;
        void __iomem *activate;
 
-       paddr = pp->cmd_block_dma + tag * sizeof(*pp->cmd_block);
+       paddr = pp->cmd_block_dma + tag * SIL24_CMD_BLOCK_SIZE;
        activate = port + PORT_CMD_ACTIVATE + tag * 8;
 
        /*
@@ -1192,7 +1196,7 @@ static int sil24_port_start(struct ata_port *ap)
        struct device *dev = ap->host->dev;
        struct sil24_port_priv *pp;
        union sil24_cmd_block *cb;
-       size_t cb_size = PAGE_SIZE * SIL24_MAX_CMDS;
+       size_t cb_size = SIL24_CMD_BLOCK_SIZE * SIL24_MAX_CMDS;
        dma_addr_t cb_dma;
 
Quoted 8 lines

drivers/ata/sata_sil24.c static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) · line 1271

Quoted 5 lines
drivers/ata/sata_sil24.c +0 -0
        pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
@@ -1265,8 +1269,8 @@ static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
        u32 tmp;
 
        /* union sil24_cmd_block must be PAGE_SIZE */

This comment should probably be rephrased to be more clear then, since like you said sizeof(union sil24_cmd_block) will no longer be PAGE_SIZE.

Quoted 6 lines

How about:

/*
* union sil24_cmd_block must be PAGE_SIZE once taking into account the 'sge'
* flexible array members in struct sil24_atapi_block and struct sil24_ata_block */

Sounds good to me!

Kind regards,
Niklas

author reviewer
#100 lore raw

RFC PATCH 35/57 virtio: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Updated multiple BUILD_BUG_ON() instances to test against page size limits.

Wrap global variables that are initialized with PAGE_SIZE derived values using DEFINE_GLOBAL_PAGE_SIZE_VAR() so their initialization can be deferred for boot-time page size builds.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/block/virtio_blk.c      |  2 +-
 drivers/virtio/virtio_balloon.c | 10 ++++++----
 net/9p/trans_virtio.c           |  4 ++--
 3 files changed, 9 insertions(+), 7 deletions(-)
drivers/block/virtio_blk.c +1 -1
index 194417abc1053..8a8960b609bc9 100644
@@ -899,7 +899,7 @@ static ssize_t serial_show(struct device *dev,
 	int err;
 
 	/* sysfs gives us a PAGE_SIZE buffer */
-	BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
+	BUILD_BUG_ON(PAGE_SIZE_MIN < VIRTIO_BLK_ID_BYTES);
 
 	buf[VIRTIO_BLK_ID_BYTES] = '\0';
 	err = virtblk_get_id(disk, buf);
drivers/virtio/virtio_balloon.c +6 -4
index 54469277ca303..3818d894bd212 100644
@@ -25,6 +25,7 @@
  * page units.
  */
 #define VIRTIO_BALLOON_PAGES_PER_PAGE (unsigned int)(PAGE_SIZE >> VIRTIO_BALLOON_PFN_SHIFT)
+#define VIRTIO_BALLOON_PAGES_PER_PAGE_MAX (unsigned int)(PAGE_SIZE_MAX >> VIRTIO_BALLOON_PFN_SHIFT)
 #define VIRTIO_BALLOON_ARRAY_PFNS_MAX 256
 /* Maximum number of (4k) pages to deflate on OOM notifications. */
 #define VIRTIO_BALLOON_OOM_NR_PAGES 256
@@ -138,7 +139,7 @@ static u32 page_to_balloon_pfn(struct page *page)
 {
 	unsigned long pfn = page_to_pfn(page);
 
-	BUILD_BUG_ON(PAGE_SHIFT < VIRTIO_BALLOON_PFN_SHIFT);
+	BUILD_BUG_ON(PAGE_SHIFT_MIN < VIRTIO_BALLOON_PFN_SHIFT);
 	/* Convert pfn from Linux page size to balloon page size. */
 	return pfn * VIRTIO_BALLOON_PAGES_PER_PAGE;
 }
@@ -228,7 +229,7 @@ static void set_page_pfns(struct virtio_balloon *vb,
 {
 	unsigned int i;
 
-	BUILD_BUG_ON(VIRTIO_BALLOON_PAGES_PER_PAGE > VIRTIO_BALLOON_ARRAY_PFNS_MAX);
+	BUILD_BUG_ON(VIRTIO_BALLOON_PAGES_PER_PAGE_MAX > VIRTIO_BALLOON_ARRAY_PFNS_MAX);
 
 	/*
 	 * Set balloon pfns pointing at this page.
@@ -1042,8 +1043,9 @@ static int virtballoon_probe(struct virtio_device *vdev)
 		 * host's base page size. However, it needs more work to report
 		 * that value. The hard-coded order would be fine currently.
 		 */
-#if defined(CONFIG_ARM64) && defined(CONFIG_ARM64_64K_PAGES)
-		vb->pr_dev_info.order = 5;
+#if defined(CONFIG_ARM64)
+		if (PAGE_SIZE == SZ_64K)
+			vb->pr_dev_info.order = 5;
 #endif
 
 		err = page_reporting_register(&vb->pr_dev_info);
net/9p/trans_virtio.c +2 -2
index 0b8086f58ad55..25b8253011cec 100644
@@ -786,7 +786,7 @@ static struct virtio_driver p9_virtio_drv = {
 	.remove		= p9_virtio_remove,
 };
 
-static struct p9_trans_module p9_virtio_trans = {
+static DEFINE_GLOBAL_PAGE_SIZE_VAR(struct p9_trans_module, p9_virtio_trans, {
 	.name = "virtio",
 	.create = p9_virtio_create,
 	.close = p9_virtio_close,
@@ -804,7 +804,7 @@ static struct p9_trans_module p9_virtio_trans = {
 	.pooled_rbuffers = false,
 	.def = 1,
 	.owner = THIS_MODULE,
-};
+});
 
 /* The standard init function */
 static int __init p9_virtio_init(void)
Signature · 1 line
2.43.0
author reviewer
#101 lore raw

RFC PATCH 36/57 xen: Remove PAGE_SIZE compile-time constant assumption

In reply to Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Allocate enough "frame_list" static storage in the balloon driver for the maximum supported page size. Although continue to use only the first PAGE_SIZE of the buffer at run-time to maintain existing behaviour.

Refactor xen_biovec_phys_mergeable() to convert ifdeffery to c if/else. For compile-time page size, the compiler will choose one branch and strip the dead one. For boot-time, it can be evaluated at run time.

Refactor a BUILD_BUG_ON to evaluate the limit (when the minimum supported page size is selected at boot-time).

Reserve enough storage for max page size in "struct remap_data" and "struct xenbus_map_node".

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/xen/balloon.c              | 11 ++++++-----
 drivers/xen/biomerge.c             | 12 ++++++------
 drivers/xen/privcmd.c              |  2 +-
 drivers/xen/xenbus/xenbus_client.c |  5 +++--
 drivers/xen/xlate_mmu.c            |  6 +++---
 include/xen/page.h                 |  2 ++
 6 files changed, 21 insertions(+), 17 deletions(-)
drivers/xen/balloon.c +6 -5
index 528395133b4f8..0ed5f6453af0e 100644
@@ -131,7 +131,8 @@ struct balloon_stats balloon_stats;
 EXPORT_SYMBOL_GPL(balloon_stats);
 
 /* We increase/decrease in batches which fit in a page */
-static xen_pfn_t frame_list[PAGE_SIZE / sizeof(xen_pfn_t)];
+static xen_pfn_t frame_list[PAGE_SIZE_MAX / sizeof(xen_pfn_t)];
+#define FRAME_LIST_NR_ENTRIES (PAGE_SIZE / sizeof(xen_pfn_t))
 
 
 /* List of ballooned pages, threaded through the mem_map array. */
@@ -389,8 +390,8 @@ static enum bp_state increase_reservation(unsigned long nr_pages)
 	unsigned long i;
 	struct page   *page;
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	page = list_first_entry_or_null(&ballooned_pages, struct page, lru);
 	for (i = 0; i < nr_pages; i++) {
@@ -434,8 +435,8 @@ static enum bp_state decrease_reservation(unsigned long nr_pages, gfp_t gfp)
 	int ret;
 	LIST_HEAD(pages);
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	for (i = 0; i < nr_pages; i++) {
 		page = alloc_page(gfp);
drivers/xen/biomerge.c +6 -6
index 05a286d24f148..28f0887e40026 100644
@@ -8,16 +8,16 @@
 bool xen_biovec_phys_mergeable(const struct bio_vec *vec1,
 			       const struct page *page)
 {
-#if XEN_PAGE_SIZE == PAGE_SIZE
-	unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
-	unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+	if (XEN_PAGE_SIZE == PAGE_SIZE) {
+		unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
+		unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+
+		return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
+	}
 
-	return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
-#else
 	/*
 	 * XXX: Add support for merging bio_vec when using different page
 	 * size in Xen and Linux.
 	 */
 	return false;
-#endif
 }
drivers/xen/privcmd.c +1 -1
index 9563650dfbafc..847f7b806caf7 100644
@@ -557,7 +557,7 @@ static long privcmd_ioctl_mmap_batch(
 	state.global_error  = 0;
 	state.version       = version;
 
-	BUILD_BUG_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);
+	BUILD_BUG_ON(((PAGE_SIZE_MIN / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE_MAX) != 0);
 	/* mmap_batch_fn guarantees ret == 0 */
 	BUG_ON(traverse_pages_block(m.num, sizeof(xen_pfn_t),
 				    &pagelist, mmap_batch_fn, &state));
drivers/xen/xenbus/xenbus_client.c +3 -2
index 51b3124b0d56c..99bde836c10c4 100644
@@ -49,9 +49,10 @@
 
 #include "xenbus.h"
 
-#define XENBUS_PAGES(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES(_grants)		(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES_MAX(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE_MIN))
 
-#define XENBUS_MAX_RING_PAGES	(XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
+#define XENBUS_MAX_RING_PAGES		(XENBUS_PAGES_MAX(XENBUS_MAX_RING_GRANTS))
 
 struct xenbus_map_node {
 	struct list_head next;
drivers/xen/xlate_mmu.c +3 -3
index f17c4c03db30c..a757c801a7542 100644
@@ -74,9 +74,9 @@ struct remap_data {
 	int mapped;
 
 	/* Hypercall parameters */
-	int h_errs[XEN_PFN_PER_PAGE];
-	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE];
-	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE];
+	int h_errs[XEN_PFN_PER_PAGE_MAX];
+	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE_MAX];
+	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE_MAX];
 
 	int h_iter;	/* Iterator */
 };
include/xen/page.h +2 -0
index 285677b42943a..86683a30038a3 100644
@@ -21,6 +21,8 @@
 	((page_to_pfn(page)) << (PAGE_SHIFT - XEN_PAGE_SHIFT))
 
 #define XEN_PFN_PER_PAGE	(PAGE_SIZE / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MIN	(PAGE_SIZE_MIN / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MAX	(PAGE_SIZE_MAX / XEN_PAGE_SIZE)
 
 #define XEN_PFN_DOWN(x)	((x) >> XEN_PAGE_SHIFT)
 #define XEN_PFN_UP(x)	(((x) + XEN_PAGE_SIZE-1) >> XEN_PAGE_SHIFT)
Signature · 1 line
2.43.0
author reviewer
#102 lore raw

Re: [RFC PATCH v1 36/57] xen: Remove PAGE_SIZE compile-time constant assumption

+ Juergen Gross, Stefano Stabellini

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 156 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Allocate enough "frame_list" static storage in the balloon driver for the maximum supported page size. Although continue to use only the first PAGE_SIZE of the buffer at run-time to maintain existing behaviour.

Refactor xen_biovec_phys_mergeable() to convert ifdeffery to c if/else. For compile-time page size, the compiler will choose one branch and strip the dead one. For boot-time, it can be evaluated at run time.

Refactor a BUILD_BUG_ON to evaluate the limit (when the minimum supported page size is selected at boot-time).

Reserve enough storage for max page size in "struct remap_data" and "struct xenbus_map_node".

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/xen/balloon.c              | 11 ++++++-----
 drivers/xen/biomerge.c             | 12 ++++++------
 drivers/xen/privcmd.c              |  2 +-
 drivers/xen/xenbus/xenbus_client.c |  5 +++--
 drivers/xen/xlate_mmu.c            |  6 +++---
 include/xen/page.h                 |  2 ++
 6 files changed, 21 insertions(+), 17 deletions(-)
drivers/xen/balloon.c +6 -5
index 528395133b4f8..0ed5f6453af0e 100644
@@ -131,7 +131,8 @@ struct balloon_stats balloon_stats;
 EXPORT_SYMBOL_GPL(balloon_stats);
 
 /* We increase/decrease in batches which fit in a page */
-static xen_pfn_t frame_list[PAGE_SIZE / sizeof(xen_pfn_t)];
+static xen_pfn_t frame_list[PAGE_SIZE_MAX / sizeof(xen_pfn_t)];
+#define FRAME_LIST_NR_ENTRIES (PAGE_SIZE / sizeof(xen_pfn_t))
 
 
 /* List of ballooned pages, threaded through the mem_map array. */
@@ -389,8 +390,8 @@ static enum bp_state increase_reservation(unsigned long nr_pages)
 	unsigned long i;
 	struct page   *page;
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	page = list_first_entry_or_null(&ballooned_pages, struct page, lru);
 	for (i = 0; i < nr_pages; i++) {
@@ -434,8 +435,8 @@ static enum bp_state decrease_reservation(unsigned long nr_pages, gfp_t gfp)
 	int ret;
 	LIST_HEAD(pages);
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	for (i = 0; i < nr_pages; i++) {
 		page = alloc_page(gfp);
drivers/xen/biomerge.c +6 -6
index 05a286d24f148..28f0887e40026 100644
@@ -8,16 +8,16 @@
 bool xen_biovec_phys_mergeable(const struct bio_vec *vec1,
 			       const struct page *page)
 {
-#if XEN_PAGE_SIZE == PAGE_SIZE
-	unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
-	unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+	if (XEN_PAGE_SIZE == PAGE_SIZE) {
+		unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
+		unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+
+		return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
+	}
 
-	return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
-#else
 	/*
 	 * XXX: Add support for merging bio_vec when using different page
 	 * size in Xen and Linux.
 	 */
 	return false;
-#endif
 }
drivers/xen/privcmd.c +1 -1
index 9563650dfbafc..847f7b806caf7 100644
@@ -557,7 +557,7 @@ static long privcmd_ioctl_mmap_batch(
 	state.global_error  = 0;
 	state.version       = version;
 
-	BUILD_BUG_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);
+	BUILD_BUG_ON(((PAGE_SIZE_MIN / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE_MAX) != 0);
 	/* mmap_batch_fn guarantees ret == 0 */
 	BUG_ON(traverse_pages_block(m.num, sizeof(xen_pfn_t),
 				    &pagelist, mmap_batch_fn, &state));
drivers/xen/xenbus/xenbus_client.c +3 -2
index 51b3124b0d56c..99bde836c10c4 100644
@@ -49,9 +49,10 @@
 
 #include "xenbus.h"
 
-#define XENBUS_PAGES(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES(_grants)		(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES_MAX(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE_MIN))
 
-#define XENBUS_MAX_RING_PAGES	(XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
+#define XENBUS_MAX_RING_PAGES		(XENBUS_PAGES_MAX(XENBUS_MAX_RING_GRANTS))
 
 struct xenbus_map_node {
 	struct list_head next;
drivers/xen/xlate_mmu.c +3 -3
index f17c4c03db30c..a757c801a7542 100644
@@ -74,9 +74,9 @@ struct remap_data {
 	int mapped;
 
 	/* Hypercall parameters */
-	int h_errs[XEN_PFN_PER_PAGE];
-	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE];
-	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE];
+	int h_errs[XEN_PFN_PER_PAGE_MAX];
+	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE_MAX];
+	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE_MAX];
 
 	int h_iter;	/* Iterator */
 };
include/xen/page.h +2 -0
index 285677b42943a..86683a30038a3 100644
@@ -21,6 +21,8 @@
 	((page_to_pfn(page)) << (PAGE_SHIFT - XEN_PAGE_SHIFT))
 
 #define XEN_PFN_PER_PAGE	(PAGE_SIZE / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MIN	(PAGE_SIZE_MIN / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MAX	(PAGE_SIZE_MAX / XEN_PAGE_SIZE)
 
 #define XEN_PFN_DOWN(x)	((x) >> XEN_PAGE_SHIFT)
 #define XEN_PFN_UP(x)	(((x) + XEN_PAGE_SIZE-1) >> XEN_PAGE_SHIFT)
#103 lore raw

Re: [RFC PATCH v1 36/57] xen: Remove PAGE_SIZE compile-time constant assumption

+Julien

Quoted 115 lines · Ryan Roberts

+ Juergen Gross, Stefano Stabellini

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 104 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Allocate enough "frame_list" static storage in the balloon driver for the maximum supported page size. Although continue to use only the first PAGE_SIZE of the buffer at run-time to maintain existing behaviour.

Refactor xen_biovec_phys_mergeable() to convert ifdeffery to c if/else. For compile-time page size, the compiler will choose one branch and strip the dead one. For boot-time, it can be evaluated at run time.

Refactor a BUILD_BUG_ON to evaluate the limit (when the minimum supported page size is selected at boot-time).

Reserve enough storage for max page size in "struct remap_data" and "struct xenbus_map_node".

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/xen/balloon.c              | 11 ++++++-----
 drivers/xen/biomerge.c             | 12 ++++++------
 drivers/xen/privcmd.c              |  2 +-
 drivers/xen/xenbus/xenbus_client.c |  5 +++--
 drivers/xen/xlate_mmu.c            |  6 +++---
 include/xen/page.h                 |  2 ++
 6 files changed, 21 insertions(+), 17 deletions(-)
drivers/xen/balloon.c +6 -5
index 528395133b4f8..0ed5f6453af0e 100644
@@ -131,7 +131,8 @@ struct balloon_stats balloon_stats;
 EXPORT_SYMBOL_GPL(balloon_stats);
 
 /* We increase/decrease in batches which fit in a page */
-static xen_pfn_t frame_list[PAGE_SIZE / sizeof(xen_pfn_t)];
+static xen_pfn_t frame_list[PAGE_SIZE_MAX / sizeof(xen_pfn_t)];
+#define FRAME_LIST_NR_ENTRIES (PAGE_SIZE / sizeof(xen_pfn_t))
 
 
 /* List of ballooned pages, threaded through the mem_map array. */
@@ -389,8 +390,8 @@ static enum bp_state increase_reservation(unsigned long nr_pages)
 	unsigned long i;
 	struct page   *page;
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	page = list_first_entry_or_null(&ballooned_pages, struct page, lru);
 	for (i = 0; i < nr_pages; i++) {
@@ -434,8 +435,8 @@ static enum bp_state decrease_reservation(unsigned long nr_pages, gfp_t gfp)
 	int ret;
 	LIST_HEAD(pages);
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	for (i = 0; i < nr_pages; i++) {
 		page = alloc_page(gfp);
drivers/xen/biomerge.c +6 -6
index 05a286d24f148..28f0887e40026 100644
@@ -8,16 +8,16 @@
 bool xen_biovec_phys_mergeable(const struct bio_vec *vec1,
 			       const struct page *page)
 {
-#if XEN_PAGE_SIZE == PAGE_SIZE
-	unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
-	unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+	if (XEN_PAGE_SIZE == PAGE_SIZE) {
+		unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
+		unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+
+		return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
+	}
 
-	return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
-#else
 	/*
 	 * XXX: Add support for merging bio_vec when using different page
 	 * size in Xen and Linux.
 	 */
 	return false;
-#endif
 }
drivers/xen/privcmd.c +0 -0
index 9563650dfbafc..847f7b806caf7 100644
@@ -557,7 +557,7 @@ static long privcmd_ioctl_mmap_batch(
 	state.global_error  = 0;
 	state.version       = version;
 
Quoted 2 lines

drivers/xen/privcmd.c static long privcmd_ioctl_mmap_batch( · line 560

Quoted 2 lines
drivers/xen/privcmd.c +1 -1
-	BUILD_BUG_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);
+	BUILD_BUG_ON(((PAGE_SIZE_MIN / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE_MAX) != 0);

Is there any value in keep this test? And if so, what should it look like? I think we should turn it into a WARN_ON:

WARN_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);

It doesn't make much sense having a BUILD_BUG_ON on a variable that can change?

Quoted 51 lines
Quoted 50 lines
drivers/xen/privcmd.c +0 -0
 	/* mmap_batch_fn guarantees ret == 0 */
 	BUG_ON(traverse_pages_block(m.num, sizeof(xen_pfn_t),
 				    &pagelist, mmap_batch_fn, &state));
drivers/xen/xenbus/xenbus_client.c +3 -2
index 51b3124b0d56c..99bde836c10c4 100644
@@ -49,9 +49,10 @@
 
 #include "xenbus.h"
 
-#define XENBUS_PAGES(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES(_grants)		(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES_MAX(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE_MIN))
 
-#define XENBUS_MAX_RING_PAGES	(XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
+#define XENBUS_MAX_RING_PAGES		(XENBUS_PAGES_MAX(XENBUS_MAX_RING_GRANTS))
 
 struct xenbus_map_node {
 	struct list_head next;
drivers/xen/xlate_mmu.c +3 -3
index f17c4c03db30c..a757c801a7542 100644
@@ -74,9 +74,9 @@ struct remap_data {
 	int mapped;
 
 	/* Hypercall parameters */
-	int h_errs[XEN_PFN_PER_PAGE];
-	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE];
-	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE];
+	int h_errs[XEN_PFN_PER_PAGE_MAX];
+	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE_MAX];
+	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE_MAX];
 
 	int h_iter;	/* Iterator */
 };
include/xen/page.h +2 -0
index 285677b42943a..86683a30038a3 100644
@@ -21,6 +21,8 @@
 	((page_to_pfn(page)) << (PAGE_SHIFT - XEN_PAGE_SHIFT))
 
 #define XEN_PFN_PER_PAGE	(PAGE_SIZE / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MIN	(PAGE_SIZE_MIN / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MAX	(PAGE_SIZE_MAX / XEN_PAGE_SIZE)
 
 #define XEN_PFN_DOWN(x)	((x) >> XEN_PAGE_SHIFT)
 #define XEN_PFN_UP(x)	(((x) + XEN_PAGE_SIZE-1) >> XEN_PAGE_SHIFT)
author reviewer
#104 lore raw

Re: [RFC PATCH v1 36/57] xen: Remove PAGE_SIZE compile-time constant assumption

Quoted 124 lines · Stefano Stabellini

+Julien

Quoted 115 lines · Ryan Roberts

+ Juergen Gross, Stefano Stabellini

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 104 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Allocate enough "frame_list" static storage in the balloon driver for the maximum supported page size. Although continue to use only the first PAGE_SIZE of the buffer at run-time to maintain existing behaviour.

Refactor xen_biovec_phys_mergeable() to convert ifdeffery to c if/else. For compile-time page size, the compiler will choose one branch and strip the dead one. For boot-time, it can be evaluated at run time.

Refactor a BUILD_BUG_ON to evaluate the limit (when the minimum supported page size is selected at boot-time).

Reserve enough storage for max page size in "struct remap_data" and "struct xenbus_map_node".

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/xen/balloon.c              | 11 ++++++-----
 drivers/xen/biomerge.c             | 12 ++++++------
 drivers/xen/privcmd.c              |  2 +-
 drivers/xen/xenbus/xenbus_client.c |  5 +++--
 drivers/xen/xlate_mmu.c            |  6 +++---
 include/xen/page.h                 |  2 ++
 6 files changed, 21 insertions(+), 17 deletions(-)
drivers/xen/balloon.c +6 -5
index 528395133b4f8..0ed5f6453af0e 100644
@@ -131,7 +131,8 @@ struct balloon_stats balloon_stats;
 EXPORT_SYMBOL_GPL(balloon_stats);
 
 /* We increase/decrease in batches which fit in a page */
-static xen_pfn_t frame_list[PAGE_SIZE / sizeof(xen_pfn_t)];
+static xen_pfn_t frame_list[PAGE_SIZE_MAX / sizeof(xen_pfn_t)];
+#define FRAME_LIST_NR_ENTRIES (PAGE_SIZE / sizeof(xen_pfn_t))
 
 
 /* List of ballooned pages, threaded through the mem_map array. */
@@ -389,8 +390,8 @@ static enum bp_state increase_reservation(unsigned long nr_pages)
 	unsigned long i;
 	struct page   *page;
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	page = list_first_entry_or_null(&ballooned_pages, struct page, lru);
 	for (i = 0; i < nr_pages; i++) {
@@ -434,8 +435,8 @@ static enum bp_state decrease_reservation(unsigned long nr_pages, gfp_t gfp)
 	int ret;
 	LIST_HEAD(pages);
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	for (i = 0; i < nr_pages; i++) {
 		page = alloc_page(gfp);
drivers/xen/biomerge.c +6 -6
index 05a286d24f148..28f0887e40026 100644
@@ -8,16 +8,16 @@
 bool xen_biovec_phys_mergeable(const struct bio_vec *vec1,
 			       const struct page *page)
 {
-#if XEN_PAGE_SIZE == PAGE_SIZE
-	unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
-	unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+	if (XEN_PAGE_SIZE == PAGE_SIZE) {
+		unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
+		unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+
+		return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
+	}
 
-	return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
-#else
 	/*
 	 * XXX: Add support for merging bio_vec when using different page
 	 * size in Xen and Linux.
 	 */
 	return false;
-#endif
 }
drivers/xen/privcmd.c +0 -0
index 9563650dfbafc..847f7b806caf7 100644
@@ -557,7 +557,7 @@ static long privcmd_ioctl_mmap_batch(
 	state.global_error  = 0;
 	state.version       = version;
 
Quoted 2 lines

drivers/xen/privcmd.c static long privcmd_ioctl_mmap_batch( · line 560

Quoted 2 lines
drivers/xen/privcmd.c +1 -1
-	BUILD_BUG_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);
+	BUILD_BUG_ON(((PAGE_SIZE_MIN / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE_MAX) != 0);

Is there any value in keep this test? And if so, what should it look like? I think we should turn it into a WARN_ON:

Quoted 4 lines

WARN_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);

It doesn't make much sense having a BUILD_BUG_ON on a variable that can change?

I believe that as long as we assume sizeof(xen_pfn_t), PAGE_SIZE and XEN_PAGE_SIZE are all power-of-two sizes, then this single build-time test should cover all possible boot-time PAGE_SIZEs.

Logic:

If PAGE_SIZE and XEN_PAGE_SIZE are power-of-two, then XEN_PFN_PER_PAGE must also be power-of-two. XEN_PFN_PER_PAGE_MAX is just the worst case limit.

(PAGE_SIZE_MIN / sizeof(xen_pfn_t)) is the number of xen_pfn_t that fit on smallest page.

If you can get an integer multiple number of XEN_PFN_PER_PAGE_MAX on the smallest page, then it remains an integer multiple as PAGE_SIZE gets bigger, assuming it is restricted to power-of-two sizes.

Perhaps there is a floor in my logic?

I'd prefer to keep BUILD_BUG_ON where possible to avoid the additional image size bloat and runtime costs.

Thanks,
Ryan

Quoted 53 lines
Quoted 53 lines
Quoted 52 lines
drivers/xen/privcmd.c +0 -0
 	/* mmap_batch_fn guarantees ret == 0 */
 	BUG_ON(traverse_pages_block(m.num, sizeof(xen_pfn_t),
 				    &pagelist, mmap_batch_fn, &state));
drivers/xen/xenbus/xenbus_client.c +3 -2
index 51b3124b0d56c..99bde836c10c4 100644
@@ -49,9 +49,10 @@
 
 #include "xenbus.h"
 
-#define XENBUS_PAGES(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES(_grants)		(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES_MAX(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE_MIN))
 
-#define XENBUS_MAX_RING_PAGES	(XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
+#define XENBUS_MAX_RING_PAGES		(XENBUS_PAGES_MAX(XENBUS_MAX_RING_GRANTS))
 
 struct xenbus_map_node {
 	struct list_head next;
drivers/xen/xlate_mmu.c +3 -3
index f17c4c03db30c..a757c801a7542 100644
@@ -74,9 +74,9 @@ struct remap_data {
 	int mapped;
 
 	/* Hypercall parameters */
-	int h_errs[XEN_PFN_PER_PAGE];
-	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE];
-	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE];
+	int h_errs[XEN_PFN_PER_PAGE_MAX];
+	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE_MAX];
+	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE_MAX];
 
 	int h_iter;	/* Iterator */
 };
include/xen/page.h +2 -0
index 285677b42943a..86683a30038a3 100644
@@ -21,6 +21,8 @@
 	((page_to_pfn(page)) << (PAGE_SHIFT - XEN_PAGE_SHIFT))
 
 #define XEN_PFN_PER_PAGE	(PAGE_SIZE / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MIN	(PAGE_SIZE_MIN / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MAX	(PAGE_SIZE_MAX / XEN_PAGE_SIZE)
 
 #define XEN_PFN_DOWN(x)	((x) >> XEN_PAGE_SHIFT)
 #define XEN_PFN_UP(x)	(((x) + XEN_PAGE_SIZE-1) >> XEN_PAGE_SHIFT)
maintainer Reviewed-by
#105 lore raw

Re: [RFC PATCH v1 36/57] xen: Remove PAGE_SIZE compile-time constant assumption

Quoted 142 lines · Ryan Roberts
Quoted 124 lines · Stefano Stabellini

+Julien

Quoted 115 lines · Ryan Roberts

+ Juergen Gross, Stefano Stabellini

This was a rather tricky series to get the recipients correct for and my script did not realize that "supporter" was a pseudonym for "maintainer" so you were missed off the original post. Appologies!

More context in cover letter:
https://lore.kernel.org/all/[email protected]/

Quoted 104 lines · Ryan Roberts

To prepare for supporting boot-time page size selection, refactor code to remove assumptions about PAGE_SIZE being compile-time constant. Code intended to be equivalent when compile-time page size is active.

Allocate enough "frame_list" static storage in the balloon driver for the maximum supported page size. Although continue to use only the first PAGE_SIZE of the buffer at run-time to maintain existing behaviour.

Refactor xen_biovec_phys_mergeable() to convert ifdeffery to c if/else. For compile-time page size, the compiler will choose one branch and strip the dead one. For boot-time, it can be evaluated at run time.

Refactor a BUILD_BUG_ON to evaluate the limit (when the minimum supported page size is selected at boot-time).

Reserve enough storage for max page size in "struct remap_data" and "struct xenbus_map_node".

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 drivers/xen/balloon.c              | 11 ++++++-----
 drivers/xen/biomerge.c             | 12 ++++++------
 drivers/xen/privcmd.c              |  2 +-
 drivers/xen/xenbus/xenbus_client.c |  5 +++--
 drivers/xen/xlate_mmu.c            |  6 +++---
 include/xen/page.h                 |  2 ++
 6 files changed, 21 insertions(+), 17 deletions(-)
drivers/xen/balloon.c +6 -5
index 528395133b4f8..0ed5f6453af0e 100644
@@ -131,7 +131,8 @@ struct balloon_stats balloon_stats;
 EXPORT_SYMBOL_GPL(balloon_stats);
 
 /* We increase/decrease in batches which fit in a page */
-static xen_pfn_t frame_list[PAGE_SIZE / sizeof(xen_pfn_t)];
+static xen_pfn_t frame_list[PAGE_SIZE_MAX / sizeof(xen_pfn_t)];
+#define FRAME_LIST_NR_ENTRIES (PAGE_SIZE / sizeof(xen_pfn_t))
 
 
 /* List of ballooned pages, threaded through the mem_map array. */
@@ -389,8 +390,8 @@ static enum bp_state increase_reservation(unsigned long nr_pages)
 	unsigned long i;
 	struct page   *page;
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	page = list_first_entry_or_null(&ballooned_pages, struct page, lru);
 	for (i = 0; i < nr_pages; i++) {
@@ -434,8 +435,8 @@ static enum bp_state decrease_reservation(unsigned long nr_pages, gfp_t gfp)
 	int ret;
 	LIST_HEAD(pages);
 
-	if (nr_pages > ARRAY_SIZE(frame_list))
-		nr_pages = ARRAY_SIZE(frame_list);
+	if (nr_pages > FRAME_LIST_NR_ENTRIES)
+		nr_pages = FRAME_LIST_NR_ENTRIES;
 
 	for (i = 0; i < nr_pages; i++) {
 		page = alloc_page(gfp);
drivers/xen/biomerge.c +6 -6
index 05a286d24f148..28f0887e40026 100644
@@ -8,16 +8,16 @@
 bool xen_biovec_phys_mergeable(const struct bio_vec *vec1,
 			       const struct page *page)
 {
-#if XEN_PAGE_SIZE == PAGE_SIZE
-	unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
-	unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+	if (XEN_PAGE_SIZE == PAGE_SIZE) {
+		unsigned long bfn1 = pfn_to_bfn(page_to_pfn(vec1->bv_page));
+		unsigned long bfn2 = pfn_to_bfn(page_to_pfn(page));
+
+		return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
+	}
 
-	return bfn1 + PFN_DOWN(vec1->bv_offset + vec1->bv_len) == bfn2;
-#else
 	/*
 	 * XXX: Add support for merging bio_vec when using different page
 	 * size in Xen and Linux.
 	 */
 	return false;
-#endif
 }
drivers/xen/privcmd.c +0 -0
index 9563650dfbafc..847f7b806caf7 100644
@@ -557,7 +557,7 @@ static long privcmd_ioctl_mmap_batch(
 	state.global_error  = 0;
 	state.version       = version;
 
Quoted 2 lines

drivers/xen/privcmd.c static long privcmd_ioctl_mmap_batch( · line 560

Quoted 2 lines
drivers/xen/privcmd.c +1 -1
-	BUILD_BUG_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);
+	BUILD_BUG_ON(((PAGE_SIZE_MIN / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE_MAX) != 0);

Is there any value in keep this test? And if so, what should it look like? I think we should turn it into a WARN_ON:

Quoted 4 lines

WARN_ON(((PAGE_SIZE / sizeof(xen_pfn_t)) % XEN_PFN_PER_PAGE) != 0);

It doesn't make much sense having a BUILD_BUG_ON on a variable that can change?

I believe that as long as we assume sizeof(xen_pfn_t), PAGE_SIZE and XEN_PAGE_SIZE are all power-of-two sizes, then this single build-time test should cover all possible boot-time PAGE_SIZEs.

Logic:

If PAGE_SIZE and XEN_PAGE_SIZE are power-of-two, then XEN_PFN_PER_PAGE must also be power-of-two. XEN_PFN_PER_PAGE_MAX is just the worst case limit.

(PAGE_SIZE_MIN / sizeof(xen_pfn_t)) is the number of xen_pfn_t that fit on smallest page.

Quoted 8 lines

If you can get an integer multiple number of XEN_PFN_PER_PAGE_MAX on the smallest page, then it remains an integer multiple as PAGE_SIZE gets bigger, assuming it is restricted to power-of-two sizes.

Perhaps there is a floor in my logic?

I'd prefer to keep BUILD_BUG_ON where possible to avoid the additional image size bloat and runtime costs.

You are right. It would be nice to add a in-code comment to explain this.

Quoted 52 lines
Quoted 51 lines
Quoted 51 lines
Quoted 50 lines
drivers/xen/privcmd.c +0 -0
 	/* mmap_batch_fn guarantees ret == 0 */
 	BUG_ON(traverse_pages_block(m.num, sizeof(xen_pfn_t),
 				    &pagelist, mmap_batch_fn, &state));
drivers/xen/xenbus/xenbus_client.c +3 -2
index 51b3124b0d56c..99bde836c10c4 100644
@@ -49,9 +49,10 @@
 
 #include "xenbus.h"
 
-#define XENBUS_PAGES(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES(_grants)		(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
+#define XENBUS_PAGES_MAX(_grants)	(DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE_MIN))
 
-#define XENBUS_MAX_RING_PAGES	(XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
+#define XENBUS_MAX_RING_PAGES		(XENBUS_PAGES_MAX(XENBUS_MAX_RING_GRANTS))
 
 struct xenbus_map_node {
 	struct list_head next;
drivers/xen/xlate_mmu.c +3 -3
index f17c4c03db30c..a757c801a7542 100644
@@ -74,9 +74,9 @@ struct remap_data {
 	int mapped;
 
 	/* Hypercall parameters */
-	int h_errs[XEN_PFN_PER_PAGE];
-	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE];
-	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE];
+	int h_errs[XEN_PFN_PER_PAGE_MAX];
+	xen_ulong_t h_idxs[XEN_PFN_PER_PAGE_MAX];
+	xen_pfn_t h_gpfns[XEN_PFN_PER_PAGE_MAX];
 
 	int h_iter;	/* Iterator */
 };
include/xen/page.h +2 -0
index 285677b42943a..86683a30038a3 100644
@@ -21,6 +21,8 @@
 	((page_to_pfn(page)) << (PAGE_SHIFT - XEN_PAGE_SHIFT))
 
 #define XEN_PFN_PER_PAGE	(PAGE_SIZE / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MIN	(PAGE_SIZE_MIN / XEN_PAGE_SIZE)
+#define XEN_PFN_PER_PAGE_MAX	(PAGE_SIZE_MAX / XEN_PAGE_SIZE)
 
 #define XEN_PFN_DOWN(x)	((x) >> XEN_PAGE_SHIFT)
 #define XEN_PFN_UP(x)	(((x) + XEN_PAGE_SIZE-1) >> XEN_PAGE_SHIFT)
author reviewer
#106 lore raw

RFC PATCH 37/57 arm64: Fix macros to work in C code in addition to the linker script

In reply to Ryan Roberts

Previously INIT_DIR_SIZE and INIT_IDMAP_DIR_SIZE used _end for the end address of the kernel image. In the linker script context, this resolves to an integer that refers to the link va of the end of the kernel image. But in C code it resolves to a pointer to the end of the image as placed in memory. So there are 2 problems; because its a pointer, we can't do arithmetic on it. And because the image may be in a different location in memory than the one it was linked at, it is not correct to find the image size by subtracting KIMAGE_VADDR.

So introduce KIMAGE_VADDR_END, which always represents the link va of the end of the kernel image as an integer.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/kernel-pgtable.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kernel-pgtable.h +4 -2
index bf05a77873a49..1722b9217d47d 100644
@@ -35,6 +35,8 @@
 #define IDMAP_LEVELS		ARM64_HW_PGTABLE_LEVELS(IDMAP_VA_BITS)
 #define IDMAP_ROOT_LEVEL	(4 - IDMAP_LEVELS)
 
+#define KIMAGE_VADDR_END	(_AT(u64, _end) - _AT(u64, _text) + KIMAGE_VADDR)
+
 /*
  * A relocatable kernel may execute from an address that differs from the one at
  * which it was linked. In the worst case, its runtime placement may intersect
@@ -56,10 +58,10 @@
 	+ EARLY_LEVEL(3, (lvls), (vstart), (vend), add) /* each entry needs a next level page table */	\
 	+ EARLY_LEVEL(2, (lvls), (vstart), (vend), add)	/* each entry needs a next level page table */	\
 	+ EARLY_LEVEL(1, (lvls), (vstart), (vend), add))/* each entry needs a next level page table */
-#define INIT_DIR_SIZE (PAGE_SIZE * (EARLY_PAGES(SWAPPER_PGTABLE_LEVELS, KIMAGE_VADDR, _end, EXTRA_PAGE) \
+#define INIT_DIR_SIZE (PAGE_SIZE * (EARLY_PAGES(SWAPPER_PGTABLE_LEVELS, KIMAGE_VADDR, KIMAGE_VADDR_END, EXTRA_PAGE) \
 				    + EARLY_SEGMENT_EXTRA_PAGES))
 
-#define INIT_IDMAP_DIR_PAGES	(EARLY_PAGES(INIT_IDMAP_PGTABLE_LEVELS, KIMAGE_VADDR, _end, 1))
+#define INIT_IDMAP_DIR_PAGES	(EARLY_PAGES(INIT_IDMAP_PGTABLE_LEVELS, KIMAGE_VADDR, KIMAGE_VADDR_END, 1))
 #define INIT_IDMAP_DIR_SIZE	((INIT_IDMAP_DIR_PAGES + EARLY_IDMAP_EXTRA_PAGES) * PAGE_SIZE)
 
 #define INIT_IDMAP_FDT_PAGES	(EARLY_PAGES(INIT_IDMAP_PGTABLE_LEVELS, 0UL, UL(MAX_FDT_SIZE), 1) - 1)
Signature · 1 line
2.43.0
author reviewer
#107 lore raw

RFC PATCH 38/57 arm64: Track early pgtable allocation limit

In reply to Ryan Roberts

Early pgtables (e.g. init_idmap_pg_dir, init_pg_dir, etc) are allocated from statically defined memory blocks within the kernel image that are sized for the calculated worst case requirements. Let's make the allocator aware of the block's limit so that it can detect any overflow.

This boils down to passing the limit of the memory block to map_range() so let's add it as a parameter. If an overflow is detected, report the error to __early_cpu_boot_status and park the cpu.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/smp.h      |  1 +
 arch/arm64/kernel/head.S          |  3 +-
 arch/arm64/kernel/image-vars.h    |  3 ++
 arch/arm64/kernel/pi/map_kernel.c | 35 +++++++++++---------
 arch/arm64/kernel/pi/map_range.c  | 54 +++++++++++++++++++++++++------
 arch/arm64/kernel/pi/pi.h         |  4 +--
 arch/arm64/mm/mmu.c               | 14 +++++---
 7 files changed, 81 insertions(+), 33 deletions(-)
arch/arm64/include/asm/smp.h +1 -0
index 2510eec026f7e..86edc5f8c9673 100644
@@ -22,6 +22,7 @@
 
 #define CPU_STUCK_REASON_52_BIT_VA	(UL(1) << CPU_STUCK_REASON_SHIFT)
 #define CPU_STUCK_REASON_NO_GRAN	(UL(2) << CPU_STUCK_REASON_SHIFT)
+#define CPU_STUCK_REASON_NO_PGTABLE_MEM	(UL(3) << CPU_STUCK_REASON_SHIFT)
 
 #ifndef __ASSEMBLY__
 
arch/arm64/kernel/head.S +2 -1
index cb68adcabe078..7e17a71fd9e4b 100644
@@ -89,7 +89,8 @@ SYM_CODE_START(primary_entry)
 	mov	sp, x1
 	mov	x29, xzr
 	adrp	x0, init_idmap_pg_dir
-	mov	x1, xzr
+	adrp	x1, init_idmap_pg_end
+	mov	x2, xzr
 	bl	__pi_create_init_idmap
 
 	/*
arch/arm64/kernel/image-vars.h +3 -0
index 8f5422ed1b758..a168f3337446f 100644
@@ -52,6 +52,7 @@ PROVIDE(__pi_cavium_erratum_27456_cpus	= cavium_erratum_27456_cpus);
 #endif
 PROVIDE(__pi__ctype			= _ctype);
 PROVIDE(__pi_memstart_offset_seed	= memstart_offset_seed);
+PROVIDE(__pi___early_cpu_boot_status	= __early_cpu_boot_status);
 
 PROVIDE(__pi_init_idmap_pg_dir		= init_idmap_pg_dir);
 PROVIDE(__pi_init_idmap_pg_end		= init_idmap_pg_end);
@@ -68,6 +69,8 @@ PROVIDE(__pi___inittext_end       	= __inittext_end);
 PROVIDE(__pi___initdata_begin     	= __initdata_begin);
 PROVIDE(__pi___initdata_end       	= __initdata_end);
 PROVIDE(__pi__data                	= _data);
+PROVIDE(__pi___mmuoff_data_start	= __mmuoff_data_start);
+PROVIDE(__pi___mmuoff_data_end		= __mmuoff_data_end);
 PROVIDE(__pi___bss_start		= __bss_start);
 PROVIDE(__pi__end			= _end);
 
arch/arm64/kernel/pi/map_kernel.c +19 -16
index f374a3e5a5fe1..dcf9233ccfff2 100644
@@ -20,11 +20,11 @@ extern const u8 __eh_frame_start[], __eh_frame_end[];
 
 extern void idmap_cpu_replace_ttbr1(void *pgdir);
 
-static void __init map_segment(pgd_t *pg_dir, u64 *pgd, u64 va_offset,
-			       void *start, void *end, pgprot_t prot,
-			       bool may_use_cont, int root_level)
+static void __init map_segment(pgd_t *pg_dir, u64 *pgd, u64 limit,
+			       u64 va_offset, void *start, void *end,
+			       pgprot_t prot, bool may_use_cont, int root_level)
 {
-	map_range(pgd, ((u64)start + va_offset) & ~PAGE_OFFSET,
+	map_range(pgd, limit, ((u64)start + va_offset) & ~PAGE_OFFSET,
 		  ((u64)end + va_offset) & ~PAGE_OFFSET, (u64)start,
 		  prot, root_level, (pte_t *)pg_dir, may_use_cont, 0);
 }
@@ -32,7 +32,7 @@ static void __init map_segment(pgd_t *pg_dir, u64 *pgd, u64 va_offset,
 static void __init unmap_segment(pgd_t *pg_dir, u64 va_offset, void *start,
 				 void *end, int root_level)
 {
-	map_segment(pg_dir, NULL, va_offset, start, end, __pgprot(0),
+	map_segment(pg_dir, NULL, 0, va_offset, start, end, __pgprot(0),
 		    false, root_level);
 }
 
@@ -41,6 +41,7 @@ static void __init map_kernel(u64 kaslr_offset, u64 va_offset, int root_level)
 	bool enable_scs = IS_ENABLED(CONFIG_UNWIND_PATCH_PAC_INTO_SCS);
 	bool twopass = IS_ENABLED(CONFIG_RELOCATABLE);
 	u64 pgdp = (u64)init_pg_dir + PAGE_SIZE;
+	u64 limit = (u64)init_pg_end;
 	pgprot_t text_prot = PAGE_KERNEL_ROX;
 	pgprot_t data_prot = PAGE_KERNEL;
 	pgprot_t prot;
@@ -78,16 +79,16 @@ static void __init map_kernel(u64 kaslr_offset, u64 va_offset, int root_level)
 	twopass |= enable_scs;
 	prot = twopass ? data_prot : text_prot;
 
-	map_segment(init_pg_dir, &pgdp, va_offset, _stext, _etext, prot,
+	map_segment(init_pg_dir, &pgdp, limit, va_offset, _stext, _etext, prot,
 		    !twopass, root_level);
-	map_segment(init_pg_dir, &pgdp, va_offset, __start_rodata,
+	map_segment(init_pg_dir, &pgdp, limit, va_offset, __start_rodata,
 		    __inittext_begin, data_prot, false, root_level);
-	map_segment(init_pg_dir, &pgdp, va_offset, __inittext_begin,
+	map_segment(init_pg_dir, &pgdp, limit, va_offset, __inittext_begin,
 		    __inittext_end, prot, false, root_level);
-	map_segment(init_pg_dir, &pgdp, va_offset, __initdata_begin,
+	map_segment(init_pg_dir, &pgdp, limit, va_offset, __initdata_begin,
 		    __initdata_end, data_prot, false, root_level);
-	map_segment(init_pg_dir, &pgdp, va_offset, _data, _end, data_prot,
-		    true, root_level);
+	map_segment(init_pg_dir, &pgdp, limit, va_offset, _data, _end,
+		    data_prot, true, root_level);
 	dsb(ishst);
 
 	idmap_cpu_replace_ttbr1(init_pg_dir);
@@ -120,9 +121,9 @@ static void __init map_kernel(u64 kaslr_offset, u64 va_offset, int root_level)
 		 * Remap these segments with different permissions
 		 * No new page table allocations should be needed
 		 */
-		map_segment(init_pg_dir, NULL, va_offset, _stext, _etext,
+		map_segment(init_pg_dir, NULL, 0, va_offset, _stext, _etext,
 			    text_prot, true, root_level);
-		map_segment(init_pg_dir, NULL, va_offset, __inittext_begin,
+		map_segment(init_pg_dir, NULL, 0, va_offset, __inittext_begin,
 			    __inittext_end, text_prot, false, root_level);
 	}
 
@@ -164,7 +165,7 @@ static void __init remap_idmap_for_lpa2(void)
 	 * LPA2 compatible fashion, and update the initial ID map while running
 	 * from that.
 	 */
-	create_init_idmap(init_pg_dir, mask);
+	create_init_idmap(init_pg_dir, init_pg_end, mask);
 	dsb(ishst);
 	set_ttbr0_for_lpa2((u64)init_pg_dir);
 
@@ -175,7 +176,7 @@ static void __init remap_idmap_for_lpa2(void)
 	memset(init_idmap_pg_dir, 0,
 	       (u64)init_idmap_pg_end - (u64)init_idmap_pg_dir);
 
-	create_init_idmap(init_idmap_pg_dir, mask);
+	create_init_idmap(init_idmap_pg_dir, init_idmap_pg_end, mask);
 	dsb(ishst);
 
 	/* switch back to the updated initial ID map */
@@ -188,6 +189,7 @@ static void __init remap_idmap_for_lpa2(void)
 static void __init map_fdt(u64 fdt)
 {
 	static u8 ptes[INIT_IDMAP_FDT_SIZE] __initdata __aligned(PAGE_SIZE);
+	u64 limit = (u64)&ptes[INIT_IDMAP_FDT_SIZE];
 	u64 efdt = fdt + MAX_FDT_SIZE;
 	u64 ptep = (u64)ptes;
 
@@ -195,7 +197,8 @@ static void __init map_fdt(u64 fdt)
 	 * Map up to MAX_FDT_SIZE bytes, but avoid overlap with
 	 * the kernel image.
 	 */
-	map_range(&ptep, fdt, (u64)_text > fdt ? min((u64)_text, efdt) : efdt,
+	map_range(&ptep, limit, fdt,
+		  (u64)_text > fdt ? min((u64)_text, efdt) : efdt,
 		  fdt, PAGE_KERNEL, IDMAP_ROOT_LEVEL,
 		  (pte_t *)init_idmap_pg_dir, false, 0);
 	dsb(ishst);
arch/arm64/kernel/pi/map_range.c +45 -9

92 lines not on this page · raw message

arch/arm64/kernel/pi/pi.h +2 -2
index c91e5e965cd39..20fe0941cb8ee 100644
@@ -28,9 +28,9 @@ u64 kaslr_early_init(void *fdt, int chosen);
 void relocate_kernel(u64 offset);
 int scs_patch(const u8 eh_frame[], int size);
 
-void map_range(u64 *pgd, u64 start, u64 end, u64 pa, pgprot_t prot,
+void map_range(u64 *pgd, u64 limit, u64 start, u64 end, u64 pa, pgprot_t prot,
 	       int level, pte_t *tbl, bool may_use_cont, u64 va_offset);
 
 asmlinkage void early_map_kernel(u64 boot_status, void *fdt);
 
-asmlinkage u64 create_init_idmap(pgd_t *pgd, pteval_t clrmask);
+asmlinkage u64 create_init_idmap(pgd_t *pgd, pgd_t *pg_end, pteval_t clrmask);
arch/arm64/mm/mmu.c +9 -5
index 353ea5dc32b85..969348a2e93c9 100644
@@ -773,8 +773,9 @@ static void __init declare_kernel_vmas(void)
 	declare_vma(&vmlinux_seg[4], _data, _end, 0);
 }
 
-void __pi_map_range(u64 *pgd, u64 start, u64 end, u64 pa, pgprot_t prot,
-		    int level, pte_t *tbl, bool may_use_cont, u64 va_offset);
+void __pi_map_range(u64 *pgd, u64 limit, u64 start, u64 end, u64 pa,
+		    pgprot_t prot, int level, pte_t *tbl, bool may_use_cont,
+		    u64 va_offset);
 
 static u8 idmap_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
 	  kpti_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
@@ -784,8 +785,9 @@ static void __init create_idmap(void)
 	u64 start = __pa_symbol(__idmap_text_start);
 	u64 end   = __pa_symbol(__idmap_text_end);
 	u64 ptep  = __pa_symbol(idmap_ptes);
+	u64 limit  = __pa_symbol(&idmap_ptes[IDMAP_LEVELS - 1][0]);
 
-	__pi_map_range(&ptep, start, end, start, PAGE_KERNEL_ROX,
+	__pi_map_range(&ptep, limit, start, end, start, PAGE_KERNEL_ROX,
 		       IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
 		       __phys_to_virt(ptep) - ptep);
 
@@ -798,8 +800,10 @@ static void __init create_idmap(void)
 		 * of its synchronization flag in the ID map.
 		 */
 		ptep = __pa_symbol(kpti_ptes);
-		__pi_map_range(&ptep, pa, pa + sizeof(u32), pa, PAGE_KERNEL,
-			       IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
+		limit  = __pa_symbol(&kpti_ptes[IDMAP_LEVELS - 1][0]);
+		__pi_map_range(&ptep, limit, pa, pa + sizeof(u32), pa,
+			       PAGE_KERNEL, IDMAP_ROOT_LEVEL,
+			       (pte_t *)idmap_pg_dir, false,
 			       __phys_to_virt(ptep) - ptep);
 	}
 }
Signature · 1 line
2.43.0
author reviewer
#108 lore raw

RFC PATCH 39/57 arm64: Introduce macros required for boot-time page selection

In reply to Ryan Roberts

This minmal set of macros will allow boot-time page selection support to be added to the arm64 arch code incrementally over the following set of patches.

The definitions in pgtable-geometry.h are for compile-time page size currently, but they will be modified in future to support boot-time page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/page-def.h         |  5 ++--
 arch/arm64/include/asm/pgtable-geometry.h | 28 +++++++++++++++++++++++
 arch/arm64/include/asm/pgtable-hwdef.h    | 16 ++++++++-----
 3 files changed, 40 insertions(+), 9 deletions(-)
 create mode 100644 arch/arm64/include/asm/pgtable-geometry.h
arch/arm64/include/asm/page-def.h +2 -3
index d69971cf49cd2..b99dee0112463 100644
@@ -9,12 +9,11 @@
 #define __ASM_PAGE_DEF_H
 
 #include <linux/const.h>
+#include <asm/pgtable-geometry.h>
 
 /* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT		CONFIG_PAGE_SHIFT
+#define PAGE_SHIFT		ptg_page_shift
 #define PAGE_SIZE		(_AC(1, UL) << PAGE_SHIFT)
 #define PAGE_MASK		(~(PAGE_SIZE-1))
 
-#include <asm-generic/pgtable-geometry.h>
-
 #endif /* __ASM_PAGE_DEF_H */
arch/arm64/include/asm/pgtable-geometry.h new file +28 -0
new file mode 100644
index 0000000000000..62fe125909c08
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef ASM_PGTABLE_GEOMETRY_H
+#define ASM_PGTABLE_GEOMETRY_H
+
+#define ARM64_PAGE_SHIFT_4K	12
+#define ARM64_PAGE_SHIFT_16K	14
+#define ARM64_PAGE_SHIFT_64K	16
+
+#define PAGE_SHIFT_MIN		CONFIG_PAGE_SHIFT
+#define PAGE_SIZE_MIN		(_AC(1, UL) << PAGE_SHIFT_MIN)
+#define PAGE_MASK_MIN		(~(PAGE_SIZE_MIN-1))
+
+#define PAGE_SHIFT_MAX		CONFIG_PAGE_SHIFT
+#define PAGE_SIZE_MAX		(_AC(1, UL) << PAGE_SHIFT_MAX)
+#define PAGE_MASK_MAX		(~(PAGE_SIZE_MAX-1))
+
+#include <asm-generic/pgtable-geometry.h>
+
+#define ptg_page_shift		CONFIG_PAGE_SHIFT
+#define ptg_pmd_shift		ARM64_HW_PGTABLE_LEVEL_SHIFT(2)
+#define ptg_pud_shift		ARM64_HW_PGTABLE_LEVEL_SHIFT(1)
+#define ptg_p4d_shift		ARM64_HW_PGTABLE_LEVEL_SHIFT(0)
+#define ptg_pgdir_shift		ARM64_HW_PGTABLE_LEVEL_SHIFT(4 - CONFIG_PGTABLE_LEVELS)
+#define ptg_cont_pte_shift	(CONFIG_ARM64_CONT_PTE_SHIFT + PAGE_SHIFT)
+#define ptg_cont_pmd_shift	(CONFIG_ARM64_CONT_PMD_SHIFT + PMD_SHIFT)
+#define ptg_pgtable_levels	CONFIG_PGTABLE_LEVELS
+
+#endif /* ASM_PGTABLE_GEOMETRY_H */
arch/arm64/include/asm/pgtable-hwdef.h +10 -6
index 1f60aa1bc750c..54a9153f56bc5 100644
@@ -41,39 +41,43 @@
 #define ARM64_HW_PGTABLE_LEVEL_SHIFT(n)	((PAGE_SHIFT - 3) * (4 - (n)) + 3)
 
 #define PTRS_PER_PTE		(1 << (PAGE_SHIFT - 3))
+#define MAX_PTRS_PER_PTE	(1 << (PAGE_SHIFT_MAX - 3))
 
 /*
  * PMD_SHIFT determines the size a level 2 page table entry can map.
  */
 #if CONFIG_PGTABLE_LEVELS > 2
-#define PMD_SHIFT		ARM64_HW_PGTABLE_LEVEL_SHIFT(2)
+#define PMD_SHIFT		ptg_pmd_shift
 #define PMD_SIZE		(_AC(1, UL) << PMD_SHIFT)
 #define PMD_MASK		(~(PMD_SIZE-1))
 #define PTRS_PER_PMD		(1 << (PAGE_SHIFT - 3))
+#define MAX_PTRS_PER_PMD	(1 << (PAGE_SHIFT_MAX - 3))
 #endif
 
 /*
  * PUD_SHIFT determines the size a level 1 page table entry can map.
  */
 #if CONFIG_PGTABLE_LEVELS > 3
-#define PUD_SHIFT		ARM64_HW_PGTABLE_LEVEL_SHIFT(1)
+#define PUD_SHIFT		ptg_pud_shift
 #define PUD_SIZE		(_AC(1, UL) << PUD_SHIFT)
 #define PUD_MASK		(~(PUD_SIZE-1))
 #define PTRS_PER_PUD		(1 << (PAGE_SHIFT - 3))
+#define MAX_PTRS_PER_PUD	(1 << (PAGE_SHIFT_MAX - 3))
 #endif
 
 #if CONFIG_PGTABLE_LEVELS > 4
-#define P4D_SHIFT		ARM64_HW_PGTABLE_LEVEL_SHIFT(0)
+#define P4D_SHIFT		ptg_p4d_shift
 #define P4D_SIZE		(_AC(1, UL) << P4D_SHIFT)
 #define P4D_MASK		(~(P4D_SIZE-1))
 #define PTRS_PER_P4D		(1 << (PAGE_SHIFT - 3))
+#define MAX_PTRS_PER_P4D	(1 << (PAGE_SHIFT_MAX - 3))
 #endif
 
 /*
  * PGDIR_SHIFT determines the size a top-level page table entry can map
  * (depending on the configuration, this level can be -1, 0, 1 or 2).
  */
-#define PGDIR_SHIFT		ARM64_HW_PGTABLE_LEVEL_SHIFT(4 - CONFIG_PGTABLE_LEVELS)
+#define PGDIR_SHIFT		ptg_pgdir_shift
 #define PGDIR_SIZE		(_AC(1, UL) << PGDIR_SHIFT)
 #define PGDIR_MASK		(~(PGDIR_SIZE-1))
 #define PTRS_PER_PGD		(1 << (VA_BITS - PGDIR_SHIFT))
@@ -81,12 +85,12 @@
 /*
  * Contiguous page definitions.
  */
-#define CONT_PTE_SHIFT		(CONFIG_ARM64_CONT_PTE_SHIFT + PAGE_SHIFT)
+#define CONT_PTE_SHIFT		ptg_cont_pte_shift
 #define CONT_PTES		(1 << (CONT_PTE_SHIFT - PAGE_SHIFT))
 #define CONT_PTE_SIZE		(CONT_PTES * PAGE_SIZE)
 #define CONT_PTE_MASK		(~(CONT_PTE_SIZE - 1))
 
-#define CONT_PMD_SHIFT		(CONFIG_ARM64_CONT_PMD_SHIFT + PMD_SHIFT)
+#define CONT_PMD_SHIFT		ptg_cont_pmd_shift
 #define CONT_PMDS		(1 << (CONT_PMD_SHIFT - PMD_SHIFT))
 #define CONT_PMD_SIZE		(CONT_PMDS * PMD_SIZE)
 #define CONT_PMD_MASK		(~(CONT_PMD_SIZE - 1))
Signature · 1 line
2.43.0
author reviewer
#109 lore raw

RFC PATCH 40/57 arm64: Refactor early pgtable size calculation macros

In reply to Ryan Roberts

The various early idmaps and init/swapper pgtables are constructed using static storage, the size of which is obviously calculated at compile-time based on the selected page size. But in the near future, boot-time page size builds will need to statically allocate enough storage for the worst case, depending on which page size is selected.

Therefore, refactor the macros that determine the storage requirement to take a page_shift parameter, then perform the calculation for each page size we are compiling with support for and take the max. For compile-time page size builds, the end result is exactly the same because there is only 1 page size we support. For boot-time page size builds we end up with the worst case required size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/kernel-pgtable.h | 148 +++++++++++++++++-------
 arch/arm64/include/asm/pgtable-hwdef.h  |   6 +-
 arch/arm64/kernel/pi/map_kernel.c       |   6 +-
 arch/arm64/kernel/pi/map_range.c        |   8 +-
 arch/arm64/kernel/vmlinux.lds.S         |   4 +-
 arch/arm64/mm/mmu.c                     |  13 +--
 6 files changed, 124 insertions(+), 61 deletions(-)
arch/arm64/include/asm/kernel-pgtable.h +105 -43
index 1722b9217d47d..facdf273d4cda 100644
@@ -12,28 +12,38 @@
 #include <asm/pgtable-hwdef.h>
 #include <asm/sparsemem.h>
 
+#define PGTABLE_LEVELS(page_shift, va_bits)				\
+	__ARM64_HW_PGTABLE_LEVELS(page_shift, va_bits)
+#define PGTABLE_LEVEL_SHIFT(page_shift, n)				\
+	__ARM64_HW_PGTABLE_LEVEL_SHIFT(page_shift, n)
+#define PGTABLE_LEVEL_SIZE(page_shift, n)				\
+	(UL(1) << PGTABLE_LEVEL_SHIFT(page_shift, n))
+
 /*
  * The physical and virtual addresses of the start of the kernel image are
  * equal modulo 2 MiB (per the arm64 booting.txt requirements). Hence we can
  * use section mapping with 4K (section size = 2M) but not with 16K (section
  * size = 32M) or 64K (section size = 512M).
  */
-#if defined(PMD_SIZE) && PMD_SIZE <= MIN_KIMG_ALIGN
-#define SWAPPER_BLOCK_SHIFT	PMD_SHIFT
-#define SWAPPER_SKIP_LEVEL	1
-#else
-#define SWAPPER_BLOCK_SHIFT	PAGE_SHIFT
-#define SWAPPER_SKIP_LEVEL	0
-#endif
-#define SWAPPER_BLOCK_SIZE	(UL(1) << SWAPPER_BLOCK_SHIFT)
-#define SWAPPER_TABLE_SHIFT	(SWAPPER_BLOCK_SHIFT + PAGE_SHIFT - 3)
-
-#define SWAPPER_PGTABLE_LEVELS		(CONFIG_PGTABLE_LEVELS - SWAPPER_SKIP_LEVEL)
-#define INIT_IDMAP_PGTABLE_LEVELS	(IDMAP_LEVELS - SWAPPER_SKIP_LEVEL)
-
-#define IDMAP_VA_BITS		48
-#define IDMAP_LEVELS		ARM64_HW_PGTABLE_LEVELS(IDMAP_VA_BITS)
-#define IDMAP_ROOT_LEVEL	(4 - IDMAP_LEVELS)
+#define SWAPPER_BLOCK_SHIFT(page_shift)					\
+	((PGTABLE_LEVEL_SIZE(page_shift, 2) <= MIN_KIMG_ALIGN) ?	\
+		PGTABLE_LEVEL_SHIFT(page_shift, 2) : (page_shift))
+
+#define SWAPPER_SKIP_LEVEL(page_shift)					\
+	((PGTABLE_LEVEL_SIZE(page_shift, 2) <= MIN_KIMG_ALIGN) ? 1 : 0)
+
+#define SWAPPER_BLOCK_SIZE(page_shift)					\
+	(UL(1) << SWAPPER_BLOCK_SHIFT(page_shift))
+
+#define SWAPPER_PGTABLE_LEVELS(page_shift)				\
+	(PGTABLE_LEVELS(page_shift, VA_BITS) - SWAPPER_SKIP_LEVEL(page_shift))
+
+#define INIT_IDMAP_PGTABLE_LEVELS(page_shift)				\
+	(IDMAP_LEVELS(page_shift) - SWAPPER_SKIP_LEVEL(page_shift))
+
+#define IDMAP_VA_BITS			48
+#define IDMAP_LEVELS(page_shift)	PGTABLE_LEVELS(page_shift, IDMAP_VA_BITS)
+#define IDMAP_ROOT_LEVEL(page_shift)	(4 - IDMAP_LEVELS(page_shift))
 
 #define KIMAGE_VADDR_END	(_AT(u64, _end) - _AT(u64, _text) + KIMAGE_VADDR)
 
@@ -43,47 +53,99 @@
  * with two adjacent PGDIR entries, which means that an additional page table
  * may be needed at each subordinate level.
  */
-#define EXTRA_PAGE	__is_defined(CONFIG_RELOCATABLE)
+#define EXTRA_PAGE			__is_defined(CONFIG_RELOCATABLE)
 
-#define SPAN_NR_ENTRIES(vstart, vend, shift) \
+#define SPAN_NR_ENTRIES(vstart, vend, shift)				\
 	((((vend) - 1) >> (shift)) - ((vstart) >> (shift)) + 1)
 
-#define EARLY_ENTRIES(vstart, vend, shift, add) \
+#define EARLY_ENTRIES(vstart, vend, shift, add)				\
 	(SPAN_NR_ENTRIES(vstart, vend, shift) + (add))
 
-#define EARLY_LEVEL(lvl, lvls, vstart, vend, add)	\
-	(lvls > lvl ? EARLY_ENTRIES(vstart, vend, SWAPPER_BLOCK_SHIFT + lvl * (PAGE_SHIFT - 3), add) : 0)
-
-#define EARLY_PAGES(lvls, vstart, vend, add) (1 	/* PGDIR page */				\
-	+ EARLY_LEVEL(3, (lvls), (vstart), (vend), add) /* each entry needs a next level page table */	\
-	+ EARLY_LEVEL(2, (lvls), (vstart), (vend), add)	/* each entry needs a next level page table */	\
-	+ EARLY_LEVEL(1, (lvls), (vstart), (vend), add))/* each entry needs a next level page table */
-#define INIT_DIR_SIZE (PAGE_SIZE * (EARLY_PAGES(SWAPPER_PGTABLE_LEVELS, KIMAGE_VADDR, KIMAGE_VADDR_END, EXTRA_PAGE) \
-				    + EARLY_SEGMENT_EXTRA_PAGES))
-
-#define INIT_IDMAP_DIR_PAGES	(EARLY_PAGES(INIT_IDMAP_PGTABLE_LEVELS, KIMAGE_VADDR, KIMAGE_VADDR_END, 1))
-#define INIT_IDMAP_DIR_SIZE	((INIT_IDMAP_DIR_PAGES + EARLY_IDMAP_EXTRA_PAGES) * PAGE_SIZE)
+#define EARLY_LEVEL(page_shift, lvl, lvls, vstart, vend, add)		\
+	(lvls > lvl ? EARLY_ENTRIES(vstart, vend,			\
+		SWAPPER_BLOCK_SHIFT(page_shift) + lvl * ((page_shift) - 3), \
+		add) : 0)
 
-#define INIT_IDMAP_FDT_PAGES	(EARLY_PAGES(INIT_IDMAP_PGTABLE_LEVELS, 0UL, UL(MAX_FDT_SIZE), 1) - 1)
-#define INIT_IDMAP_FDT_SIZE	((INIT_IDMAP_FDT_PAGES + EARLY_IDMAP_EXTRA_FDT_PAGES) * PAGE_SIZE)
+#define EARLY_PAGES(page_shift, lvls, vstart, vend, add) (1 /* PGDIR */	\
+	+ EARLY_LEVEL((page_shift), 3, (lvls), (vstart), (vend), add)	\
+	+ EARLY_LEVEL((page_shift), 2, (lvls), (vstart), (vend), add)	\
+	+ EARLY_LEVEL((page_shift), 1, (lvls), (vstart), (vend), add))
 
 /* The number of segments in the kernel image (text, rodata, inittext, initdata, data+bss) */
-#define KERNEL_SEGMENT_COUNT	5
+#define KERNEL_SEGMENT_COUNT		5
 
-#if SWAPPER_BLOCK_SIZE > SEGMENT_ALIGN
-#define EARLY_SEGMENT_EXTRA_PAGES (KERNEL_SEGMENT_COUNT + 1)
 /*
  * The initial ID map consists of the kernel image, mapped as two separate
  * segments, and may appear misaligned wrt the swapper block size. This means
  * we need 3 additional pages. The DT could straddle a swapper block boundary,
  * so it may need 2.
  */
-#define EARLY_IDMAP_EXTRA_PAGES		3
-#define EARLY_IDMAP_EXTRA_FDT_PAGES	2
-#else
-#define EARLY_SEGMENT_EXTRA_PAGES	0
-#define EARLY_IDMAP_EXTRA_PAGES		0
-#define EARLY_IDMAP_EXTRA_FDT_PAGES	0
-#endif
+#define EARLY_SEGMENT_EXTRA_PAGES(page_shift)				\
+	((SWAPPER_BLOCK_SIZE(page_shift) > SEGMENT_ALIGN) ?		\
+		(KERNEL_SEGMENT_COUNT + 1) : 0)
+
+#define EARLY_IDMAP_EXTRA_PAGES(page_shift)				\
+	((SWAPPER_BLOCK_SIZE(page_shift) > SEGMENT_ALIGN) ? 3 : 0)
+
+#define EARLY_IDMAP_EXTRA_FDT_PAGES(page_shift)				\
+	((SWAPPER_BLOCK_SIZE(page_shift) > SEGMENT_ALIGN) ? 2 : 0)
+
+#define INIT_DIR_PAGES(page_shift)					\
+	(EARLY_PAGES((page_shift), SWAPPER_PGTABLE_LEVELS(page_shift),	\
+		KIMAGE_VADDR, KIMAGE_VADDR_END, EXTRA_PAGE))
+
+#define INIT_DIR_SIZE(page_shift)					\
+	((INIT_DIR_PAGES(page_shift) +					\
+	EARLY_SEGMENT_EXTRA_PAGES(page_shift)) * (UL(1) << (page_shift)))
+
+#define INIT_IDMAP_DIR_PAGES(page_shift)				\
+	(EARLY_PAGES((page_shift),					\
+		INIT_IDMAP_PGTABLE_LEVELS(page_shift),			\
+		KIMAGE_VADDR, KIMAGE_VADDR_END, 1))
+
+#define INIT_IDMAP_DIR_SIZE(page_shift)					\
+	((INIT_IDMAP_DIR_PAGES(page_shift) +				\
+	EARLY_IDMAP_EXTRA_PAGES(page_shift)) * (UL(1) << (page_shift)))
+
+#define INIT_IDMAP_FDT_PAGES(page_shift)				\
+	(EARLY_PAGES((page_shift),					\
+		INIT_IDMAP_PGTABLE_LEVELS(page_shift),			\
+		UL(0), UL(MAX_FDT_SIZE), 1) - 1)
+
+#define INIT_IDMAP_FDT_SIZE(page_shift)					\
+	((INIT_IDMAP_FDT_PAGES(page_shift) +				\
+	EARLY_IDMAP_EXTRA_FDT_PAGES(page_shift)) * (UL(1) << (page_shift)))
+
+#define VAL_IF_HAVE_PGSZ(val, page_shift)				\
+	((page_shift) >= PAGE_SHIFT_MIN &&				\
+	 (page_shift) <= PAGE_SHIFT_MAX ? (val) : 0)
+
+#define MAX_IF_HAVE_PGSZ(val4k, val16k, val64k)				\
+	MAX(VAL_IF_HAVE_PGSZ((val4k), ARM64_PAGE_SHIFT_4K), MAX(	\
+	    VAL_IF_HAVE_PGSZ((val16k), ARM64_PAGE_SHIFT_16K),		\
+	    VAL_IF_HAVE_PGSZ((val64k), ARM64_PAGE_SHIFT_64K)))
+
+#define IDMAP_LEVELS_MAX						\
+	MAX_IF_HAVE_PGSZ(IDMAP_LEVELS(ARM64_PAGE_SHIFT_4K),		\
+			 IDMAP_LEVELS(ARM64_PAGE_SHIFT_16K),		\
+			 IDMAP_LEVELS(ARM64_PAGE_SHIFT_64K))
+
+#define __INIT_DIR_SIZE_MAX						\
+	MAX_IF_HAVE_PGSZ(INIT_DIR_SIZE(ARM64_PAGE_SHIFT_4K),		\
+			 INIT_DIR_SIZE(ARM64_PAGE_SHIFT_16K),		\
+			 INIT_DIR_SIZE(ARM64_PAGE_SHIFT_64K))
+
+#define INIT_DIR_SIZE_MAX						\
+	MAX(__INIT_DIR_SIZE_MAX, INIT_IDMAP_DIR_SIZE_MAX)
+
+#define INIT_IDMAP_DIR_SIZE_MAX						\
+	MAX_IF_HAVE_PGSZ(INIT_IDMAP_DIR_SIZE(ARM64_PAGE_SHIFT_4K),	\
+			 INIT_IDMAP_DIR_SIZE(ARM64_PAGE_SHIFT_16K),	\
+			 INIT_IDMAP_DIR_SIZE(ARM64_PAGE_SHIFT_64K))
+
+#define INIT_IDMAP_FDT_SIZE_MAX						\
+	MAX_IF_HAVE_PGSZ(INIT_IDMAP_FDT_SIZE(ARM64_PAGE_SHIFT_4K),	\
+			 INIT_IDMAP_FDT_SIZE(ARM64_PAGE_SHIFT_16K),	\
+			 INIT_IDMAP_FDT_SIZE(ARM64_PAGE_SHIFT_64K))
 
 #endif	/* __ASM_KERNEL_PGTABLE_H */
arch/arm64/include/asm/pgtable-hwdef.h +4 -2
index 54a9153f56bc5..ca8bcbc1fe220 100644
@@ -23,7 +23,8 @@
  *
  * which gets simplified as :
  */
-#define ARM64_HW_PGTABLE_LEVELS(va_bits) (((va_bits) - 4) / (PAGE_SHIFT - 3))
+#define __ARM64_HW_PGTABLE_LEVELS(page_shift, va_bits)	(((va_bits) - 4) / ((page_shift) - 3))
+#define ARM64_HW_PGTABLE_LEVELS(va_bits)		__ARM64_HW_PGTABLE_LEVELS(PAGE_SHIFT, va_bits)
 
 /*
  * Size mapped by an entry at level n ( -1 <= n <= 3)
@@ -38,7 +39,8 @@
  * Rearranging it a bit we get :
  *   (4 - n) * (PAGE_SHIFT - 3) + 3
  */
-#define ARM64_HW_PGTABLE_LEVEL_SHIFT(n)	((PAGE_SHIFT - 3) * (4 - (n)) + 3)
+#define __ARM64_HW_PGTABLE_LEVEL_SHIFT(page_shift, n)	(((page_shift) - 3) * (4 - (n)) + 3)
+#define ARM64_HW_PGTABLE_LEVEL_SHIFT(n)			__ARM64_HW_PGTABLE_LEVEL_SHIFT(PAGE_SHIFT, n)
 
 #define PTRS_PER_PTE		(1 << (PAGE_SHIFT - 3))
 #define MAX_PTRS_PER_PTE	(1 << (PAGE_SHIFT_MAX - 3))
arch/arm64/kernel/pi/map_kernel.c +3 -3
index dcf9233ccfff2..a53fc225d2d0d 100644
@@ -188,8 +188,8 @@ static void __init remap_idmap_for_lpa2(void)
 
 static void __init map_fdt(u64 fdt)
 {
-	static u8 ptes[INIT_IDMAP_FDT_SIZE] __initdata __aligned(PAGE_SIZE);
-	u64 limit = (u64)&ptes[INIT_IDMAP_FDT_SIZE];
+	static u8 ptes[INIT_IDMAP_FDT_SIZE_MAX] __initdata __aligned(PAGE_SIZE);
+	u64 limit = (u64)&ptes[INIT_IDMAP_FDT_SIZE_MAX];
 	u64 efdt = fdt + MAX_FDT_SIZE;
 	u64 ptep = (u64)ptes;
 
@@ -199,7 +199,7 @@ static void __init map_fdt(u64 fdt)
 	 */
 	map_range(&ptep, limit, fdt,
 		  (u64)_text > fdt ? min((u64)_text, efdt) : efdt,
-		  fdt, PAGE_KERNEL, IDMAP_ROOT_LEVEL,
+		  fdt, PAGE_KERNEL, IDMAP_ROOT_LEVEL(PAGE_SHIFT),
 		  (pte_t *)init_idmap_pg_dir, false, 0);
 	dsb(ishst);
 }
arch/arm64/kernel/pi/map_range.c +4 -4
index f0024d9b1d921..b62d2e3135f81 100644
@@ -131,11 +131,11 @@ asmlinkage u64 __init create_init_idmap(pgd_t *pg_dir, pgd_t *pg_end,
 	pgprot_val(data_prot) &= ~clrmask;
 
 	map_range(&ptep, (u64)pg_end, (u64)_stext, (u64)__initdata_begin,
-		  (u64)_stext, text_prot, IDMAP_ROOT_LEVEL, (pte_t *)pg_dir,
-		  false, 0);
+		  (u64)_stext, text_prot,
+		  IDMAP_ROOT_LEVEL(PAGE_SHIFT), (pte_t *)pg_dir, false, 0);
 	map_range(&ptep, (u64)pg_end, (u64)__initdata_begin, (u64)_end,
-		  (u64)__initdata_begin, data_prot, IDMAP_ROOT_LEVEL,
-		  (pte_t *)pg_dir, false, 0);
+		  (u64)__initdata_begin, data_prot,
+		  IDMAP_ROOT_LEVEL(PAGE_SHIFT), (pte_t *)pg_dir, false, 0);
 
 	return ptep;
 }
arch/arm64/kernel/vmlinux.lds.S +2 -2
index 55a8e310ea12c..7f3f6d709ae73 100644
@@ -249,7 +249,7 @@ SECTIONS
 	__initdata_begin = .;
 
 	init_idmap_pg_dir = .;
-	. += INIT_IDMAP_DIR_SIZE;
+	. += INIT_IDMAP_DIR_SIZE_MAX;
 	init_idmap_pg_end = .;
 
 	.init.data : {
@@ -319,7 +319,7 @@ SECTIONS
 
 	. = ALIGN(PAGE_SIZE);
 	init_pg_dir = .;
-	. += INIT_DIR_SIZE;
+	. += INIT_DIR_SIZE_MAX;
 	init_pg_end = .;
 	/* end of zero-init region */
 
arch/arm64/mm/mmu.c +6 -7
index 969348a2e93c9..d4d30eaefb4cd 100644
@@ -777,19 +777,19 @@ void __pi_map_range(u64 *pgd, u64 limit, u64 start, u64 end, u64 pa,
 		    pgprot_t prot, int level, pte_t *tbl, bool may_use_cont,
 		    u64 va_offset);
 
-static u8 idmap_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
-	  kpti_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
+static u8 idmap_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
+	  kpti_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
 
 static void __init create_idmap(void)
 {
 	u64 start = __pa_symbol(__idmap_text_start);
 	u64 end   = __pa_symbol(__idmap_text_end);
 	u64 ptep  = __pa_symbol(idmap_ptes);
-	u64 limit  = __pa_symbol(&idmap_ptes[IDMAP_LEVELS - 1][0]);
+	u64 limit  = __pa_symbol(&idmap_ptes[IDMAP_LEVELS_MAX - 1][0]);
 
 	__pi_map_range(&ptep, limit, start, end, start, PAGE_KERNEL_ROX,
-		       IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
-		       __phys_to_virt(ptep) - ptep);
+		       IDMAP_ROOT_LEVEL(PAGE_SHIFT), (pte_t *)idmap_pg_dir,
+		       false, __phys_to_virt(ptep) - ptep);
 
 	if (IS_ENABLED(CONFIG_UNMAP_KERNEL_AT_EL0) && !arm64_use_ng_mappings) {
 		extern u32 __idmap_kpti_flag;
@@ -800,9 +800,8 @@ static void __init create_idmap(void)
 		 * of its synchronization flag in the ID map.
 		 */
 		ptep = __pa_symbol(kpti_ptes);
-		limit  = __pa_symbol(&kpti_ptes[IDMAP_LEVELS - 1][0]);
 		__pi_map_range(&ptep, limit, pa, pa + sizeof(u32), pa,
-			       PAGE_KERNEL, IDMAP_ROOT_LEVEL,
+			       PAGE_KERNEL, IDMAP_ROOT_LEVEL(PAGE_SHIFT),
 			       (pte_t *)idmap_pg_dir, false,
 			       __phys_to_virt(ptep) - ptep);
 	}
Signature · 1 line
2.43.0
author reviewer
#110 lore raw

RFC PATCH 41/57 arm64: Pass desired page size on command line

In reply to Ryan Roberts

Allow user to pass desired page size via command line as either "arm64.pagesize=4k", "arm64.pagesize=16k", or "arm64.pagesize=64k". The specified value is stored in the SW_FEATURE register as an encoded page shift in a 4 bit field.

We only allow setting the page size override if the requested size is supported by the HW and is within the compile-time [PAGE_SIZE_MIN, PAGE_SIZE_MAX] range. This second condition means that overrides get ignored when we have a compile-time page size (because PAGE_SIZE_MIN == PAGE_SIZE_MAX).

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/cpufeature.h   | 11 ++++++++
 arch/arm64/kernel/pi/idreg-override.c | 36 +++++++++++++++++++++++++++
 2 files changed, 47 insertions(+)
arch/arm64/include/asm/cpufeature.h +11 -0
index 5584342672715..4edbb586810d7 100644
@@ -18,6 +18,7 @@
 #define ARM64_SW_FEATURE_OVERRIDE_NOKASLR	0
 #define ARM64_SW_FEATURE_OVERRIDE_HVHE		4
 #define ARM64_SW_FEATURE_OVERRIDE_RODATA_OFF	8
+#define ARM64_SW_FEATURE_OVERRIDE_PAGESHIFT	12
 
 #ifndef __ASSEMBLY__
 
@@ -963,6 +964,16 @@ static inline bool arm64_test_sw_feature_override(int feat)
 					    &arm64_sw_feature_override);
 }
 
+static inline int arm64_pageshift_cmdline(void)
+{
+	int val;
+
+	val = arm64_apply_feature_override(0,
+					   ARM64_SW_FEATURE_OVERRIDE_PAGESHIFT,
+					   4, &arm64_sw_feature_override);
+	return val ? val * 2 + 10 : 0;
+}
+
 static inline bool kaslr_disabled_cmdline(void)
 {
 	return arm64_test_sw_feature_override(ARM64_SW_FEATURE_OVERRIDE_NOKASLR);
arch/arm64/kernel/pi/idreg-override.c +36 -0
index 29d4b6244a6f6..5a38bdb231bc8 100644
@@ -183,6 +183,38 @@ static bool __init hvhe_filter(u64 val)
 						     ID_AA64MMFR1_EL1_VH_SHIFT));
 }
 
+static bool __init pageshift_filter(u64 val)
+{
+	u64 mmfr0 = read_sysreg_s(SYS_ID_AA64MMFR0_EL1);
+	u32 tgran64 = SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN64, mmfr0);
+	u32 tgran16 = SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN16, mmfr0);
+	u32 tgran4 = SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN4, mmfr0);
+
+	/* pageshift is stored compressed in 4 bit field. */
+	if (val)
+		val = val * 2 + 10;
+
+	if (val < PAGE_SHIFT_MIN || val > PAGE_SHIFT_MAX)
+		return false;
+
+	if (val == ARM64_PAGE_SHIFT_64K &&
+	    tgran64 >= ID_AA64MMFR0_EL1_TGRAN64_SUPPORTED_MIN &&
+	    tgran64 <= ID_AA64MMFR0_EL1_TGRAN64_SUPPORTED_MAX)
+		return true;
+
+	if (val == ARM64_PAGE_SHIFT_16K &&
+	    tgran16 >= ID_AA64MMFR0_EL1_TGRAN16_SUPPORTED_MIN &&
+	    tgran16 <= ID_AA64MMFR0_EL1_TGRAN16_SUPPORTED_MAX)
+		return true;
+
+	if (val == ARM64_PAGE_SHIFT_4K &&
+	    tgran4 >= ID_AA64MMFR0_EL1_TGRAN4_SUPPORTED_MIN &&
+	    tgran4 <= ID_AA64MMFR0_EL1_TGRAN4_SUPPORTED_MAX)
+		return true;
+
+	return false;
+}
+
 static const struct ftr_set_desc sw_features __prel64_initconst = {
 	.name		= "arm64_sw",
 	.override	= &arm64_sw_feature_override,
@@ -190,6 +222,7 @@ static const struct ftr_set_desc sw_features __prel64_initconst = {
 		FIELD("nokaslr", ARM64_SW_FEATURE_OVERRIDE_NOKASLR, NULL),
 		FIELD("hvhe", ARM64_SW_FEATURE_OVERRIDE_HVHE, hvhe_filter),
 		FIELD("rodataoff", ARM64_SW_FEATURE_OVERRIDE_RODATA_OFF, NULL),
+		FIELD("pageshift", ARM64_SW_FEATURE_OVERRIDE_PAGESHIFT, pageshift_filter),
 		{}
 	},
 };
@@ -225,6 +258,9 @@ static const struct {
 	{ "rodata=off",			"arm64_sw.rodataoff=1" },
 	{ "arm64.nolva",		"id_aa64mmfr2.varange=0" },
 	{ "arm64.no32bit_el0",		"id_aa64pfr0.el0=1" },
+	{ "arm64.pagesize=4k",		"arm64_sw.pageshift=1" },
+	{ "arm64.pagesize=16k",		"arm64_sw.pageshift=2" },
+	{ "arm64.pagesize=64k",		"arm64_sw.pageshift=3" },
 };
 
 static int __init parse_hexdigit(const char *p, u64 *v)
Signature · 1 line
2.43.0
author reviewer
#111 lore raw

RFC PATCH 42/57 arm64: Divorce early init from PAGE_SIZE

In reply to Ryan Roberts

Refactor all the early code between entrypoint and start_kernel() so that it does not rely on compile-time configuration of page size. For now, that code chooses to use the compile-time page size as its boot-time selected page size, but this will change in the near future to allow the page size to be specified on the command line.

An initial page size is selected by probe_init_idmap_page_shift(), which is used for the init_idmap_pg_dir. This selects the largest page size that the HW supports and which is also in the range of page sizes allowed by the compile-time config. For now, the allowed range only covers the compile-time selected page size, but in future boot-time page size builds, the range will be expanded.

Once the mmu is enabled, we access the command line in the device tree as before, which allows us to determine the page size requested by the user, filtered by the same allowed compile-time range of page sizes - still just the compile-time selected page size for now. If no acceptable page size was specified on the command line, we fall back to the page size selected in probe_init_idmap_page_shift(). We then do a dance to repaint init_idmap_pg_dir for the final page size and for LPA2, if in use. Finally with that installed, we can continue booting the kernel.

For all of this to work, we must replace previous compile-time decisions with run-time decisions. For the most part, we can do this by looking at tcr_el1.tg0 to determine the installed page size. These run-time decisions are not in hot code paths so I don't anticipate any performance regressions as a result and therefore I prefer the simplicity of using the run-time approach even for builds that specify a compile-time page size.

Of course to be able to actually change the early page size, the static storage for the page tables need to be sized for the maximum requirement. Currently they are still sized for the compile-time page size.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/assembler.h    |  50 +++++++-
 arch/arm64/include/asm/cpufeature.h   |  33 +++--
 arch/arm64/include/asm/pgtable-prot.h |   2 +-
 arch/arm64/kernel/head.S              |  40 ++++--
 arch/arm64/kernel/pi/idreg-override.c |  32 +++--
 arch/arm64/kernel/pi/map_kernel.c     |  87 +++++++++----
 arch/arm64/kernel/pi/map_range.c      | 171 ++++++++++++++++++++++----
 arch/arm64/kernel/pi/pi.h             |  61 ++++++++-
 arch/arm64/mm/proc.S                  |  21 ++--
 9 files changed, 405 insertions(+), 92 deletions(-)
arch/arm64/include/asm/assembler.h +49 -1
index bc0b0d75acef7..77c2d707adb1a 100644
@@ -568,6 +568,14 @@ alternative_endif
 	mrs	\rd, sp_el0
 	.endm
 
+/*
+ * Retrieve and return tcr_el1.tg0 in \tg0.
+ */
+	.macro	get_tg0, tg0
+	mrs	\tg0, tcr_el1
+	and	\tg0, \tg0, #TCR_TG0_MASK
+	.endm
+
 /*
  * If the kernel is built for 52-bit virtual addressing but the hardware only
  * supports 48 bits, we cannot program the pgdir address into TTBR1 directly,
@@ -584,12 +592,16 @@ alternative_endif
  * 	ttbr: Value of ttbr to set, modified.
  */
 	.macro	offset_ttbr1, ttbr, tmp
-#if defined(CONFIG_ARM64_VA_BITS_52) && !defined(CONFIG_ARM64_LPA2)
+#if defined(CONFIG_ARM64_VA_BITS_52)
+	get_tg0	\tmp
+	cmp	\tmp, #TCR_TG0_64K
+	b.ne	.Ldone\@
 	mrs	\tmp, tcr_el1
 	and	\tmp, \tmp, #TCR_T1SZ_MASK
 	cmp	\tmp, #TCR_T1SZ(VA_BITS_MIN)
 	orr	\tmp, \ttbr, #TTBR1_BADDR_4852_OFFSET
 	csel	\ttbr, \tmp, \ttbr, eq
+.Ldone\@:
 #endif
 	.endm
 
@@ -863,4 +875,40 @@ alternative_cb ARM64_ALWAYS_SYSTEM, spectre_bhb_patch_clearbhb
 alternative_cb_end
 #endif /* CONFIG_MITIGATE_SPECTRE_BRANCH_HISTORY */
 	.endm
+
+/*
+ * Given \tg0, populates \val with one of the 3 passed in values, corresponding
+ * to the page size advertised by \tg0.
+ */
+	.macro	value_for_page_size, val, tg0, val4k, val16k, val64k
+.Lsz_64k\@:
+	cmp	\tg0, #TCR_TG0_64K
+	b.ne	.Lsz_16k\@
+	mov	\val, #\val64k
+	b	.Ldone\@
+.Lsz_16k\@:
+	cmp	\tg0, #TCR_TG0_16K
+	b.ne	.Lsz_4k\@
+	mov	\val, #\val16k
+	b	.Ldone\@
+.Lsz_4k\@:
+	mov	\val, #\val4k
+.Ldone\@:
+	.endm
+
+	.macro	tgran_shift, val, tg0
+	value_for_page_size \val, \tg0, ID_AA64MMFR0_EL1_TGRAN4_SHIFT, ID_AA64MMFR0_EL1_TGRAN16_SHIFT, ID_AA64MMFR0_EL1_TGRAN64_SHIFT
+	.endm
+
+	.macro	tgran_min, val, tg0
+	value_for_page_size \val, \tg0, ID_AA64MMFR0_EL1_TGRAN4_SUPPORTED_MIN, ID_AA64MMFR0_EL1_TGRAN16_SUPPORTED_MIN, ID_AA64MMFR0_EL1_TGRAN64_SUPPORTED_MIN
+	.endm
+
+	.macro	tgran_max, val, tg0
+	value_for_page_size \val, \tg0, ID_AA64MMFR0_EL1_TGRAN4_SUPPORTED_MAX, ID_AA64MMFR0_EL1_TGRAN16_SUPPORTED_MAX, ID_AA64MMFR0_EL1_TGRAN64_SUPPORTED_MAX
+	.endm
+
+	.macro	tgran_lpa2, val, tg0
+	value_for_page_size \val, \tg0, ID_AA64MMFR0_EL1_TGRAN4_52_BIT, ID_AA64MMFR0_EL1_TGRAN16_52_BIT, -1
+	.endm
 #endif	/* __ASM_ASSEMBLER_H */
arch/arm64/include/asm/cpufeature.h +23 -10
index 4edbb586810d7..2c22cfdc04bc7 100644
@@ -26,6 +26,7 @@
 #include <linux/jump_label.h>
 #include <linux/kernel.h>
 #include <linux/cpumask.h>
+#include <linux/sizes.h>
 
 /*
  * CPU feature register tracking
@@ -1014,10 +1015,13 @@ static inline bool cpu_has_pac(void)
 					    &id_aa64isar2_override);
 }
 
-static inline bool cpu_has_lva(void)
+static inline bool cpu_has_lva(u64 page_size)
 {
 	u64 mmfr2;
 
+	if (page_size != SZ_64K)
+		return false;
+
 	mmfr2 = read_sysreg_s(SYS_ID_AA64MMFR2_EL1);
 	mmfr2 &= ~id_aa64mmfr2_override.mask;
 	mmfr2 |= id_aa64mmfr2_override.val;
@@ -1025,22 +1029,31 @@ static inline bool cpu_has_lva(void)
 						    ID_AA64MMFR2_EL1_VARange_SHIFT);
 }
 
-static inline bool cpu_has_lpa2(void)
+static inline bool cpu_has_lpa2(u64 page_size)
 {
-#ifdef CONFIG_ARM64_LPA2
 	u64 mmfr0;
 	int feat;
+	int shift;
+	int minval;
+
+	switch (page_size) {
+	case SZ_4K:
+		shift = ID_AA64MMFR0_EL1_TGRAN4_SHIFT;
+		minval = ID_AA64MMFR0_EL1_TGRAN4_52_BIT;
+		break;
+	case SZ_16K:
+		shift = ID_AA64MMFR0_EL1_TGRAN16_SHIFT;
+		minval = ID_AA64MMFR0_EL1_TGRAN16_52_BIT;
+		break;
+	default:
+		return false;
+	}
 
 	mmfr0 = read_sysreg(id_aa64mmfr0_el1);
 	mmfr0 &= ~id_aa64mmfr0_override.mask;
 	mmfr0 |= id_aa64mmfr0_override.val;
-	feat = cpuid_feature_extract_signed_field(mmfr0,
-						  ID_AA64MMFR0_EL1_TGRAN_SHIFT);
-
-	return feat >= ID_AA64MMFR0_EL1_TGRAN_LPA2;
-#else
-	return false;
-#endif
+	feat = cpuid_feature_extract_signed_field(mmfr0, shift);
+	return feat >= minval;
 }
 
 #endif /* __ASSEMBLY__ */
arch/arm64/include/asm/pgtable-prot.h +1 -1
index b11cfb9fdd379..f8ebf424ca016 100644
@@ -74,7 +74,7 @@ extern bool arm64_use_ng_mappings;
 #define PTE_MAYBE_NG		(arm64_use_ng_mappings ? PTE_NG : 0)
 #define PMD_MAYBE_NG		(arm64_use_ng_mappings ? PMD_SECT_NG : 0)
 
-#ifndef CONFIG_ARM64_LPA2
+#ifndef CONFIG_ARM64_VA_BITS_52
 #define lpa2_is_enabled()	false
 #define PTE_MAYBE_SHARED	PTE_SHARED
 #define PMD_MAYBE_SHARED	PMD_SECT_S
arch/arm64/kernel/head.S +31 -9
index 7e17a71fd9e4b..761b7f5633e15 100644
@@ -88,6 +88,8 @@ SYM_CODE_START(primary_entry)
 	adrp	x1, early_init_stack
 	mov	sp, x1
 	mov	x29, xzr
+	bl	__pi_probe_init_idmap_page_shift
+	mov	x3, x0
 	adrp	x0, init_idmap_pg_dir
 	adrp	x1, init_idmap_pg_end
 	mov	x2, xzr
@@ -471,11 +473,16 @@ SYM_FUNC_END(set_cpu_boot_mode_flag)
  */
 	.section ".idmap.text","a"
 SYM_FUNC_START(__enable_mmu)
+	get_tg0 x3
+	tgran_shift x4, x3
+	tgran_min x5, x3
+	tgran_max x6, x3
 	mrs	x3, ID_AA64MMFR0_EL1
-	ubfx	x3, x3, #ID_AA64MMFR0_EL1_TGRAN_SHIFT, 4
-	cmp     x3, #ID_AA64MMFR0_EL1_TGRAN_SUPPORTED_MIN
+	lsr	x3, x3, x4
+	ubfx	x3, x3, #0, 4
+	cmp     x3, x5
 	b.lt    __no_granule_support
-	cmp     x3, #ID_AA64MMFR0_EL1_TGRAN_SUPPORTED_MAX
+	cmp     x3, x6
 	b.gt    __no_granule_support
 	phys_to_ttbr x2, x2
 	msr	ttbr0_el1, x2			// load TTBR0
@@ -488,17 +495,32 @@ SYM_FUNC_END(__enable_mmu)
 
 #ifdef CONFIG_ARM64_VA_BITS_52
 SYM_FUNC_START(__cpu_secondary_check52bitva)
-#ifndef CONFIG_ARM64_LPA2
+	/*
+	 * tcr_el1 is not yet loaded (there is a chicken-and-egg problem) so we
+	 * can't figure out LPA2 vs LVA from that. But this is only called for
+	 * secondary cpus so tcr_boot_fields has already been populated by the
+	 * primary cpu. So grab that and rely on the DS bit to tell us if we are
+	 * LPA2 or LVA.
+	 */
+	adr_l	x1, __pi_tcr_boot_fields
+	ldr	x0, [x1]
+	and	x1, x0, #TCR_DS
+	cbnz	x1, .Llpa2
+.Llva:
 	mrs_s	x0, SYS_ID_AA64MMFR2_EL1
 	and	x0, x0, ID_AA64MMFR2_EL1_VARange_MASK
 	cbnz	x0, 2f
-#else
+	b	.Lfail
+.Llpa2:
+	and	x0, x0, #TCR_TG0_MASK
+	tgran_shift x1, x0
+	tgran_lpa2 x2, x0
 	mrs	x0, id_aa64mmfr0_el1
-	sbfx	x0, x0, #ID_AA64MMFR0_EL1_TGRAN_SHIFT, 4
-	cmp	x0, #ID_AA64MMFR0_EL1_TGRAN_LPA2
+	lsr	x0, x0, x1
+	sbfx	x0, x0, #0, 4
+	cmp	x0, x2
 	b.ge	2f
-#endif
-
+.Lfail:
 	update_early_cpu_boot_status \
 		CPU_STUCK_IN_KERNEL | CPU_STUCK_REASON_52_BIT_VA, x0, x1
 1:	wfe
arch/arm64/kernel/pi/idreg-override.c +23 -9
index 5a38bdb231bc8..0685c0a3255e2 100644
@@ -62,20 +62,34 @@ static const struct ftr_set_desc mmfr1 __prel64_initconst = {
 
 static bool __init mmfr2_varange_filter(u64 val)
 {
-	int __maybe_unused feat;
+	u64 mmfr0;
+	int feat;
+	int shift;
+	int minval;
 
 	if (val)
 		return false;
 
-#ifdef CONFIG_ARM64_LPA2
-	feat = cpuid_feature_extract_signed_field(read_sysreg(id_aa64mmfr0_el1),
-						  ID_AA64MMFR0_EL1_TGRAN_SHIFT);
-	if (feat >= ID_AA64MMFR0_EL1_TGRAN_LPA2) {
-		id_aa64mmfr0_override.val |=
-			(ID_AA64MMFR0_EL1_TGRAN_LPA2 - 1) << ID_AA64MMFR0_EL1_TGRAN_SHIFT;
-		id_aa64mmfr0_override.mask |= 0xfU << ID_AA64MMFR0_EL1_TGRAN_SHIFT;
+	mmfr0 = read_sysreg(id_aa64mmfr0_el1);
+
+	/* Remove LPA2 support for 4K granule. */
+	shift = ID_AA64MMFR0_EL1_TGRAN4_SHIFT;
+	minval = ID_AA64MMFR0_EL1_TGRAN4_52_BIT;
+	feat = cpuid_feature_extract_signed_field(mmfr0, shift);
+	if (feat >= minval) {
+		id_aa64mmfr0_override.val |= (minval - 1) << shift;
+		id_aa64mmfr0_override.mask |= 0xfU << shift;
+	}
+
+	/* Remove LPA2 support for 16K granule. */
+	shift = ID_AA64MMFR0_EL1_TGRAN16_SHIFT;
+	minval = ID_AA64MMFR0_EL1_TGRAN16_52_BIT;
+	feat = cpuid_feature_extract_signed_field(mmfr0, shift);
+	if (feat >= minval) {
+		id_aa64mmfr0_override.val |= (minval - 1) << shift;
+		id_aa64mmfr0_override.mask |= 0xfU << shift;
 	}
-#endif
+
 	return true;
 }
 
arch/arm64/kernel/pi/map_kernel.c +63 -24

168 lines not on this page · raw message

arch/arm64/kernel/pi/map_range.c +146 -25

237 lines not on this page · raw message

arch/arm64/kernel/pi/pi.h +60 -1

70 lines not on this page · raw message

arch/arm64/mm/proc.S +9 -12
index f4bc6c5bac062..ab5aa84923524 100644
@@ -22,14 +22,6 @@
 #include <asm/smp.h>
 #include <asm/sysreg.h>
 
-#ifdef CONFIG_ARM64_64K_PAGES
-#define TCR_TG_FLAGS	TCR_TG0_64K | TCR_TG1_64K
-#elif defined(CONFIG_ARM64_16K_PAGES)
-#define TCR_TG_FLAGS	TCR_TG0_16K | TCR_TG1_16K
-#else /* CONFIG_ARM64_4K_PAGES */
-#define TCR_TG_FLAGS	TCR_TG0_4K | TCR_TG1_4K
-#endif
-
 #ifdef CONFIG_RANDOMIZE_BASE
 #define TCR_KASLR_FLAGS	TCR_NFD1
 #else
@@ -469,18 +461,23 @@ SYM_FUNC_START(__cpu_setup)
 	tcr	.req	x16
 	mov_q	mair, MAIR_EL1_SET
 	mov_q	tcr, TCR_T0SZ(IDMAP_VA_BITS) | TCR_T1SZ(VA_BITS_MIN) | TCR_CACHE_FLAGS | \
-		     TCR_SMP_FLAGS | TCR_TG_FLAGS | TCR_KASLR_FLAGS | TCR_ASID16 | \
+		     TCR_SMP_FLAGS | TCR_KASLR_FLAGS | TCR_ASID16 | \
 		     TCR_TBI0 | TCR_A1 | TCR_KASAN_SW_FLAGS | TCR_MTE_FLAGS
 
+	/*
+	 * Insert the boot-time determined fields (TG0, TG1 and DS), which are
+	 * cached in the tcr_boot_fields variable.
+	 */
+	adr_l	x2, __pi_tcr_boot_fields
+	ldr	x3, [x2]
+	orr	tcr, tcr, x3
+
 	tcr_clear_errata_bits tcr, x9, x5
 
 #ifdef CONFIG_ARM64_VA_BITS_52
 	mov		x9, #64 - VA_BITS
 alternative_if ARM64_HAS_VA52
 	tcr_set_t1sz	tcr, x9
-#ifdef CONFIG_ARM64_LPA2
-	orr		tcr, tcr, #TCR_DS
-#endif
 alternative_else_nop_endif
 #endif
 
Signature · 1 line
2.43.0
author reviewer
#112 lore raw

RFC PATCH 43/57 arm64: Clean up simple cases of CONFIG_ARM64_*K_PAGES

In reply to Ryan Roberts

There are a number of places that define macros conditionally depending on which of the CONFIG_ARM64_*K_PAGES macros are defined. But in preparation for supporting boot-time page size selection, we will no longer be able to make these decisions at compile time.

So let's refactor the code to check the size of PAGE_SIZE using the ternary operator. This approach will still resolve to compile-time constants when configured for a compile-time page size, but it will also work when we turn PAGE_SIZE into a run-time value. Additionally, IS_ENABLED(CONFIG_ARM64_*K_PAGES) instances are also converted to test the size of PAGE_SIZE.

Additionally modify ARM64_HAS_VA52 capability detection to use a custom match function, which chooses which feature register and field to check based on PAGE_SIZE. The compiler will eliminate the other page sizes when selecting a compile time page size, but will also now cope with seting page size at boot time.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/kvm_arm.h     | 21 ++++-------
 arch/arm64/include/asm/kvm_pgtable.h |  6 +---
 arch/arm64/include/asm/memory.h      |  7 ++--
 arch/arm64/include/asm/processor.h   | 10 +++---
 arch/arm64/include/asm/sparsemem.h   | 11 ++----
 arch/arm64/include/asm/sysreg.h      | 54 ++++++++++++++++++----------
 arch/arm64/kernel/cpufeature.c       | 43 +++++++++++++---------
 arch/arm64/mm/fixmap.c               |  2 +-
 arch/arm64/mm/init.c                 | 20 +++++------
 arch/arm64/mm/kasan_init.c           |  8 ++---
 arch/arm64/mm/mmu.c                  |  2 +-
 drivers/irqchip/irq-gic-v3-its.c     |  2 +-
 12 files changed, 94 insertions(+), 92 deletions(-)
arch/arm64/include/asm/kvm_arm.h +6 -15
index d81cc746e0ebd..08155dc17ad17 100644
@@ -189,22 +189,13 @@
  * Entry_Level = 4 - Number_of_levels.
  *
  */
-#ifdef CONFIG_ARM64_64K_PAGES
+#define VTCR_EL2_TGRAN							\
+	(PAGE_SIZE == SZ_64K ?						\
+		VTCR_EL2_TG0_64K :					\
+		(PAGE_SIZE == SZ_16K ? VTCR_EL2_TG0_16K : VTCR_EL2_TG0_4K))
 
-#define VTCR_EL2_TGRAN			VTCR_EL2_TG0_64K
-#define VTCR_EL2_TGRAN_SL0_BASE		3UL
-
-#elif defined(CONFIG_ARM64_16K_PAGES)
-
-#define VTCR_EL2_TGRAN			VTCR_EL2_TG0_16K
-#define VTCR_EL2_TGRAN_SL0_BASE		3UL
-
-#else	/* 4K */
-
-#define VTCR_EL2_TGRAN			VTCR_EL2_TG0_4K
-#define VTCR_EL2_TGRAN_SL0_BASE		2UL
-
-#endif
+#define VTCR_EL2_TGRAN_SL0_BASE						\
+	(PAGE_SIZE == SZ_64K ? 3UL : (PAGE_SIZE == SZ_16K ? 3UL : 2UL))
 
 #define VTCR_EL2_LVLS_TO_SL0(levels)	\
 	((VTCR_EL2_TGRAN_SL0_BASE - (4 - (levels))) << VTCR_EL2_SL0_SHIFT)
arch/arm64/include/asm/kvm_pgtable.h +1 -5
index 19278dfe79782..796614bf59e78 100644
@@ -20,11 +20,7 @@
  *  - 16K (level 2):	32MB
  *  - 64K (level 2):	512MB
  */
-#ifdef CONFIG_ARM64_4K_PAGES
-#define KVM_PGTABLE_MIN_BLOCK_LEVEL	1
-#else
-#define KVM_PGTABLE_MIN_BLOCK_LEVEL	2
-#endif
+#define KVM_PGTABLE_MIN_BLOCK_LEVEL	(PAGE_SIZE == SZ_4K ? 1 : 2)
 
 #define kvm_lpa2_is_enabled()		system_supports_lpa2()
 
arch/arm64/include/asm/memory.h +2 -5
index 54fb014eba058..6aa97fa22dc30 100644
@@ -188,11 +188,8 @@
 #define MT_S2_FWB_NORMAL_NC	5
 #define MT_S2_FWB_DEVICE_nGnRE	1
 
-#ifdef CONFIG_ARM64_4K_PAGES
-#define IOREMAP_MAX_ORDER	(PUD_SHIFT)
-#else
-#define IOREMAP_MAX_ORDER	(PMD_SHIFT)
-#endif
+#define IOREMAP_MAX_ORDER						\
+	(PAGE_SIZE == SZ_4K ? PUD_SHIFT : PMD_SHIFT)
 
 /*
  *  Open-coded (swapper_pg_dir - reserved_pg_dir) as this cannot be calculated
arch/arm64/include/asm/processor.h +5 -5
index f77371232d8c6..444694a4e6733 100644
@@ -55,15 +55,15 @@
 #define TASK_SIZE_MAX		(UL(1) << VA_BITS)
 
 #ifdef CONFIG_COMPAT
-#if defined(CONFIG_ARM64_64K_PAGES) && defined(CONFIG_KUSER_HELPERS)
+#if defined(CONFIG_KUSER_HELPERS)
 /*
- * With CONFIG_ARM64_64K_PAGES enabled, the last page is occupied
- * by the compat vectors page.
+ * With 64K pages in use, the last page is occupied by the compat vectors page.
  */
-#define TASK_SIZE_32		UL(0x100000000)
+#define TASK_SIZE_32							\
+	(PAGE_SIZE == SZ_64K ? UL(0x100000000) : (UL(0x100000000) - PAGE_SIZE))
 #else
 #define TASK_SIZE_32		(UL(0x100000000) - PAGE_SIZE)
-#endif /* CONFIG_ARM64_64K_PAGES */
+#endif /* CONFIG_KUSER_HELPERS */
 #define TASK_SIZE		(test_thread_flag(TIF_32BIT) ? \
 				TASK_SIZE_32 : TASK_SIZE_64)
 #define TASK_SIZE_OF(tsk)	(test_tsk_thread_flag(tsk, TIF_32BIT) ? \
arch/arm64/include/asm/sparsemem.h +2 -9
index 8a8acc220371c..a05fdd54014f7 100644
@@ -11,19 +11,12 @@
  * Section size must be at least 512MB for 64K base
  * page size config. Otherwise it will be less than
  * MAX_PAGE_ORDER and the build process will fail.
- */
-#ifdef CONFIG_ARM64_64K_PAGES
-#define SECTION_SIZE_BITS 29
-
-#else
-
-/*
+ *
  * Section size must be at least 128MB for 4K base
  * page size config. Otherwise PMD based huge page
  * entries could not be created for vmemmap mappings.
  * 16K follows 4K for simplicity.
  */
-#define SECTION_SIZE_BITS 27
-#endif /* CONFIG_ARM64_64K_PAGES */
+#define SECTION_SIZE_BITS	(PAGE_SIZE == SZ_64K ? 29 : 27)
 
 #endif
arch/arm64/include/asm/sysreg.h +36 -18

70 lines not on this page · raw message

arch/arm64/kernel/cpufeature.c +27 -16

74 lines not on this page · raw message

arch/arm64/mm/fixmap.c +1 -1
index de1e09d986ad2..15ce3253ad359 100644
@@ -82,7 +82,7 @@ static void __init early_fixmap_init_pud(p4d_t *p4dp, unsigned long addr,
 		 * share the top level pgd entry, which should only happen on
 		 * 16k/4 levels configurations.
 		 */
-		BUG_ON(!IS_ENABLED(CONFIG_ARM64_16K_PAGES));
+		BUG_ON(PAGE_SIZE != SZ_16K);
 	}
 
 	if (p4d_none(p4d))
arch/arm64/mm/init.c +8 -12
index 9b5ab6818f7f3..42eb246949072 100644
@@ -73,13 +73,10 @@ phys_addr_t __ro_after_init arm64_dma_phys_limit;
  * (64k granule), or a multiple that can be mapped using contiguous bits
  * in the page tables: 32 * PMD_SIZE (16k granule)
  */
-#if defined(CONFIG_ARM64_4K_PAGES)
-#define ARM64_MEMSTART_SHIFT		PUD_SHIFT
-#elif defined(CONFIG_ARM64_16K_PAGES)
-#define ARM64_MEMSTART_SHIFT		CONT_PMD_SHIFT
-#else
-#define ARM64_MEMSTART_SHIFT		PMD_SHIFT
-#endif
+#define ARM64_MEMSTART_SHIFT						\
+	(PAGE_SIZE == SZ_4K ?						\
+		PUD_SHIFT :						\
+		(PAGE_SIZE == SZ_16K ? CONT_PMD_SHIFT : PMD_SHIFT))
 
 /*
  * sparsemem vmemmap imposes an additional requirement on the alignment of
@@ -87,11 +84,10 @@ phys_addr_t __ro_after_init arm64_dma_phys_limit;
  * has a direct correspondence, and needs to appear sufficiently aligned
  * in the virtual address space.
  */
-#if ARM64_MEMSTART_SHIFT < SECTION_SIZE_BITS
-#define ARM64_MEMSTART_ALIGN	(1UL << SECTION_SIZE_BITS)
-#else
-#define ARM64_MEMSTART_ALIGN	(1UL << ARM64_MEMSTART_SHIFT)
-#endif
+#define ARM64_MEMSTART_ALIGN						\
+	(ARM64_MEMSTART_SHIFT < SECTION_SIZE_BITS ?			\
+		(1UL << SECTION_SIZE_BITS) :				\
+		(1UL << ARM64_MEMSTART_SHIFT))
 
 static void __init arch_reserve_crashkernel(void)
 {
arch/arm64/mm/kasan_init.c +4 -4
index b65a29440a0c9..9af897fb3c432 100644
@@ -178,10 +178,10 @@ static void __init kasan_pgd_populate(unsigned long addr, unsigned long end,
 	} while (pgdp++, addr = next, addr != end);
 }
 
-#if defined(CONFIG_ARM64_64K_PAGES) || CONFIG_PGTABLE_LEVELS > 4
+#if CONFIG_PGTABLE_LEVELS > 4
 #define SHADOW_ALIGN	P4D_SIZE
 #else
-#define SHADOW_ALIGN	PUD_SIZE
+#define SHADOW_ALIGN	(PAGE_SIZE == SZ_64K ? P4D_SIZE : PUD_SIZE)
 #endif
 
 /*
@@ -243,8 +243,8 @@ static int __init root_level_idx(u64 addr)
 	 * not implemented. This means we need to index the table as usual,
 	 * instead of masking off bits based on vabits_actual.
 	 */
-	u64 vabits = IS_ENABLED(CONFIG_ARM64_64K_PAGES) ? VA_BITS
-							: vabits_actual;
+	u64 vabits = PAGE_SIZE == SZ_64K ? VA_BITS
+					 : vabits_actual;
 	int shift = (ARM64_HW_PGTABLE_LEVELS(vabits) - 1) * (PAGE_SHIFT - 3);
 
 	return (addr & ~_PAGE_OFFSET(vabits)) >> (shift + PAGE_SHIFT);
arch/arm64/mm/mmu.c +1 -1
index d4d30eaefb4cd..a528787c1e550 100644
@@ -1179,7 +1179,7 @@ int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
 {
 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
 
-	if (!IS_ENABLED(CONFIG_ARM64_4K_PAGES))
+	if (PAGE_SIZE != SZ_4K)
 		return vmemmap_populate_basepages(start, end, node, altmap);
 	else
 		return vmemmap_populate_hugepages(start, end, node, altmap);
drivers/irqchip/irq-gic-v3-its.c +1 -1
index fdec478ba5e70..b745579b4b9f3 100644
@@ -2323,7 +2323,7 @@ static int its_setup_baser(struct its_node *its, struct its_baser *baser,
 	baser_phys = virt_to_phys(base);
 
 	/* Check if the physical address of the memory is above 48bits */
-	if (IS_ENABLED(CONFIG_ARM64_64K_PAGES) && (baser_phys >> 48)) {
+	if (PAGE_SIZE == SZ_64K && (baser_phys >> 48)) {
 
 		/* 52bit PA is supported only when PageSize=64K */
 		if (psz != SZ_64K) {
Signature · 1 line
2.43.0
author reviewer
#113 lore raw

RFC PATCH 44/57 arm64: Align sections to PAGE_SIZE_MAX

In reply to Ryan Roberts

Increase alignment of sections in nvhe hyp, vdso and final vmlinux image from PAGE_SIZE to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

For a boot-time page size build, image size is comparable to a 64K page size compile-time build. In future, it may be desirable to optimize run-time memory consumption by freeing unused padding pages when the boot-time selected page size is less than PAGE_SIZE_MAX.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/memory.h     |  4 +--
 arch/arm64/kernel/vdso-wrap.S       |  4 +--
 arch/arm64/kernel/vdso.c            |  7 +++---
 arch/arm64/kernel/vdso/vdso.lds.S   |  4 +--
 arch/arm64/kernel/vdso32-wrap.S     |  4 +--
 arch/arm64/kernel/vdso32/vdso.lds.S |  4 +--
 arch/arm64/kernel/vmlinux.lds.S     | 38 ++++++++++++++---------------
 arch/arm64/kvm/hyp/nvhe/hyp.lds.S   |  2 +-
 8 files changed, 34 insertions(+), 33 deletions(-)
arch/arm64/include/asm/memory.h +2 -2
index 6aa97fa22dc30..5393a859183f7 100644
@@ -195,13 +195,13 @@
  *  Open-coded (swapper_pg_dir - reserved_pg_dir) as this cannot be calculated
  *  until link time.
  */
-#define RESERVED_SWAPPER_OFFSET	(PAGE_SIZE)
+#define RESERVED_SWAPPER_OFFSET	(PAGE_SIZE_MAX)
 
 /*
  *  Open-coded (swapper_pg_dir - tramp_pg_dir) as this cannot be calculated
  *  until link time.
  */
-#define TRAMP_SWAPPER_OFFSET	(2 * PAGE_SIZE)
+#define TRAMP_SWAPPER_OFFSET	(2 * PAGE_SIZE_MAX)
 
 #ifndef __ASSEMBLY__
 
arch/arm64/kernel/vdso-wrap.S +2 -2
index c4b1990bf2be0..79fa77628199b 100644
@@ -13,10 +13,10 @@
 
 	.globl vdso_start, vdso_end
 	.section .rodata
-	.balign PAGE_SIZE
+	.balign PAGE_SIZE_MAX
 vdso_start:
 	.incbin "arch/arm64/kernel/vdso/vdso.so"
-	.balign PAGE_SIZE
+	.balign PAGE_SIZE_MAX
 vdso_end:
 
 	.previous
arch/arm64/kernel/vdso.c +4 -3
index 89b6e78400023..1efe98909a2e0 100644
@@ -195,7 +195,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 
 	vdso_text_len = vdso_info[abi].vdso_pages << PAGE_SHIFT;
 	/* Be sure to map the data page */
-	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE_MAX;
 
 	vdso_base = get_unmapped_area(NULL, 0, vdso_mapping_len, 0, 0);
 	if (IS_ERR_VALUE(vdso_base)) {
@@ -203,7 +203,8 @@ static int __setup_additional_pages(enum vdso_abi abi,
 		goto up_fail;
 	}
 
-	ret = _install_special_mapping(mm, vdso_base, VVAR_NR_PAGES * PAGE_SIZE,
+	ret = _install_special_mapping(mm, vdso_base,
+				       VVAR_NR_PAGES * PAGE_SIZE_MAX,
 				       VM_READ|VM_MAYREAD|VM_PFNMAP,
 				       vdso_info[abi].dm);
 	if (IS_ERR(ret))
@@ -212,7 +213,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 	if (system_supports_bti_kernel())
 		gp_flags = VM_ARM64_BTI;
 
-	vdso_base += VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_base += VVAR_NR_PAGES * PAGE_SIZE_MAX;
 	mm->context.vdso = (void *)vdso_base;
 	ret = _install_special_mapping(mm, vdso_base, vdso_text_len,
 				       VM_READ|VM_EXEC|gp_flags|
arch/arm64/kernel/vdso/vdso.lds.S +2 -2
index 45354f2ddf706..f7d1537a689e8 100644
@@ -18,9 +18,9 @@ OUTPUT_ARCH(aarch64)
 
 SECTIONS
 {
-	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE_MAX);
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
 
arch/arm64/kernel/vdso32-wrap.S +2 -2
index e72ac7bc4c04f..1c6069d6c457e 100644
@@ -10,10 +10,10 @@
 
 	.globl vdso32_start, vdso32_end
 	.section .rodata
-	.balign PAGE_SIZE
+	.balign PAGE_SIZE_MAX
 vdso32_start:
 	.incbin "arch/arm64/kernel/vdso32/vdso.so"
-	.balign PAGE_SIZE
+	.balign PAGE_SIZE_MAX
 vdso32_end:
 
 	.previous
arch/arm64/kernel/vdso32/vdso.lds.S +2 -2
index 8d95d7d35057d..c46d18a69d1ce 100644
@@ -18,9 +18,9 @@ OUTPUT_ARCH(arm)
 
 SECTIONS
 {
-	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE_MAX);
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
 
arch/arm64/kernel/vmlinux.lds.S +19 -19
index 7f3f6d709ae73..1ef6dea13b57c 100644
@@ -15,16 +15,16 @@
 
 #define HYPERVISOR_DATA_SECTIONS				\
 	HYP_SECTION_NAME(.rodata) : {				\
-		. = ALIGN(PAGE_SIZE);				\
+		. = ALIGN(PAGE_SIZE_MAX);			\
 		__hyp_rodata_start = .;				\
 		*(HYP_SECTION_NAME(.data..ro_after_init))	\
 		*(HYP_SECTION_NAME(.rodata))			\
-		. = ALIGN(PAGE_SIZE);				\
+		. = ALIGN(PAGE_SIZE_MAX);			\
 		__hyp_rodata_end = .;				\
 	}
 
 #define HYPERVISOR_PERCPU_SECTION				\
-	. = ALIGN(PAGE_SIZE);					\
+	. = ALIGN(PAGE_SIZE_MAX);				\
 	HYP_SECTION_NAME(.data..percpu) : {			\
 		*(HYP_SECTION_NAME(.data..percpu))		\
 	}
@@ -39,7 +39,7 @@
 #define BSS_FIRST_SECTIONS					\
 	__hyp_bss_start = .;					\
 	*(HYP_SECTION_NAME(.bss))				\
-	. = ALIGN(PAGE_SIZE);					\
+	. = ALIGN(PAGE_SIZE_MAX);				\
 	__hyp_bss_end = .;
 
 /*
@@ -48,7 +48,7 @@
  * between them, which can in some cases cause the linker to misalign them. To
  * work around the issue, force a page alignment for __bss_start.
  */
-#define SBSS_ALIGN			PAGE_SIZE
+#define SBSS_ALIGN			PAGE_SIZE_MAX
 #else /* CONFIG_KVM */
 #define HYPERVISOR_EXTABLE
 #define HYPERVISOR_DATA_SECTIONS
@@ -75,14 +75,14 @@ ENTRY(_text)
 jiffies = jiffies_64;
 
 #define HYPERVISOR_TEXT					\
-	. = ALIGN(PAGE_SIZE);				\
+	. = ALIGN(PAGE_SIZE_MAX);			\
 	__hyp_idmap_text_start = .;			\
 	*(.hyp.idmap.text)				\
 	__hyp_idmap_text_end = .;			\
 	__hyp_text_start = .;				\
 	*(.hyp.text)					\
 	HYPERVISOR_EXTABLE				\
-	. = ALIGN(PAGE_SIZE);				\
+	. = ALIGN(PAGE_SIZE_MAX);			\
 	__hyp_text_end = .;
 
 #define IDMAP_TEXT					\
@@ -113,11 +113,11 @@ jiffies = jiffies_64;
 
 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
 #define TRAMP_TEXT					\
-	. = ALIGN(PAGE_SIZE);				\
+	. = ALIGN(PAGE_SIZE_MAX);			\
 	__entry_tramp_text_start = .;			\
 	*(.entry.tramp.text)				\
-	. = ALIGN(PAGE_SIZE);				\
 	__entry_tramp_text_end = .;			\
+	. = ALIGN(PAGE_SIZE_MAX);			\
 	*(.entry.tramp.rodata)
 #else
 #define TRAMP_TEXT
@@ -187,7 +187,7 @@ SECTIONS
 	_etext = .;			/* End of text section */
 
 	/* everything from this point to __init_begin will be marked RO NX */
-	RO_DATA(PAGE_SIZE)
+	RO_DATA(PAGE_SIZE_MAX)
 
 	HYPERVISOR_DATA_SECTIONS
 
@@ -206,22 +206,22 @@ SECTIONS
 		HIBERNATE_TEXT
 		KEXEC_TEXT
 		IDMAP_TEXT
-		. = ALIGN(PAGE_SIZE);
+		. = ALIGN(PAGE_SIZE_MAX);
 	}
 
 	idmap_pg_dir = .;
-	. += PAGE_SIZE;
+	. += PAGE_SIZE_MAX;
 
 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
 	tramp_pg_dir = .;
-	. += PAGE_SIZE;
+	. += PAGE_SIZE_MAX;
 #endif
 
 	reserved_pg_dir = .;
-	. += PAGE_SIZE;
+	. += PAGE_SIZE_MAX;
 
 	swapper_pg_dir = .;
-	. += PAGE_SIZE;
+	. += PAGE_SIZE_MAX;
 
 	. = ALIGN(SEGMENT_ALIGN);
 	__init_begin = .;
@@ -290,7 +290,7 @@ SECTIONS
 
 	_data = .;
 	_sdata = .;
-	RW_DATA(L1_CACHE_BYTES, PAGE_SIZE, THREAD_ALIGN)
+	RW_DATA(L1_CACHE_BYTES, PAGE_SIZE_MAX, THREAD_ALIGN)
 
 	/*
 	 * Data written with the MMU off but read with the MMU on requires
@@ -317,7 +317,7 @@ SECTIONS
 	/* start of zero-init region */
 	BSS_SECTION(SBSS_ALIGN, 0, 0)
 
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE_MAX);
 	init_pg_dir = .;
 	. += INIT_DIR_SIZE_MAX;
 	init_pg_end = .;
@@ -356,7 +356,7 @@ SECTIONS
  * former is page-aligned, but the latter may not be with 16K or 64K pages, so
  * it should also not cross a page boundary.
  */
-ASSERT(__hyp_idmap_text_end - __hyp_idmap_text_start <= PAGE_SIZE,
+ASSERT(__hyp_idmap_text_end - __hyp_idmap_text_start <= SZ_4K,
 	"HYP init code too big")
 ASSERT(__idmap_text_end - (__idmap_text_start & ~(SZ_4K - 1)) <= SZ_4K,
 	"ID map text too big or misaligned")
@@ -367,7 +367,7 @@ ASSERT(__hibernate_exit_text_start == swsusp_arch_suspend_exit,
        "Hibernate exit text does not start with swsusp_arch_suspend_exit")
 #endif
 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
-ASSERT((__entry_tramp_text_end - __entry_tramp_text_start) <= 3*PAGE_SIZE,
+ASSERT((__entry_tramp_text_end - __entry_tramp_text_start) <= 3 * SZ_4K,
 	"Entry trampoline text too big")
 #endif
 #ifdef CONFIG_KVM
arch/arm64/kvm/hyp/nvhe/hyp.lds.S +1 -1
index f4562f417d3fc..74c7c21626270 100644
@@ -21,7 +21,7 @@ SECTIONS {
 	 * .hyp..data..percpu needs to be page aligned to maintain the same
 	 * alignment for when linking into vmlinux.
 	 */
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE_MAX);
 	BEGIN_HYP_SECTION(.data..percpu)
 		PERCPU_INPUT(L1_CACHE_BYTES)
 	END_HYP_SECTION
Signature · 1 line
2.43.0
#114 lore raw

Re: [RFC PATCH v1 44/57] arm64: Align sections to PAGE_SIZE_MAX

Quoted 65 lines · Ryan Roberts

Increase alignment of sections in nvhe hyp, vdso and final vmlinux image from PAGE_SIZE to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

For a boot-time page size build, image size is comparable to a 64K page size compile-time build. In future, it may be desirable to optimize run-time memory consumption by freeing unused padding pages when the boot-time selected page size is less than PAGE_SIZE_MAX.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/memory.h     |  4 +--
 arch/arm64/kernel/vdso-wrap.S       |  4 +--
 arch/arm64/kernel/vdso.c            |  7 +++---
 arch/arm64/kernel/vdso/vdso.lds.S   |  4 +--
 arch/arm64/kernel/vdso32-wrap.S     |  4 +--
 arch/arm64/kernel/vdso32/vdso.lds.S |  4 +--
 arch/arm64/kernel/vmlinux.lds.S     | 38 ++++++++++++++---------------
 arch/arm64/kvm/hyp/nvhe/hyp.lds.S   |  2 +-
 8 files changed, 34 insertions(+), 33 deletions(-)
arch/arm64/kernel/vdso.c +4 -3
index 89b6e78400023..1efe98909a2e0 100644
@@ -195,7 +195,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 
 	vdso_text_len = vdso_info[abi].vdso_pages << PAGE_SHIFT;
 	/* Be sure to map the data page */
-	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE_MAX;
 
 	vdso_base = get_unmapped_area(NULL, 0, vdso_mapping_len, 0, 0);
 	if (IS_ERR_VALUE(vdso_base)) {
@@ -203,7 +203,8 @@ static int __setup_additional_pages(enum vdso_abi abi,
 		goto up_fail;
 	}
 
-	ret = _install_special_mapping(mm, vdso_base, VVAR_NR_PAGES * PAGE_SIZE,
+	ret = _install_special_mapping(mm, vdso_base,
+				       VVAR_NR_PAGES * PAGE_SIZE_MAX,
 				       VM_READ|VM_MAYREAD|VM_PFNMAP,
 				       vdso_info[abi].dm);
 	if (IS_ERR(ret))
@@ -212,7 +213,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 	if (system_supports_bti_kernel())
 		gp_flags = VM_ARM64_BTI;
 
-	vdso_base += VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_base += VVAR_NR_PAGES * PAGE_SIZE_MAX;
 	mm->context.vdso = (void *)vdso_base;
 	ret = _install_special_mapping(mm, vdso_base, vdso_text_len,
 				       VM_READ|VM_EXEC|gp_flags|
arch/arm64/kernel/vdso/vdso.lds.S +0 -0
index 45354f2ddf706..f7d1537a689e8 100644

arch/arm64/kernel/vdso/vdso.lds.S OUTPUT_ARCH(aarch64) · line 23

Quoted 8 lines
arch/arm64/kernel/vdso/vdso.lds.S +2 -2
@@ -18,9 +18,9 @@ OUTPUT_ARCH(aarch64)
 
 SECTIONS
 {
-	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE_MAX);

This looks like it also needs a change to vvar_fault() in vdso.c. The symbols are now always PAGE_SIZE_MAX apart, while vvar_fault() works in page offsets (vmf->pgoff) that are based on the runtime PAGE_SIZE and it expects hardcoded offsets.

As test you can use tools/testing/selftests/timens/timens.

(I can't test this right now, so it's only a suspicion)

Quoted 18 lines
arch/arm64/kernel/vdso/vdso.lds.S +0 -0
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
 
arch/arm64/kernel/vdso32/vdso.lds.S +2 -2
index 8d95d7d35057d..c46d18a69d1ce 100644
@@ -18,9 +18,9 @@ OUTPUT_ARCH(arm)
 
 SECTIONS
 {
-	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE_MAX);
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
author reviewer
#115 lore raw

Re: [RFC PATCH v1 44/57] arm64: Align sections to PAGE_SIZE_MAX

Quoted 80 lines · Thomas Weißschuh
Quoted 65 lines · Ryan Roberts

Increase alignment of sections in nvhe hyp, vdso and final vmlinux image from PAGE_SIZE to PAGE_SIZE_MAX. For compile-time PAGE_SIZE, PAGE_SIZE_MAX == PAGE_SIZE so there is no change. For boot-time PAGE_SIZE, PAGE_SIZE_MAX is the largest selectable page size.

For a boot-time page size build, image size is comparable to a 64K page size compile-time build. In future, it may be desirable to optimize run-time memory consumption by freeing unused padding pages when the boot-time selected page size is less than PAGE_SIZE_MAX.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/memory.h     |  4 +--
 arch/arm64/kernel/vdso-wrap.S       |  4 +--
 arch/arm64/kernel/vdso.c            |  7 +++---
 arch/arm64/kernel/vdso/vdso.lds.S   |  4 +--
 arch/arm64/kernel/vdso32-wrap.S     |  4 +--
 arch/arm64/kernel/vdso32/vdso.lds.S |  4 +--
 arch/arm64/kernel/vmlinux.lds.S     | 38 ++++++++++++++---------------
 arch/arm64/kvm/hyp/nvhe/hyp.lds.S   |  2 +-
 8 files changed, 34 insertions(+), 33 deletions(-)
arch/arm64/kernel/vdso.c +4 -3
index 89b6e78400023..1efe98909a2e0 100644
@@ -195,7 +195,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 
 	vdso_text_len = vdso_info[abi].vdso_pages << PAGE_SHIFT;
 	/* Be sure to map the data page */
-	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE_MAX;
 
 	vdso_base = get_unmapped_area(NULL, 0, vdso_mapping_len, 0, 0);
 	if (IS_ERR_VALUE(vdso_base)) {
@@ -203,7 +203,8 @@ static int __setup_additional_pages(enum vdso_abi abi,
 		goto up_fail;
 	}
 
-	ret = _install_special_mapping(mm, vdso_base, VVAR_NR_PAGES * PAGE_SIZE,
+	ret = _install_special_mapping(mm, vdso_base,
+				       VVAR_NR_PAGES * PAGE_SIZE_MAX,
 				       VM_READ|VM_MAYREAD|VM_PFNMAP,
 				       vdso_info[abi].dm);
 	if (IS_ERR(ret))
@@ -212,7 +213,7 @@ static int __setup_additional_pages(enum vdso_abi abi,
 	if (system_supports_bti_kernel())
 		gp_flags = VM_ARM64_BTI;
 
-	vdso_base += VVAR_NR_PAGES * PAGE_SIZE;
+	vdso_base += VVAR_NR_PAGES * PAGE_SIZE_MAX;
 	mm->context.vdso = (void *)vdso_base;
 	ret = _install_special_mapping(mm, vdso_base, vdso_text_len,
 				       VM_READ|VM_EXEC|gp_flags|
arch/arm64/kernel/vdso/vdso.lds.S +0 -0
index 45354f2ddf706..f7d1537a689e8 100644

arch/arm64/kernel/vdso/vdso.lds.S OUTPUT_ARCH(aarch64) · line 23

Quoted 8 lines
arch/arm64/kernel/vdso/vdso.lds.S +2 -2
@@ -18,9 +18,9 @@ OUTPUT_ARCH(aarch64)
 
 SECTIONS
 {
-	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE(_timens_data = _vdso_data + PAGE_SIZE_MAX);

This looks like it also needs a change to vvar_fault() in vdso.c. The symbols are now always PAGE_SIZE_MAX apart, while vvar_fault() works in page offsets (vmf->pgoff) that are based on the runtime PAGE_SIZE and it expects hardcoded offsets.

Quoted 3 lines

As test you can use tools/testing/selftests/timens/timens.

(I can't test this right now, so it's only a suspicion)

Ahh good spot - that test does infact fail.

This fixes the problem:

---8<---

arch/arm64/kernel/vdso.c +0 -0
index 1efe98909a2e0..d2049ba6b19f5 100644
@@ -151,10 +151,11 @@ int vdso_join_timens(struct task_struct *task, struct

time_namespace *ns)
static vm_fault_t vvar_fault(const struct vm_special_mapping *sm,
struct vm_area_struct *vma, struct vm_fault *vmf)
{

+       pgoff_t pgmaxoff = vmf->pgoff >> (PAGE_SHIFT_MAX - PAGE_SHIFT);
        struct page *timens_page = find_timens_vvar_page(vma);
        unsigned long pfn;

- switch (vmf->pgoff) {

+       switch (pgmaxoff) {
        case VVAR_DATA_PAGE_OFFSET:
                if (timens_page)
                        pfn = page_to_pfn(timens_page);

---8<---

I'll include it in the next version.

Thanks,
Ryan

Quoted 19 lines
Quoted 19 lines
arch/arm64/kernel/vdso/vdso.lds.S +0 -0
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
 
arch/arm64/kernel/vdso32/vdso.lds.S +2 -2
index 8d95d7d35057d..c46d18a69d1ce 100644
@@ -18,9 +18,9 @@ OUTPUT_ARCH(arm)
 
 SECTIONS
 {
-	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE);
+	PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE_MAX);
 #ifdef CONFIG_TIME_NS
-	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE);
+	PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE_MAX);
 #endif
 	. = VDSO_LBASE + SIZEOF_HEADERS;
author reviewer
#116 lore raw

RFC PATCH 45/57 arm64: Rework trampoline rodata mapping

In reply to Ryan Roberts

Now that the trampoline rodata is aligned to the next PAGE_SIZE_MAX boundary after the end of the trampoline text, the code that maps it in the fixmap is incorrect, because it still assumes the rodata is in the next page immediately after the text. Of course it still works for now with compile-time page size but for boot-time page size when selecting a page size less than PAGE_SIZE_MAX, it will fail.

So let's fix that by allocating sufficient fixmap slots to cover the extra alignment padding in the worst case (PAGE_SIZE == PAGE_SIZE_MIN) and explicitly mapping the rodata to the slot offset correctly from the text.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/fixmap.h   | 16 +++++++++++-----
 arch/arm64/include/asm/sections.h |  1 +
 arch/arm64/kernel/vmlinux.lds.S   |  4 +++-
 arch/arm64/mm/mmu.c               | 22 ++++++++++++++--------
 4 files changed, 29 insertions(+), 14 deletions(-)
arch/arm64/include/asm/fixmap.h +11 -5
index 87e307804b99c..9a496d54dfe6e 100644
@@ -59,13 +59,19 @@ enum fixed_addresses {
 #endif /* CONFIG_ACPI_APEI_GHES */
 
 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
+#define TRAMP_TEXT_SIZE	(PAGE_SIZE_MIN * 3)
 #ifdef CONFIG_RELOCATABLE
-	FIX_ENTRY_TRAMP_TEXT4,	/* one extra slot for the data page */
+#define TRAMP_DATA_SIZE	PAGE_SIZE_MIN
+#define TRAMP_PAD_SIZE	(PAGE_SIZE_MAX - PAGE_SIZE_MIN)
+#else
+#define TRAMP_DATA_SIZE	0
+#define TRAMP_PAD_SIZE	0
 #endif
-	FIX_ENTRY_TRAMP_TEXT3,
-	FIX_ENTRY_TRAMP_TEXT2,
-	FIX_ENTRY_TRAMP_TEXT1,
-#define TRAMP_VALIAS		(__fix_to_virt(FIX_ENTRY_TRAMP_TEXT1))
+#define TRAMP_SIZE	(TRAMP_TEXT_SIZE + TRAMP_DATA_SIZE + TRAMP_PAD_SIZE)
+	FIX_ENTRY_TRAMP_END,
+	FIX_ENTRY_TRAMP_BEGIN = FIX_ENTRY_TRAMP_END +
+				DIV_ROUND_UP(TRAMP_SIZE, PAGE_SIZE_MIN) - 1,
+#define TRAMP_VALIAS		(__fix_to_virt(FIX_ENTRY_TRAMP_BEGIN))
 #endif /* CONFIG_UNMAP_KERNEL_AT_EL0 */
 	__end_of_permanent_fixed_addresses,
 
arch/arm64/include/asm/sections.h +1 -0
index 40971ac1303f9..252ec58963093 100644
@@ -21,6 +21,7 @@ extern char __exittext_begin[], __exittext_end[];
 extern char __irqentry_text_start[], __irqentry_text_end[];
 extern char __mmuoff_data_start[], __mmuoff_data_end[];
 extern char __entry_tramp_text_start[], __entry_tramp_text_end[];
+extern char __entry_tramp_rodata_start[], __entry_tramp_rodata_end[];
 extern char __relocate_new_kernel_start[], __relocate_new_kernel_end[];
 
 static inline size_t entry_tramp_text_size(void)
arch/arm64/kernel/vmlinux.lds.S +3 -1
index 1ef6dea13b57c..09fcc234c0f77 100644
@@ -118,7 +118,9 @@ jiffies = jiffies_64;
 	*(.entry.tramp.text)				\
 	__entry_tramp_text_end = .;			\
 	. = ALIGN(PAGE_SIZE_MAX);			\
-	*(.entry.tramp.rodata)
+	__entry_tramp_rodata_start = .;			\
+	*(.entry.tramp.rodata)				\
+	__entry_tramp_rodata_end = .;
 #else
 #define TRAMP_TEXT
 #endif
arch/arm64/mm/mmu.c +14 -8
index a528787c1e550..84df9f278d24d 100644
@@ -734,25 +734,31 @@ static int __init map_entry_trampoline(void)
 		return 0;
 
 	pgprot_t prot = kernel_exec_prot();
-	phys_addr_t pa_start = __pa_symbol(__entry_tramp_text_start);
+	phys_addr_t pa_text = __pa_symbol(__entry_tramp_text_start);
+	phys_addr_t pa_data = __pa_symbol(__entry_tramp_rodata_start);
+	int slot = FIX_ENTRY_TRAMP_BEGIN;
 
 	/* The trampoline is always mapped and can therefore be global */
 	pgprot_val(prot) &= ~PTE_NG;
 
 	/* Map only the text into the trampoline page table */
 	memset(tramp_pg_dir, 0, PGD_SIZE);
-	__create_pgd_mapping(tramp_pg_dir, pa_start, TRAMP_VALIAS,
+	__create_pgd_mapping(tramp_pg_dir, pa_text, TRAMP_VALIAS,
 			     entry_tramp_text_size(), prot,
 			     __pgd_pgtable_alloc, NO_BLOCK_MAPPINGS);
 
 	/* Map both the text and data into the kernel page table */
-	for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++)
-		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
-			     pa_start + i * PAGE_SIZE, prot);
+	for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++) {
+		__set_fixmap(slot, pa_text, prot);
+		pa_text += PAGE_SIZE;
+		slot--;
+	}
 
-	if (IS_ENABLED(CONFIG_RELOCATABLE))
-		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
-			     pa_start + i * PAGE_SIZE, PAGE_KERNEL_RO);
+	if (IS_ENABLED(CONFIG_RELOCATABLE)) {
+		slot -= (pa_data - pa_text) / PAGE_SIZE;
+		VM_BUG_ON(slot < FIX_ENTRY_TRAMP_END);
+		__set_fixmap(slot, pa_data, PAGE_KERNEL_RO);
+	}
 
 	return 0;
 }
Signature · 1 line
2.43.0
author reviewer
#117 lore raw

RFC PATCH 46/57 arm64: Generalize fixmap for boot-time page size

In reply to Ryan Roberts

Some fixmap fixed address slots previously depended on PAGE_SIZE (i.e. to determine how many slots were required to cover a given size). Since we require the fixed address slots to be compile-time constant, let's work out the worst case number of required slots when page size is PAGE_SIZE_MIN instead.

Additionally, let's determine the worst-case number of PTE tables we require and statically allocate enough memory.

For compile-time page size builds, the end result is the same as it was previously.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/fixmap.h | 12 ++++++++----
 arch/arm64/mm/fixmap.c          | 34 ++++++++++++++++++++++-----------
 2 files changed, 31 insertions(+), 15 deletions(-)
arch/arm64/include/asm/fixmap.h +8 -4
index 9a496d54dfe6e..c73fd3c1334ff 100644
@@ -43,7 +43,7 @@ enum fixed_addresses {
 	 * whether it crosses any page boundary.
 	 */
 	FIX_FDT_END,
-	FIX_FDT = FIX_FDT_END + DIV_ROUND_UP(MAX_FDT_SIZE, PAGE_SIZE) + 1,
+	FIX_FDT = FIX_FDT_END + DIV_ROUND_UP(MAX_FDT_SIZE, PAGE_SIZE_MIN) + 1,
 
 	FIX_EARLYCON_MEM_BASE,
 	FIX_TEXT_POKE0,
@@ -79,7 +79,7 @@ enum fixed_addresses {
 	 * Temporary boot-time mappings, used by early_ioremap(),
 	 * before ioremap() is functional.
 	 */
-#define NR_FIX_BTMAPS		(SZ_256K / PAGE_SIZE)
+#define NR_FIX_BTMAPS		(SZ_256K / PAGE_SIZE_MIN)
 #define FIX_BTMAPS_SLOTS	7
 #define TOTAL_FIX_BTMAPS	(NR_FIX_BTMAPS * FIX_BTMAPS_SLOTS)
 
@@ -101,8 +101,12 @@ enum fixed_addresses {
 
 #define FIXADDR_SIZE		(__end_of_permanent_fixed_addresses << PAGE_SHIFT)
 #define FIXADDR_START		(FIXADDR_TOP - FIXADDR_SIZE)
-#define FIXADDR_TOT_SIZE	(__end_of_fixed_addresses << PAGE_SHIFT)
-#define FIXADDR_TOT_START	(FIXADDR_TOP - FIXADDR_TOT_SIZE)
+#define __FIXADDR_TOT_SIZE(page_shift)					\
+	(__end_of_fixed_addresses << (page_shift))
+#define __FIXADDR_TOT_START(page_shift)					\
+	(FIXADDR_TOP - __FIXADDR_TOT_SIZE(page_shift))
+#define FIXADDR_TOT_SIZE	__FIXADDR_TOT_SIZE(PAGE_SHIFT)
+#define FIXADDR_TOT_START	__FIXADDR_TOT_START(PAGE_SHIFT)
 
 #define FIXMAP_PAGE_IO     __pgprot(PROT_DEVICE_nGnRE)
 
arch/arm64/mm/fixmap.c +23 -11
index 15ce3253ad359..a0dcf2375ccb4 100644
@@ -17,27 +17,39 @@
 #include <asm/tlbflush.h>
 
 /* ensure that the fixmap region does not grow down into the PCI I/O region */
-static_assert(FIXADDR_TOT_START > PCI_IO_END);
+static_assert(__FIXADDR_TOT_START(PAGE_SHIFT_MAX) > PCI_IO_END);
 
-#define NR_BM_PTE_TABLES \
-	SPAN_NR_ENTRIES(FIXADDR_TOT_START, FIXADDR_TOP, PMD_SHIFT)
-#define NR_BM_PMD_TABLES \
-	SPAN_NR_ENTRIES(FIXADDR_TOT_START, FIXADDR_TOP, PUD_SHIFT)
+#define FIXMAP_LEVEL(page_shift, lvl, vstart, vend)			\
+	SPAN_NR_ENTRIES(vstart, vend, PGTABLE_LEVEL_SHIFT(page_shift, lvl))
 
-static_assert(NR_BM_PMD_TABLES == 1);
+#define FIXMAP_PAGES(page_shift, level)					\
+	FIXMAP_LEVEL(page_shift, level,					\
+		     __FIXADDR_TOT_START(page_shift), FIXADDR_TOP)
+
+#define FIXMAP_SIZE(page_shift, level)					\
+	(FIXMAP_PAGES(page_shift, level) * (UL(1) << (page_shift)))
+
+#define FIXMAP_PTE_SIZE_MAX						\
+	MAX_IF_HAVE_PGSZ(FIXMAP_SIZE(ARM64_PAGE_SHIFT_4K, 2),		\
+			 FIXMAP_SIZE(ARM64_PAGE_SHIFT_16K, 2),		\
+			 FIXMAP_SIZE(ARM64_PAGE_SHIFT_64K, 2))
+
+static_assert(FIXMAP_PAGES(ARM64_PAGE_SHIFT_4K, 1) == 1);
+static_assert(FIXMAP_PAGES(ARM64_PAGE_SHIFT_16K, 1) == 1);
+static_assert(FIXMAP_PAGES(ARM64_PAGE_SHIFT_64K, 1) == 1);
 
 #define __BM_TABLE_IDX(addr, shift) \
 	(((addr) >> (shift)) - (FIXADDR_TOT_START >> (shift)))
 
 #define BM_PTE_TABLE_IDX(addr)	__BM_TABLE_IDX(addr, PMD_SHIFT)
 
-static pte_t bm_pte[NR_BM_PTE_TABLES][PTRS_PER_PTE] __page_aligned_bss;
-static pmd_t bm_pmd[PTRS_PER_PMD] __page_aligned_bss __maybe_unused;
-static pud_t bm_pud[PTRS_PER_PUD] __page_aligned_bss __maybe_unused;
+static pte_t bm_pte[FIXMAP_PTE_SIZE_MAX / sizeof(pte_t)] __page_aligned_bss;
+static pmd_t bm_pmd[MAX_PTRS_PER_PMD] __page_aligned_bss __maybe_unused;
+static pud_t bm_pud[MAX_PTRS_PER_PUD] __page_aligned_bss __maybe_unused;
 
 static inline pte_t *fixmap_pte(unsigned long addr)
 {
-	return &bm_pte[BM_PTE_TABLE_IDX(addr)][pte_index(addr)];
+	return &bm_pte[BM_PTE_TABLE_IDX(addr) * PTRS_PER_PTE + pte_index(addr)];
 }
 
 static void __init early_fixmap_init_pte(pmd_t *pmdp, unsigned long addr)
@@ -46,7 +58,7 @@ static void __init early_fixmap_init_pte(pmd_t *pmdp, unsigned long addr)
 	pte_t *ptep;
 
 	if (pmd_none(pmd)) {
-		ptep = bm_pte[BM_PTE_TABLE_IDX(addr)];
+		ptep = &bm_pte[BM_PTE_TABLE_IDX(addr) * PTRS_PER_PTE];
 		__pmd_populate(pmdp, __pa_symbol(ptep), PMD_TYPE_TABLE);
 	}
 }
Signature · 1 line
2.43.0
author reviewer
#118 lore raw

RFC PATCH 47/57 arm64: Statically allocate and align for worst-case page size

In reply to Ryan Roberts

Increase the size and alignment of the zero page and various static buffers used for page tables to PAGE_SIZE_MAX. This resolves to the same thing for compile-time page size builds.

For boot-time builds, we may in future consider freeing unused pages at runtime when the selected page size is less than MAX.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/include/asm/pgtable.h  | 2 +-
 arch/arm64/kernel/pi/map_kernel.c | 2 +-
 arch/arm64/mm/mmu.c               | 6 +++---
 3 files changed, 5 insertions(+), 5 deletions(-)
arch/arm64/include/asm/pgtable.h +1 -1
index 7a4f5604be3f7..fd47f70a42396 100644
@@ -61,7 +61,7 @@
  * ZERO_PAGE is a global shared page that is always zero: used
  * for zero-mapped memory areas etc..
  */
-extern unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)];
+extern unsigned long empty_zero_page[PAGE_SIZE_MAX / sizeof(unsigned long)];
 #define ZERO_PAGE(vaddr)	phys_to_page(__pa_symbol(empty_zero_page))
 
 #define pte_ERROR(e)	\
arch/arm64/kernel/pi/map_kernel.c +1 -1
index 7a62d4238449d..deb8cd50b0b0c 100644
@@ -199,7 +199,7 @@ static void __init remap_idmap(bool use_lpa2, int page_shift)
 
 static void __init map_fdt(u64 fdt, int page_shift)
 {
-	static u8 ptes[INIT_IDMAP_FDT_SIZE_MAX] __initdata __aligned(PAGE_SIZE);
+	static u8 ptes[INIT_IDMAP_FDT_SIZE_MAX] __initdata __aligned(PAGE_SIZE_MAX);
 	static bool first_time __initdata = true;
 	u64 limit = (u64)&ptes[INIT_IDMAP_FDT_SIZE_MAX];
 	u64 efdt = fdt + MAX_FDT_SIZE;
arch/arm64/mm/mmu.c +3 -3
index 84df9f278d24d..b4cd3b6a73c22 100644
@@ -62,7 +62,7 @@ long __section(".mmuoff.data.write") __early_cpu_boot_status;
  * Empty_zero_page is a special page that is used for zero-initialized data
  * and COW.
  */
-unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)] __page_aligned_bss;
+unsigned long empty_zero_page[PAGE_SIZE_MAX / sizeof(unsigned long)] __page_aligned_bss;
 EXPORT_SYMBOL(empty_zero_page);
 
 static DEFINE_SPINLOCK(swapper_pgdir_lock);
@@ -783,8 +783,8 @@ void __pi_map_range(u64 *pgd, u64 limit, u64 start, u64 end, u64 pa,
 		    pgprot_t prot, int level, pte_t *tbl, bool may_use_cont,
 		    u64 va_offset);
 
-static u8 idmap_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
-	  kpti_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
+static u8 idmap_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE_MAX] __aligned(PAGE_SIZE_MAX) __ro_after_init,
+	  kpti_ptes[IDMAP_LEVELS_MAX - 1][PAGE_SIZE_MAX] __aligned(PAGE_SIZE_MAX) __ro_after_init;
 
 static void __init create_idmap(void)
 {
Signature · 1 line
2.43.0
author reviewer
#119 lore raw

RFC PATCH 48/57 arm64: Convert switch to if for non-const comparison values

In reply to Ryan Roberts

When we enable boot-time page size, some macros are no longer compile-time constants. Where these macros are used as cases in switch statements, the switch statements no longer compile.

Let's convert these to if/else blocks, which can handle the runtime values.

---

***NOTE***
Any confused maintainers may want to read the cover note here for context:
https://lore.kernel.org/all/[email protected]/

 arch/arm64/kvm/mmu.c        | 32 +++++++++++++++-----------------
 arch/arm64/mm/hugetlbpage.c | 34 +++++++++++-----------------------
 2 files changed, 26 insertions(+), 40 deletions(-)
arch/arm64/kvm/mmu.c +15 -17
index a509b63bd4dd5..248a2d7ad6dbb 100644
@@ -1487,29 +1487,27 @@ static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
 		vma_shift = get_vma_page_shift(vma, hva);
 	}
 
-	switch (vma_shift) {
 #ifndef __PAGETABLE_PMD_FOLDED
-	case PUD_SHIFT:
-		if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
-			break;
-		fallthrough;
+	if (vma_shift == PUD_SHIFT) {
+		if (!fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
+			vma_shift = PMD_SHIFT;
+	}
 #endif
-	case CONT_PMD_SHIFT:
+	if (vma_shift == CONT_PMD_SHIFT) {
 		vma_shift = PMD_SHIFT;
-		fallthrough;
-	case PMD_SHIFT:
-		if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
-			break;
-		fallthrough;
-	case CONT_PTE_SHIFT:
+	}
+	if (vma_shift == PMD_SHIFT) {
+		if (!fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
+			vma_shift = PAGE_SHIFT;
+	}
+	if (vma_shift == CONT_PTE_SHIFT) {
 		vma_shift = PAGE_SHIFT;
 		force_pte = true;
-		fallthrough;
-	case PAGE_SHIFT:
-		break;
-	default:
-		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
 	}
+	if (vma_shift != PUD_SHIFT &&
+	    vma_shift != PMD_SHIFT &&
+	    vma_shift != PAGE_SHIFT)
+		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
 
 	vma_pagesize = 1UL << vma_shift;
 
arch/arm64/mm/hugetlbpage.c +11 -23
index 5f1e2103888b7..bc98c20655bba 100644
@@ -51,16 +51,12 @@ void __init arm64_hugetlb_cma_reserve(void)
 
 static bool __hugetlb_valid_size(unsigned long size)
 {
-	switch (size) {
 #ifndef __PAGETABLE_PMD_FOLDED
-	case PUD_SIZE:
+	if (size == PUD_SIZE)
 		return pud_sect_supported();
 #endif
-	case CONT_PMD_SIZE:
-	case PMD_SIZE:
-	case CONT_PTE_SIZE:
+	if (size == CONT_PMD_SIZE || size == PMD_SIZE || size == CONT_PTE_SIZE)
 		return true;
-	}
 
 	return false;
 }
@@ -104,24 +100,20 @@ static inline int num_contig_ptes(unsigned long size, size_t *pgsize)
 
 	*pgsize = size;
 
-	switch (size) {
 #ifndef __PAGETABLE_PMD_FOLDED
-	case PUD_SIZE:
+	if (size == PUD_SIZE) {
 		if (pud_sect_supported())
 			contig_ptes = 1;
-		break;
+	} else
 #endif
-	case PMD_SIZE:
+	if (size == PMD_SIZE) {
 		contig_ptes = 1;
-		break;
-	case CONT_PMD_SIZE:
+	} else if (size == CONT_PMD_SIZE) {
 		*pgsize = PMD_SIZE;
 		contig_ptes = CONT_PMDS;
-		break;
-	case CONT_PTE_SIZE:
+	} else if (size == CONT_PTE_SIZE) {
 		*pgsize = PAGE_SIZE;
 		contig_ptes = CONT_PTES;
-		break;
 	}
 
 	return contig_ptes;
@@ -339,20 +331,16 @@ unsigned long hugetlb_mask_last_page(struct hstate *h)
 {
 	unsigned long hp_size = huge_page_size(h);
 
-	switch (hp_size) {
 #ifndef __PAGETABLE_PMD_FOLDED
-	case PUD_SIZE:
+	if (hp_size == PUD_SIZE)
 		return PGDIR_SIZE - PUD_SIZE;
 #endif
-	case CONT_PMD_SIZE:
+	if (hp_size == CONT_PMD_SIZE)
 		return PUD_SIZE - CONT_PMD_SIZE;
-	case PMD_SIZE:
+	if (hp_size == PMD_SIZE)
 		return PUD_SIZE - PMD_SIZE;
-	case CONT_PTE_SIZE:
+	if (hp_size == CONT_PTE_SIZE)
 		return PMD_SIZE - CONT_PTE_SIZE;
-	default:
-		break;
-	}
 
 	return 0UL;
 }
Signature · 1 line
2.43.0