Skip to contentSkip to conversation

kbuild: significantly speed up kernel builds

PATCH Superseded Lorenzo Stoakes (ARM) 8 participants 76 messages Sep 17 – Sep 22

Subsystems (12)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover kbuild: significantly speed up kernel builds

A typical kernel build consists of a frustratingly large amount of time spent stuck in single-threaded bottlenecks.

It turns out that there's a lot we can do about this and doing so significantly impacts kernel build times.

This series makes allmodconfig builds up to 36% faster, incremental builds up to ~70% faster, and noop builds up to ~90% faster.

Builds are faster across the board on every device I tested.

Machines used for perf testing:

* Threadripper - x86, AMD Threadripper 9980X, 64 cores, 128 threads
* EPYC - x86, 2 socket EPYC 9754, 256 cores, 512 threads
* M2 - arm64, 2022 M2 macbook pro, 8 cores, 8 threads
(4 perf, 4 efficiency)

Cutting to the chase:

		== IMPORTANT NOTE on dependencies/build configuration ==

Performance numbers are based on a build which:

* Has these series applied (as these supersede changes from a previous version of this series):

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

* Runs make KRUSTFLAGS=-Zthreads=8 -j $(nproc) ....
* Runs with the pigz tool installed locally.

		== allmodconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       344.2s   278.6s    -65.6s (-19%)
Threadripper, clang     342.6s   266.8s    -75.8s (-22%)
EPYC, gcc               188.0s   121.1s    -66.9s (-36%)
EPYC, clang             259.5s   184.6s    -74.9s (-29%)
		== allmodconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        40.1s    15.4s    -24.7s (-62%)
Threadripper, clang      40.3s    15.6s    -24.8s (-61%)
EPYC, gcc                70.9s    24.3s    -46.6s (-66%)
EPYC, clang              70.4s    24.3s    -46.1s (-65%)
		== allmodconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        15.3s     1.4s    -13.9s (-91%)
Threadripper, clang      16.2s     1.8s    -14.4s (-89%)
EPYC, gcc                30.6s     1.5s    -29.1s (-95%)
EPYC, clang              32.3s     2.2s    -30.1s (-93%)
		== defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        32.5s    26.3s     -6.1s (-19%)
Threadripper, clang      34.5s    27.2s     -7.3s (-21%)
EPYC, gcc                28.7s    20.6s     -8.1s (-28%)
EPYC, clang              39.8s    32.2s     -7.6s (-19%)
M2, gcc                 519.3s   512.4s     -6.9s (-1%)

M2, clang 634.5s 569.4s -65.1s (-10%)

		== defconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        11.2s     6.0s     -5.3s (-47%)
Threadripper, clang      11.3s     5.4s     -5.9s (-52%)
EPYC, gcc                18.6s     9.2s     -9.4s (-51%)
EPYC, clang              19.6s     8.6s    -11.0s (-56%)
M2, gcc                  18.0s     9.9s     -8.1s (-45%)
M2, clang                18.1s     8.2s     -9.9s (-55%)
		== defconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc         1.1s    0.60s    -0.50s (-45%)
Threadripper, clang       1.3s    0.66s    -0.63s (-49%)
EPYC, gcc                 1.7s    0.66s     -1.0s (-61%)
EPYC, clang               2.0s    0.80s     -1.2s (-60%)
M2, gcc                   6.4s     1.7s     -4.7s (-74%)
M2, clang                 7.1s     1.7s     -5.4s (-76%)

Further performance numbers are provided for each commit giving a sense of what each contributes to the final result.

			== Testing ==

Beyond x86, allmodconfig was built with the series for arm64, arm, riscv, powerpc64, s390 and loongarch, and for arm64, arm, s390 and loongarch the System.map is identical to what the previous shell mksysmap produces for the same vmlinux.

Also tested were parisc64 and m68k build as far as mainline lets them (a driver's static assertion and an undefined-symbol check on parisc, gcc 16 internal compiler errors on m68k, none of it from this series).

Kernels for x86, arm64, arm, riscv, loongarch, powerpc64, s390, m68k and parisc64 all boot under qemu, every text symbol of System.map is in /proc/kallsyms at the relocated address, and a module loads and unloads. The s390, arm and loongarch kernels also pass the kallsyms selftest.

An x86 kernel with CONFIG_MODVERSIONS, CONFIG_EXTENDED_MODVERSIONS and CONFIG_MODULE_SRCVERSION_ALL boots, loads and unloads modules. External modules build against both in-tree and O= builds, and every commit builds on x86 defconfig.

Build times are the best of several runs, no unexpected errors or warnings were seen.

While some aspects of the build process have been changed, all tooling should function identically to before.

			== LLM usage ==

An LLM was used to first determine where the bottlenecks were then to figure out how to improve them.

It generated a lot of code, much of it hideous.

I extensively audited and rewrote a lot of it, and heavily edited commit messages, the cover letter and comments.

The LLM has also orchestrated build runs, testing, debugging and analysis.

I have manually checked for correctness in both build and running kernels generated with this series applied.

Performance improvements were also verified manually.

Since an LLM was used extensively, each commit carries an Assisted-by tag.

			== What was changed? ==

Fundamentally the series improves build times by parallelising single-threaded tasks as much as possible and improving the efficiency of code used in the build process.

kbuild, kallsyms, modpost, objtool, mksysmap and the rust build system were all updated as part of this change.

Nothing too controversial was included. There are further improvements that could be made, but they would either by very invasive (large scale C header changes) or generate diminishing returns.

			== Patches ==

kbuild (1): Make .modinfo an INFO section.

kallsyms (2, 3): Some efficiency improvements through use of a cache.

kbuild (4, 5): Don't sort nm output unnecessarily, do not include
relocations in the kallsyms trial links.

elf-parse (6): Section flags, symbol binding and a read-only mapping,
for the next patch.

kallsyms (7): Don't use nm, read the ELF symbol table directly.

kbuild (8, 9): Implement a cache to track objects, check dependency
timestamps more efficiently.

kbuild (10): Move the toolchain checks into their own Kconfig file.

kbuild (11): Probe compiler, linker flags once at top of build.

modpost (12): Improve performance through use of a cache.

modules (13, 14): Emit module descriptors as assembly (*.mod.S) rather
than C (*.mod.c), reducing CPU seconds taken by 10x to perform the task. Also shard module finalisation rather than running 10's of thousands of tiny runs.

objtool (15-17): Replace reloc hash with a per-section index, size
the instruction hash to the code rather than hard-code it, and decode large objects over multiple threads.

rust (18, 19): Set correct dependencies and build crates in parallel
with C code, retaining the requirement that rust/ crates are built first.

kbuild (20): Default to using a parallel implementation of gzip
(pigz) if available on the system.

---
v3:
* Rebased on Linus's master branch.
* Fixed link to Josh's series, which was wrongly pointing at a single commit as per Andre (off-list).
* Fixed typo in 11/20 (+ fixed a couple more), as per John.
* Hardened depcheck in 9/20 against a .cmd file with an empty name as per Sashiko.
* Updated 14/20 so only the top-level make instance builds .module-common.o the chunk instances treat it as a plain prerequisite, to prevent a child accidentally building it as per Sashiko.
* Updated 15/20 to drop the relocation hash altogether, building one section at a time incrementally, falling back to linear scan for anything out of order (not sure that'll ever happen though?) as per Josh, Linus.
* Updated 17/20 to limit the parallelisation to the --link step only (in practice - objtool's processing of vmlinux.o) + updated commit msg to reflect, as per Kees.
* Updated the commit message in 14/20 to give clearer rationales for the batching of modfinal instances, as per Kees.
* Dropped what was 18/21 - the rustc front end threading patch, as the parallel flag name is still uncertain and a user can set KRUSTFLAGS=-Zthreads=8 to get the behaviour without it. Also updated cover letter pre-requisite section to mention this, as per Miguel.
* Updated 19/20 (was 20/21) so modules_prepare no longer builds rust/ when a goal that builds the tree is also given, ensuring duplicate rust/ builds do not happen, as per Kees.
* Updated 20/20 (was 21/21) to remove the reproducible build doc update, as per Kees.
* Updated 20/20 (was 21/21) to have pigz use the make job server and to define a specific kernel build variable for this - KPGZIP - also fold in a further suggestion which eliminates a wrapper script, as per Kees.

v2:
* Rebased on Linus's master branch.
* Removed the first 2 fix patches as they have been taken to upstream in commit 281b61d408d4 ("scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms") and commit 59351365ac27 ("scripts/mksysmap: fix escape of '$' in the __pi_ pattern") - thanks Nicolas!
* Fixed patch 3/21 (previously 4/23) to check error on close via ferror() and fclose() as per David Laight.
* Updated 21/21 to not use threads for modules, only for vmlinux, and updated docs to reflect this.
* Dropped patches (as was) 13 and 17 as the equivalent work is being performed upstream:
https://lore.kernel.org/linux-modules/[email protected]/
* Updated the cover letter to mention the dependency on this series for perf numbers.
* Fixed various typos.
* Checked all of the hallucinated sashiko reports. Replied inline to emails to keep a record of them but not going to repeat here, unless people want a list.
* Fixed up 9/21 (was 11/23) to fix the bit of sashiko's report that wasn't hallucinated - check ferror() to bring depcheck in line with fixdep and kallsyms.
* Fixed up patch 13/21 (was 15/23) to emit the __this_module fields in offset order to handle CONFIG_RANDSTRUCT as per Sashiko.
* Fixed up patch 19/23 (now 17/21) to resolve various races. Sashiko hallucinated a lot of the report, and missed some stuff thread sanitizer found. Resolve call destinations serially to resolve most of the valid stuff and add a lock around pv_ops, and instruction hash freed properly. Tested and confirmed resolved locally, as per Sashiko.
* Fixed up patch 20/21 (was 22/23) to only build rust/ when modules_prepare is one of several make goals, rather than the only one. This matches the rest of the Makefile's behaviour on this and ensures rust components are built if multiple build choices are passed to make, as per Sashiko.
* Fixed up patch 5/21 (was 6/23) to test CONFIG_ARCH_VMLINUX_NEEDS_RELOCS directly in link-vmlinux.sh rather than plumbing a var through, for a far smaller patch as per Nathan.
* Moved patch 1/21 (was 9/23) to the front of the series and dropped two comments, as per Nathan, so it can go in ahead of the rest.
* Added patch 10/21 moving the existing toolchain checks out of init/Kconfig into init/Kconfig.toolchain, as per Nathan, with 11/21 adding to it.
* In 11/21 (previously 12/23) Moved -fno-stack-clash-protection back to the Makefile to fix an issue with ppc32 as per Nathan.
* Updated patch 15/21 (was 18/23) to drop the dead end cache as Josh has one in his noreturn series:
https://lore.kernel.org/9d4b8ccfed745ac47a954aa2e1de62a85197122d.1788899473.git.jpoimboe@kernel.org
* Also updated patch 15/21 (was 18/23) to hash relocation sections objtool creates itself and moved cache-to-hash copy into elf_create_reloc(), as per Josh.
* Split the instruction hash sizing out of patch 17/21 (was 19/23) into its own patch 16/21, as per Josh.
* Made the rustc parallel front end opt-in in patch 18/21 (was 20/23) via KBUILD_RUST_THREADS, as its output is not yet reproducible, and dropped the probe for the planned -j flag, as per Björn, Miguel and Nicolas.
* Tested changes to ensure any flagged issues were resolved and that nothing broke.
* Did a re-run of profiling numbers to reflect changes and updated cover letter and commit messages.
https://lore.kernel.org/r/[email protected]

v1:
https://lore.kernel.org/r/[email protected]

---
Lorenzo Stoakes (ARM) (20):
kbuild: do not allocate .modinfo in vmlinux
kallsyms: index symbols by token to speed up table compression
kallsyms: output binary data to speed output and kallsyms assembly
kbuild: do not sort nm output where the order is irrelevant
kbuild: only emit vmlinux relocations when required
elf-parse: add section flags, symbol binding and a read-only mapping
kallsyms: reimplement mksysmap in C
kbuild: cache list, composite object state per object
kbuild: implement and use depcheck to check dependency timestamps
kbuild: move the toolchain checks into init/Kconfig.toolchain
kbuild: avoid re-running compiler and linker probes
modpost: cache section relocation mismatch state
modpost: emit module descriptors as assembly
kbuild: batch module finalisation
objtool: cache relocations, do less work, eliminate relocation hash
objtool: size the instruction hash to the text
objtool: decode instructions and resolve branch targets in parallel
rust: make exports.o depend on the headers generated for it
kbuild: build rust crates in parallel with the rest of the build
kbuild: compress the kernel with pigz if available

 .gitignore                              |   1 +
 Documentation/kbuild/kbuild.rst         |  17 +
 Documentation/process/changes.rst       |   8 +
 Kbuild                                  |   5 +
 Makefile                                |  48 +-
 arch/arm64/kernel/pi/Makefile           |   2 +-
 arch/riscv/kernel/pi/Makefile           |   2 +-
 arch/x86/Kconfig                        |  17 +
 arch/x86/Makefile                       |  12 +-
 arch/x86/boot/Makefile                  |   2 +-
 arch/x86/boot/compressed/Makefile       |   2 +-
 drivers/firmware/efi/libstub/Makefile   |   2 +-
 include/asm-generic/vmlinux.lds.h       |   2 +-
 include/linux/vermagic.h                |   2 +-
 init/Kconfig                            | 197 +-------
 init/Kconfig.toolchain                  | 272 +++++++++++
 kernel/Makefile                         |   6 +-
 rust/Makefile                           |   5 +
 scripts/Makefile                        |   4 +-
 scripts/Makefile.build                  |  27 +-
 scripts/Makefile.lib                    |  11 +-
 scripts/Makefile.modfinal               |  40 +-
 scripts/Makefile.modpost                |   2 +-
 scripts/Makefile.vmlinux                |  22 +-
 scripts/Makefile.warn                   |  28 +-
 scripts/basic/.gitignore                |   1 +
 scripts/basic/Makefile                  |   2 +-
 scripts/basic/depcheck.c                | 441 ++++++++++++++++++
 scripts/check-function-names.sh         |   3 +-
 scripts/elf-parse.c                     |  48 +-
 scripts/elf-parse.h                     |  19 +
 scripts/jobserver-exec                  |   3 +-
 scripts/kallsyms-sysmap.c               | 269 +++++++++++
 scripts/kallsyms.c                      | 374 +++++++++++-----
 scripts/kallsyms.h                      |  44 ++
 scripts/link-vmlinux.sh                 |  24 +-
 scripts/mksysmap                        |  94 ----
 scripts/mod/.gitignore                  |   1 +
 scripts/mod/Makefile                    |   8 +
 scripts/mod/modpost.c                   | 703 ++++++++++++++++++++++-------
 scripts/mod/module-offsets.c            |  35 ++
 scripts/tags.sh                         |   5 +-
 tools/lib/python/jobserver.py           |  13 +
 tools/objtool/Makefile                  |   2 +-
 tools/objtool/check.c                   | 771 ++++++++++++++++++++++++--------
 tools/objtool/elf.c                     | 204 +++++++--
 tools/objtool/include/objtool/elf.h     |  10 +-
 tools/objtool/include/objtool/objtool.h |   3 +-
 tools/objtool/objtool.c                 |  15 +-
 49 files changed, 2925 insertions(+), 903 deletions(-)

---
base-commit: 238650ef6c7c7cca08e032527329424c9fbd70e5
change-id: 20260904-build-speedup-25e11a00b3d0

Best regards,

Signature · 1 line
Lorenzo Stoakes (ARM) <[email protected]>
#1 lore raw

PATCH v3 1/20 kbuild: do not allocate .modinfo in vmlinux

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") placed MODULE_INFO() strings in the .modinfo section in vmlinux.unstripped, however it left the section allocatable, so it gets assigned an address and on arm64, arm and riscv, the section is tagged as PT_LOAD.

This is useless as the data is ultimately stripped anyway.

Doing this results in a lot of unnecessary work - each pass copies the whole file, 450 MIB with relocations for an x86 allmodconfig build and 250 MiB for an arm64 allmodconfig build.

This adds ~0.7s on the serial tail of every build for arm64 and ~0.2s for x86 (the tail is single-threaded work done after parallel work has finished).

Nothing requires .modinfo to exist at an address, so fix this by using --dump-section which prevents the allocation.

Image, bzImage, System.map and modules.builtin.modinfo are unchanged and the stripped vmlinux differs only in its program headers.

The objcopy passes are on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc       11.2s    11.1s    -0.15s (-1%)
  x86 defconfig, touch mm/vma.c, clang     11.3s    11.1s    -0.19s (-2%)
  x86 defconfig, clean, gcc                32.5s    32.3s    -0.16s (-1%)
  x86 defconfig, clean, clang              34.5s    34.2s    -0.26s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    40.1s    39.7s    -0.44s (-1%)
Assisted-by LLM
---
 include/asm-generic/vmlinux.lds.h |  2 +-
 scripts/Makefile.vmlinux          | 22 ++++------------------
 2 files changed, 5 insertions(+), 19 deletions(-)
include/asm-generic/vmlinux.lds.h +1 -1
index b2988aa12f66..7be9e0321867 100644
@@ -855,7 +855,7 @@
 		KLP_SYMID
 
 #define MODINFO								\
-		.modinfo : { *(.modinfo) . = ALIGN(8); }
+		.modinfo (INFO) : { *(.modinfo) . = ALIGN(8); }
 
 #ifdef CONFIG_GENERIC_BUG
 #define BUG_TABLE							\
scripts/Makefile.vmlinux +4 -18
index fcae1e432d9a..88881826335c 100644
@@ -89,11 +89,8 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*'
 
 remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'
 
-# To avoid warnings: "empty loadable segment detected at ..." from GNU objcopy,
-# it is necessary to remove the PT_LOAD flag from the segment.
 quiet_cmd_strip_relocs = OBJCOPY $@
-      cmd_strip_relocs = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \
-                         $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@
+      cmd_strip_relocs = $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $< $@
 
 targets += vmlinux
 vmlinux: vmlinux.unstripped FORCE
@@ -102,21 +99,10 @@ vmlinux: vmlinux.unstripped FORCE
 # modules.builtin.modinfo
 # ---------------------------------------------------------------------------
 
-# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with
-# tools that expect vmlinux to have sufficiently aligned sections but the
-# additional bytes used for padding .modinfo to satisfy this requirement break
-# certain versions of kmod with
-#
-#   depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix
-#
-# Strip the trailing padding bytes after extracting .modinfo to comply with
-# what kmod expects to parse.
 quiet_cmd_modules_builtin_modinfo = GEN     $@
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    sed -i 's/\x00\+$$/\x00/g' $@; \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< [email protected]; \
+                                    rm -f [email protected]; \
+                                    sed -i 's/\x00\+$$/\x00/g' $@
 
 targets += modules.builtin.modinfo
 modules.builtin.modinfo: vmlinux.unstripped FORCE
Signature · 1 line
2.55.0
Reviewed-by on v3 1/20
#2 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 113

Quoted 9 lines · Lorenzo Stoakes (ARM)
scripts/Makefile.vmlinux +0 -9
-# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with
-# tools that expect vmlinux to have sufficiently aligned sections but the
-# additional bytes used for padding .modinfo to satisfy this requirement break
-# certain versions of kmod with
-#
-#   depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix
-#
-# Strip the trailing padding bytes after extracting .modinfo to comply with
-# what kmod expects to parse.

This comment still seems useful here (afaict the stripping is still happening with the "sed"). Maybe better to leave it, or future readers are left wondering what the sed is for?

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 105

Quoted 9 lines

quiet_cmd_modules_builtin_modinfo = GEN $@

scripts/Makefile.vmlinux +3 -5
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    sed -i 's/\x00\+$$/\x00/g' $@; \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< [email protected]; \
+                                    rm -f [email protected]; \
+                                    sed -i 's/\x00\+$$/\x00/g' $@

Otherwise, looks good. With the comment back (or rewritten):

-Kees

Signature · 1 line
Kees Cook
#3 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

Quoted 14 lines · Kees Cook

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 113

Quoted 9 lines · Lorenzo Stoakes (ARM)
scripts/Makefile.vmlinux +0 -9
-# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with
-# tools that expect vmlinux to have sufficiently aligned sections but the
-# additional bytes used for padding .modinfo to satisfy this requirement break
-# certain versions of kmod with
-#
-#   depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix
-#
-# Strip the trailing padding bytes after extracting .modinfo to comply with
-# what kmod expects to parse.

This comment still seems useful here (afaict the stripping is still happening with the "sed"). Maybe better to leave it, or future readers are left wondering what the sed is for?

Ack will restore!

Quoted 13 lines

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 105

Quoted 10 lines

quiet_cmd_modules_builtin_modinfo = GEN $@

scripts/Makefile.vmlinux +3 -5
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    sed -i 's/\x00\+$$/\x00/g' $@; \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< [email protected]; \
+                                    rm -f [email protected]; \
+                                    sed -i 's/\x00\+$$/\x00/g' $@

Otherwise, looks good. With the comment back (or rewritten):

Quoted 1 line

Thanks!

Quoted 5 lines

-Kees

--
Kees Cook

--
Cheers, Lorenzo

#4 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

In reply to Kees Cook
Quoted 14 lines · Kees Cook

Review

Quoted 9 lines · Lorenzo Stoakes (ARM)
(quoted diff) +0 -9
-# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with
-# tools that expect vmlinux to have sufficiently aligned sections but the
-# additional bytes used for padding .modinfo to satisfy this requirement break
-# certain versions of kmod with
-#
-#   depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix
-#
-# Strip the trailing padding bytes after extracting .modinfo to comply with
-# what kmod expects to parse.

This comment still seems useful here (afaict the stripping is still happening with the "sed"). Maybe better to leave it, or future readers are left wondering what the sed is for?

Thanks for bringing this up. I think we can actually get rid of that sed and comment altogether. It was added by

a26a6c93edfe ("kbuild: Strip trailing padding bytes from modules.builtin.modinfo")

to fix

d50f21091358 ("kbuild: align modinfo section for Secureboot Authenticode EDK2 compat")

but I do not think that this alignment is needed anymore since I properly fixed Dimitri's issue in

8678591b4746 ("kbuild: Split .modinfo out from ELF_DETAILS")

So I think we could go with something like

From 008046b33ef4b476048e3ddb2c679a453254e535 Mon Sep 17 00:00:00 2001
From: Nathan Chancellor <[email protected]>
Date: Thu, 17 Sep 2026 17:29:53 -0700
Subject: [PATCH] kbuild: Remove alignment on .modinfo section

Commit d50f21091358 ("kbuild: align modinfo section for Secureboot Authenticode EDK2 compat") aligned .modinfo because it appeared in the x86_64 compressed kernel image after commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped"), breaking boot.

Commit 8678591b4746 ("kbuild: Split .modinfo out from ELF_DETAILS") properly addresses .modinfo appearing in unexpected contexts like compressed images by moving it out of ELF_DETAILS and explicitly specifying its location in every architecture's vmlinux linker script or discarding it where it may appear elsewhere.

Effectively revert commit d50f21091358 ("kbuild: align modinfo section for Secureboot Authenticode EDK2 compat") and its follow up fix, commit a26a6c93edfe ("kbuild: Strip trailing padding bytes from modules.builtin.modinfo"), as they are no longer necessary in the current tree. This simplifies future cleanups.

---
 include/asm-generic/vmlinux.lds.h |  2 +-
 scripts/Makefile.vmlinux          | 10 ----------
 2 files changed, 1 insertion(+), 11 deletions(-)
include/asm-generic/vmlinux.lds.h +1 -1
index b2988aa12f66..26201821ea7f 100644
@@ -855,7 +855,7 @@
 		KLP_SYMID
 
 #define MODINFO								\
-		.modinfo : { *(.modinfo) . = ALIGN(8); }
+		.modinfo : { *(.modinfo) }
 
 #ifdef CONFIG_GENERIC_BUG
 #define BUG_TABLE							\
scripts/Makefile.vmlinux +0 -10
index fcae1e432d9a..6833b517cacb 100644
@@ -102,18 +102,8 @@ vmlinux: vmlinux.unstripped FORCE
 # modules.builtin.modinfo
 # ---------------------------------------------------------------------------
 
-# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with
-# tools that expect vmlinux to have sufficiently aligned sections but the
-# additional bytes used for padding .modinfo to satisfy this requirement break
-# certain versions of kmod with
-#
-#   depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix
-#
-# Strip the trailing padding bytes after extracting .modinfo to comply with
-# what kmod expects to parse.
 quiet_cmd_modules_builtin_modinfo = GEN     $@
       cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    sed -i 's/\x00\+$$/\x00/g' $@; \
                                     chmod -x $@
 
 OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
Signature · 1 line
Then this patch becomes much more obvious (at least to me)
include/asm-generic/vmlinux.lds.h +1 -1
index 26201821ea7f..a6730d34e8c6 100644
@@ -855,7 +855,7 @@
 		KLP_SYMID
 
 #define MODINFO								\
-		.modinfo : { *(.modinfo) }
+		.modinfo (INFO) : { *(.modinfo) }
 
 #ifdef CONFIG_GENERIC_BUG
 #define BUG_TABLE							\
scripts/Makefile.vmlinux +2 -8
index 6833b517cacb..95b523fe4f9e 100644
@@ -89,11 +89,8 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*'
 
 remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'
 
-# To avoid warnings: "empty loadable segment detected at ..." from GNU objcopy,
-# it is necessary to remove the PT_LOAD flag from the segment.
 quiet_cmd_strip_relocs = OBJCOPY $@
-      cmd_strip_relocs = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \
-                         $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@
+      cmd_strip_relocs = $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $< $@
 
 targets += vmlinux
 vmlinux: vmlinux.unstripped FORCE
@@ -103,10 +100,7 @@ vmlinux: vmlinux.unstripped FORCE
 # ---------------------------------------------------------------------------
 
 quiet_cmd_modules_builtin_modinfo = GEN     $@
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< /dev/null
 
 targets += modules.builtin.modinfo
 modules.builtin.modinfo: vmlinux.unstripped FORCE

--

Thoughts?

Signature · 2 lines
Cheers,
Nathan
#5 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

On Thu, Sep 17, 2026 at 05:51:42PM -0700, Nathan Chancellor wrote:
[...]

Quoted 25 lines

From 008046b33ef4b476048e3ddb2c679a453254e535 Mon Sep 17 00:00:00 2001
From: Nathan Chancellor <[email protected]>
Date: Thu, 17 Sep 2026 17:29:53 -0700
Subject: [PATCH] kbuild: Remove alignment on .modinfo section

Commit d50f21091358 ("kbuild: align modinfo section for Secureboot Authenticode EDK2 compat") aligned .modinfo because it appeared in the x86_64 compressed kernel image after commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped"), breaking boot.

Commit 8678591b4746 ("kbuild: Split .modinfo out from ELF_DETAILS") properly addresses .modinfo appearing in unexpected contexts like compressed images by moving it out of ELF_DETAILS and explicitly specifying its location in every architecture's vmlinux linker script or discarding it where it may appear elsewhere.

Effectively revert commit d50f21091358 ("kbuild: align modinfo section for Secureboot Authenticode EDK2 compat") and its follow up fix, commit a26a6c93edfe ("kbuild: Strip trailing padding bytes from modules.builtin.modinfo"), as they are no longer necessary in the current tree. This simplifies future cleanups.

---

[...]

Quoted 3 lines

Then this patch becomes much more obvious (at least to me)

Yes, thanks. Looks good to me and I think it's a good idea to apply that patch first.

for Nathans patch: Reviewed-by: Nicolas Schier <[email protected]>

[ Lorenzo's patch, updated by Nathan ]
[...]

Quoted 4 lines
scripts/Makefile.vmlinux +0 -0
index 6833b517cacb..95b523fe4f9e 100644

[...]

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 103

Quoted 9 lines
scripts/Makefile.vmlinux +1 -4
@@ -103,10 +100,7 @@ vmlinux: vmlinux.unstripped FORCE
 # ---------------------------------------------------------------------------
 
 quiet_cmd_modules_builtin_modinfo = GEN     $@
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< /dev/null

By shifting from "$(cmd_objcopy)" to "$(OBJCOPY) + args", $(OBJCOPYFLAGS) is dropped. It this by intention?

Kind regards,
Nicolas

#6 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

Quoted 4 lines · Nicolas Schier

Yes, thanks. Looks good to me and I think it's a good idea to apply that patch first.

for Nathans patch: Reviewed-by: Nicolas Schier <[email protected]>

Thanks, I have pushed this to kbuild-next-speedups as

36d4a11b56aa ("kbuild: Remove alignment on .modinfo section")

which Lorenzo can base on. I have also tentatively included the patches that are basically ready in my eyes based on consensus and review so far for initial build testing. I do see some comments on some of those patches though, so I will hold off on fully applying them until the next revision. If there are any other changes that we should consider taking quickly on the next revision, please feel free to point them out, it is a bit hard to follow these threads sometimes :)

[1]: https://git.kernel.org/kbuild/l/kbuild-next-speedups

Quoted 11 lines

[ Lorenzo's patch, updated by Nathan ]
[...]

Quoted 4 lines
scripts/Makefile.vmlinux +0 -0
index 6833b517cacb..95b523fe4f9e 100644

[...]

Quoted 3 lines
scripts/Makefile.vmlinux +0 -0
@@ -103,10 +100,7 @@ vmlinux: vmlinux.unstripped FORCE
 # ---------------------------------------------------------------------------
 
Quoted 9 lines

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 103

Quoted 6 lines
scripts/Makefile.vmlinux +1 -4
 quiet_cmd_modules_builtin_modinfo = GEN     $@
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< /dev/null

By shifting from "$(cmd_objcopy)" to "$(OBJCOPY) + args", $(OBJCOPYFLAGS) is dropped. It this by intention?

I am not sure it matters in this case since I don't think there are global OBJCOPYFLAGS, I only see instances that come from specific rules but I might be missing something.

Signature · 2 lines
Cheers,
Nathan
#7 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

Quoted 11 lines · Nathan Chancellor
Quoted 4 lines · Nicolas Schier

Yes, thanks. Looks good to me and I think it's a good idea to apply that patch first.

for Nathans patch: Reviewed-by: Nicolas Schier <[email protected]>

Thanks, I have pushed this to kbuild-next-speedups as

36d4a11b56aa ("kbuild: Remove alignment on .modinfo section")

which Lorenzo can base on. I have also tentatively included the patches

Ack, will rebase future revisions on this patch.

Quoted 6 lines

that are basically ready in my eyes based on consensus and review so far for initial build testing. I do see some comments on some of those patches though, so I will hold off on fully applying them until the next revision. If there are any other changes that we should consider taking quickly on the next revision, please feel free to point them out, it is a bit hard to follow these threads sometimes :)

Thanks :)

Quoted 24 lines

[1]: https://git.kernel.org/kbuild/l/kbuild-next-speedups

Quoted 11 lines

[ Lorenzo's patch, updated by Nathan ]
[...]

Quoted 4 lines
scripts/Makefile.vmlinux +0 -0
index 6833b517cacb..95b523fe4f9e 100644

[...]

Quoted 3 lines
scripts/Makefile.vmlinux +0 -0
@@ -103,10 +100,7 @@ vmlinux: vmlinux.unstripped FORCE
 # ---------------------------------------------------------------------------
 
Quoted 9 lines

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 103

Quoted 6 lines
scripts/Makefile.vmlinux +1 -4
 quiet_cmd_modules_builtin_modinfo = GEN     $@
-      cmd_modules_builtin_modinfo = $(cmd_objcopy); \
-                                    chmod -x $@
-
-OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< /dev/null

By shifting from "$(cmd_objcopy)" to "$(OBJCOPY) + args", $(OBJCOPYFLAGS) is dropped. It this by intention?

Quoted 3 lines

I am not sure it matters in this case since I don't think there are global OBJCOPYFLAGS, I only see instances that come from specific rules but I might be missing something.

OBJCOPYFLAGS is exported from the top level Makefile:

655:export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS KBUILD_LDFLAGS

And is set by various arches e.g.:

arch/csky/Makefile
2:OBJCOPYFLAGS :=-O binary

arch/mips/Makefile
348:OBJCOPYFLAGS += --remove-section=.reginfo

arch/openrisc/Makefile
20:OBJCOPYFLAGS := -O binary -R .note -R .comment -S

arch/sh/Makefile
79:OBJCOPYFLAGS := -O binary -R .note -R .note.gnu.build-id -R .comment \
-R .stab -R .stabstr -S

arch/s390/Makefile
123:OBJCOPYFLAGS := -O binary

And none of this should impact .modinfo, and if it did it'd be broken as then .modinfo would be different for one arch and not the others.

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#8 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

In reply to Lorenzo Stoakes (ARM)

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 105

Quoted 3 lines · Lorenzo Stoakes (ARM)
scripts/Makefile.vmlinux +3 -0
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< [email protected]; \
+                                    rm -f [email protected]; \
+                                    sed -i 's/\x00\+$$/\x00/g' $@

Oh, I just noticed this. I don't think the .tmp is needed. You can just use /dev/null for the outfile here: no need to write anything unused to disk; seems to work for binutils and llvm's objcopy.

Signature · 1 line
Kees Cook
#9 lore raw

Re: [PATCH v3 01/20] kbuild: do not allocate .modinfo in vmlinux

Quoted 8 lines · Kees Cook

scripts/Makefile.vmlinux vmlinux: vmlinux.unstripped FORCE · line 105

Quoted 3 lines · Lorenzo Stoakes (ARM)
scripts/Makefile.vmlinux +3 -0
+      cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< [email protected]; \
+                                    rm -f [email protected]; \
+                                    sed -i 's/\x00\+$$/\x00/g' $@

Oh, I just noticed this. I don't think the .tmp is needed. You can just use /dev/null for the outfile here: no need to write anything unused to disk; seems to work for binutils and llvm's objcopy.

Ack will fix up thanks!

Quoted 3 lines

--
Kees Cook

--
Cheers, Lorenzo

#10 lore raw

PATCH v3 2/20 kallsyms: index symbols by token to speed up table compression

In reply to Lorenzo Stoakes (ARM)

The kallsyms program compresses symbols by figuring out the most commonly used substrings in all of the input symbols then uses special character codes to represent them.

For instance, 0xf7 might end up representing "write_", then every single symbol that contains "write_" can use 0xf7 as a shorthand and save 5 bytes each time.

'Special' character codes are any byte value that is not used in any symbol, either due to being an invalid character, or not being present in any symbol (e.g. if no symbol contains 'z', then 'z' can be used as special character).

It does this by first figuring out which special characters are available in insert_real_symbols_in_table(), then iterating through every available special character, counting how many times each pair of adjacent characters appear in symbols in build_initial_token_table().

These adjacent pairs are known as 'tokens'.

Token counts are initially obtained by build_initial_token_table(), then optimize_result() calls find_best_token() to determine the token that appeared the most number of times and assigns it the next special character.

Finally, optimize_result() calls compress_symbols() to replace every token in every symbol with its special character, which updates token_profit[] as it does so.

This process is repeated for each remaining available special character, with tokens now perhaps containing previously assigned special characters (e.g. if 'wr' was assigned 0x80, then the token representing 'wri' would be '\x80i').

This compresses that token by 50% in each symbol it appears in (two bytes are now represented by one) and thus by repeatedly doing this kallsyms obtains good symbol compression.

However, compress_symbols() is seriously inefficient - it iterates through EVERY symbol for EVERY special character assignment, i.e. ~256 * nr_symbols.

Modern x86-64 kernels, for instance, have ~158,000 symbols, so millions of iterations are performed, most of which are entirely unnecessary (tokens don't appear in most symbols).

In practice kallsyms spends half its runtime doing this, two or three times per vmlinux link step.

Fix this by tracking which symbols each token appears in token_syms[], and only compress symbols which actually need to be updated.

Each time a token is compressed that token can no longer appear in any symbol, so that token_syms[] entry can be freed.

However new token_syms[] entries must be created for each new token containing the assigned special character, but this is bounded by the number of replacements in the symbol which is very small.

In testing on an x86-64 platform using clang, each kallsyms invocation dropped from 0.59s to 0.33s with CONFIG_KALLSYMS_ALL set and from 0.38s to 0.22s without it set.

The data was carefully checked and verified to be byte-for-byte identical for six symbol sets (two vmlinux passes, vmlinux.o, three userspace binaries) with all option combinations.

As part of this change, additionally refactor the code to be a little easier to follow.

kallsyms runs two or three times on the serial tail of every build that links vmlinux, no-op builds do not link and are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc       11.1s    10.6s    -0.53s (-5%)
  x86 defconfig, touch mm/vma.c, clang     11.1s    10.5s    -0.64s (-6%)
  x86 defconfig, clean, gcc                32.3s    31.3s     -1.0s (-3%)
  x86 defconfig, clean, clang              34.2s    33.3s    -0.89s (-3%)
  x86 allmodconfig, touch mm/vma.c, gcc    39.7s    38.7s     -1.0s (-3%)
  x86 allmodconfig, touch mm/vma.c, clang  40.3s    39.1s     -1.3s (-3%)
Assisted-by LLM
---
 scripts/kallsyms.c | 138 +++++++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 124 insertions(+), 14 deletions(-)
scripts/kallsyms.c +124 -14
index 494852ade6d8..350d118c3b9e 100644
@@ -58,12 +58,47 @@ static unsigned int table_size, table_cnt;
 static int all_symbols;
 static int pc_relative;
 
+/* A dynamic array of symbols, encoded by symbol index. */
+struct sym_arr {
+	unsigned int *sym_indexes;
+	unsigned int cnt, cap;
+};
+
 static int token_profit[0x10000];
+static struct sym_arr token_syms[0x10000];
 
 /* the table that holds the result of the compression */
 static unsigned char best_table[256][2];
 static unsigned char best_table_len[256];
 
+static unsigned int sym_arr_last(const struct sym_arr *arr)
+{
+	return arr->cnt ? arr->sym_indexes[arr->cnt - 1] : UINT_MAX;
+}
+
+static void sym_arr_maybe_expand(struct sym_arr *arr)
+{
+	if (arr->cap > arr->cnt)
+		return;
+
+	arr->cap = arr->cap ? arr->cap * 2 : 16;
+	arr->sym_indexes = xrealloc(arr->sym_indexes,
+				    arr->cap * sizeof(*arr->sym_indexes));
+}
+
+static void sym_arr_add(struct sym_arr *arr, unsigned int sym_idx)
+{
+	sym_arr_maybe_expand(arr);
+	arr->sym_indexes[arr->cnt++] = sym_idx;
+}
+
+static void sym_arr_free(struct sym_arr *arr)
+{
+	free(arr->sym_indexes);
+	arr->sym_indexes = NULL;
+	arr->cnt = 0;
+	arr->cap = 0;
+}
 
 static void usage(void)
 {
@@ -458,6 +493,15 @@ static void write_src(void)
 	printf("\n");
 }
 
+static unsigned int token_index(unsigned char first, unsigned char second)
+{
+	return first + (second << 8);
+}
+
+static unsigned int sym_token_index(const unsigned char *symbol, int first_idx)
+{
+	return token_index(symbol[first_idx], symbol[first_idx + 1]);
+}
 
 /* table lookup compression functions */
 
@@ -467,7 +511,7 @@ static void learn_symbol(const unsigned char *symbol, int len)
 	int i;
 
 	for (i = 0; i < len - 1; i++)
-		token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
+		token_profit[sym_token_index(symbol, i)]++;
 }
 
 /* decrease the count for all the possible tokens in a symbol */
@@ -476,16 +520,76 @@ static void forget_symbol(const unsigned char *symbol, int len)
 	int i;
 
 	for (i = 0; i < len - 1; i++)
-		token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
+		token_profit[sym_token_index(symbol, i)]--;
+}
+
+static void token_add_symbol(unsigned int token_idx, unsigned int sym_idx)
+{
+	struct sym_arr *arr = &token_syms[token_idx];
+
+	/* Symbol indexes kept in sorted order, check for duplicate. */
+	if (sym_arr_last(arr) == sym_idx)
+		return;
+
+	sym_arr_add(arr, sym_idx);
+}
+
+static void symbol_index_all_tokens(const unsigned char *symbol, int len,
+				    unsigned int sym_idx)
+{
+	int i;
+
+	for (i = 0; i < len - 1; i++) {
+		const unsigned int token_idx = sym_token_index(symbol, i);
+
+		token_add_symbol(token_idx, sym_idx);
+	}
+}
+
+/*
+ * The symbol just got compressed. The only parts of the symbol that changed
+ * meaningfully are those containing the newly assigned compressed char, so
+ * index those.
+ */
+static void symbol_index_new_tokens(const unsigned char *symbol, int len,
+				    unsigned int sym_idx, int compressed_chr)
+{
+	int i;
+
+	for (i = 0; i < len - 1; i++) {
+		const unsigned int token_idx = sym_token_index(symbol, i);
+
+		if (symbol[i] == compressed_chr ||
+		    symbol[i + 1] == compressed_chr)
+			token_add_symbol(token_idx, sym_idx);
+	}
 }
 
-/* do the initial token count */
 static void build_initial_token_table(void)
 {
 	unsigned int i;
 
 	for (i = 0; i < table_cnt; i++)
 		learn_symbol(table[i]->sym, table[i]->len);
+
+	/*
+	 * The initial occurrence counts tell us exactly how much memory should
+	 * be reserved for each token's symbol array.
+	 */
+	for (i = 0; i < ARRAY_SIZE(token_syms); i++) {
+		const int nr_syms = token_profit[i];
+
+		if (!nr_syms)
+			continue;
+
+		token_syms[i].cap = nr_syms;
+		token_syms[i].sym_indexes =
+			xmalloc(nr_syms * sizeof(unsigned int));
+	}
+
+	/* For every symbol, index every token -> symbol it is present in. */
+	for (i = 0; i < table_cnt; i++)
+		symbol_index_all_tokens(table[i]->sym, table[i]->len, i);
 }
 
 static unsigned char *find_token(unsigned char *str, int len,
@@ -502,27 +606,30 @@ static unsigned char *find_token(unsigned char *str, int len,
 
 /* replace a given token in all the valid symbols. Use the sampled symbols
  * to update the counts */
-static void compress_symbols(const unsigned char *str, int idx)
+static void compress_symbols(const unsigned char *str, int compressed_chr)
 {
-	unsigned int i, len, size;
+	const unsigned int token_idx = sym_token_index(str, 0);
+	struct sym_arr *arr = &token_syms[token_idx];
+	unsigned int sym_idx, j, len, size;
 	unsigned char *p1, *p2;
 
-	for (i = 0; i < table_cnt; i++) {
+	/* Iterate through all symbols this token is found in and compress. */
+	for (j = 0; j < arr->cnt; j++) {
+		sym_idx = arr->sym_indexes[j];
 
-		len = table[i]->len;
-		p1 = table[i]->sym;
+		len = table[sym_idx]->len;
+		p1 = table[sym_idx]->sym;
 
-		/* find the token on the symbol */
 		p2 = find_token(p1, len, str);
 		if (!p2) continue;
 
 		/* decrease the counts for this symbol's tokens */
-		forget_symbol(table[i]->sym, len);
+		forget_symbol(table[sym_idx]->sym, len);
 
 		size = len;
 
 		do {
-			*p2 = idx;
+			*p2 = compressed_chr;
 			p2++;
 			size -= (p2 - p1);
 			memmove(p2, p2 + 1, size);
@@ -536,11 +643,14 @@ static void compress_symbols(const unsigned char *str, int idx)
 
 		} while (p2);
 
-		table[i]->len = len;
+		table[sym_idx]->len = len;
 
-		/* increase the counts for this symbol's new tokens */
-		learn_symbol(table[i]->sym, len);
+		learn_symbol(table[sym_idx]->sym, len);
+		symbol_index_new_tokens(table[sym_idx]->sym, len, sym_idx,
+					compressed_chr);
 	}
+
+	sym_arr_free(arr); /* No symbol contains this token any more. */
 }
 
 /* search the token with the maximum profit */
Signature · 1 line
2.55.0
Reviewed-by on v3 2/20
#11 lore raw

Re: [PATCH v3 02/20] kallsyms: index symbols by token to speed up table compression

Quoted 6 lines · Lorenzo Stoakes (ARM)
scripts/kallsyms.c +0 -0
index 494852ade6d8..350d118c3b9e 100644
@@ -58,12 +58,47 @@ static unsigned int table_size, table_cnt;
 static int all_symbols;

scripts/kallsyms.c static unsigned int table_size, table_cnt; · line 68

Quoted 10 lines
scripts/kallsyms.c +7 -0
 static int pc_relative;
 
+/* A dynamic array of symbols, encoded by symbol index. */
+struct sym_arr {
+	unsigned int *sym_indexes;
+	unsigned int cnt, cap;
+};
+
 static int token_profit[0x10000];
+static struct sym_arr token_syms[0x10000];

Nit: since you're refactoring too, can 0x10000 be a #define so it's not open-coded 3 places? (find_best_token() uses the value too, though arguably it should actually just use ARRAY_SIZE(token_profit) instead).

Quoted 11 lines

[...]

scripts/kallsyms.c +4 -3
-static void compress_symbols(const unsigned char *str, int idx)
+static void compress_symbols(const unsigned char *str, int compressed_chr)
 {
-	unsigned int i, len, size;
+	const unsigned int token_idx = sym_token_index(str, 0);
+	struct sym_arr *arr = &token_syms[token_idx];
+	unsigned int sym_idx, j, len, size;
 	unsigned char *p1, *p2;
 
-	for (i = 0; i < table_cnt; i++) {

scripts/kallsyms.c static unsigned char *find_token(unsigned char *str, int len, · line 515

Quoted 10 lines
scripts/kallsyms.c +5 -3
+	/* Iterate through all symbols this token is found in and compress. */
+	for (j = 0; j < arr->cnt; j++) {
+		sym_idx = arr->sym_indexes[j];
 
-		len = table[i]->len;
-		p1 = table[i]->sym;
+		len = table[sym_idx]->len;
+		p1 = table[sym_idx]->sym;
 
-		/* find the token on the symbol */

Why drop this comment? It's a little redundant to "find_token", but I always question comment _removal_ when it's not solving an inaccuracy.

scripts/kallsyms.c static void compress_symbols(const unsigned char *str, int idx) · line 541

Quoted 9 lines

[...]

scripts/kallsyms.c +1 -2
@@ -536,11 +643,14 @@ static void compress_symbols(const unsigned char *str, int idx)
 
 		} while (p2);
 
-		table[i]->len = len;
+		table[sym_idx]->len = len;
 
-		/* increase the counts for this symbol's new tokens */

Same question here: the comment is still valid?

Otherwise, looks good to me.

Signature · 1 line
Kees Cook
#12 lore raw

Re: [PATCH v3 02/20] kallsyms: index symbols by token to speed up table compression

Quoted 9 lines · Kees Cook
Quoted 8 lines · Lorenzo Stoakes (ARM)
scripts/kallsyms.c +0 -0
index 494852ade6d8..350d118c3b9e 100644
@@ -58,12 +58,47 @@ static unsigned int table_size, table_cnt;
 static int all_symbols;
 static int pc_relative;
 
Quoted 12 lines

scripts/kallsyms.c static unsigned int table_size, table_cnt; · line 68

Quoted 8 lines
scripts/kallsyms.c +7 -0
+/* A dynamic array of symbols, encoded by symbol index. */
+struct sym_arr {
+	unsigned int *sym_indexes;
+	unsigned int cnt, cap;
+};
+
 static int token_profit[0x10000];
+static struct sym_arr token_syms[0x10000];

Nit: since you're refactoring too, can 0x10000 be a #define so it's not open-coded 3 places? (find_best_token() uses the value too, though arguably it should actually just use ARRAY_SIZE(token_profit) instead).

Sure, will do!

And yeah ARRAY_SIZE() makes sense there also.

Quoted 21 lines
Quoted 21 lines

[...]

scripts/kallsyms.c +9 -5
-static void compress_symbols(const unsigned char *str, int idx)
+static void compress_symbols(const unsigned char *str, int compressed_chr)
 {
-	unsigned int i, len, size;
+	const unsigned int token_idx = sym_token_index(str, 0);
+	struct sym_arr *arr = &token_syms[token_idx];
+	unsigned int sym_idx, j, len, size;
 	unsigned char *p1, *p2;
 
-	for (i = 0; i < table_cnt; i++) {
+	/* Iterate through all symbols this token is found in and compress. */
+	for (j = 0; j < arr->cnt; j++) {
+		sym_idx = arr->sym_indexes[j];
 
-		len = table[i]->len;
-		p1 = table[i]->sym;
+		len = table[sym_idx]->len;
+		p1 = table[sym_idx]->sym;
Quoted 4 lines

scripts/kallsyms.c static unsigned char *find_token(unsigned char *str, int len, · line 515

Quoted 1 line
scripts/kallsyms.c +0 -1
-		/* find the token on the symbol */

Why drop this comment? It's a little redundant to "find_token", but I always question comment _removal_ when it's not solving an inaccuracy.

Sometimes I lose track which bits are mine/the LLM's, but I don't love comments that don't add all that much, and I also berate the LLM about writing the literally worse comments I've ever seen in my life so could have been either me or it...

Anyway, will restore!

Quoted 4 lines
Quoted 4 lines

[...]

scripts/kallsyms.c +0 -0
@@ -536,11 +643,14 @@ static void compress_symbols(const unsigned char *str, int idx)
 
Quoted 8 lines

scripts/kallsyms.c static void compress_symbols(const unsigned char *str, int idx) · line 541

Quoted 6 lines
scripts/kallsyms.c +1 -2
 		} while (p2);
 
-		table[i]->len = len;
+		table[sym_idx]->len = len;
 
-		/* increase the counts for this symbol's new tokens */

Same question here: the comment is still valid?

Ack will restore!

Quoted 4 lines

Otherwise, looks good to me.

Thanks!

Quoted 4 lines

--
Kees Cook

--
Cheers, Lorenzo

#13 lore raw

PATCH v3 3/20 kallsyms: output binary data to speed output and kallsyms assembly

In reply to Lorenzo Stoakes (ARM)

kallsyms generates an assembly file that consists mostly of .byte entries containing compressed names, token strings and name-sorted sequence numbers.

For an x86-64 build with 158k symbols that is a 37 MiB .S file which takes 0.57s to assemble each of the two to three times it is built over a kernel build.

Each time it is generated it also takes kallsyms a similar amount of time to output it.

Avoid this overhead by instead outputting this data as binary and importing it into the assembly using the .incbin directive.

Tables that are wider than a byte remain part of the assembly to ensure endianness and relative relocations are performed correctly.

With this change, the output assembly file shrinks from 37 MiB to 9.8 MiB, with a 2.6 MiB binary data file alongside it, and the object remains identical.

The generated binary file is deleted correctly on build clean along with all other ephemeral data.

On an x86-64 system with CONFIG_KALLSYMS_ALL set:

                       before   after    delta
  scripts/kallsyms     0.24s    0.18s    0.06s
  assemble             0.57s    0.16s    0.41s

Per kallsyms invocation/assembly, for a total of 0.47s time saving upon invocation.

An incremental build on the same system was reduced from 11.15s to 9.65s, indicating a total of 1.5 seconds saved over the build.

The kallsyms runs and their assembly are on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc       10.6s     9.7s    -0.89s (-8%)
  x86 defconfig, touch mm/vma.c, clang     10.5s     9.3s     -1.2s (-11%)
  x86 defconfig, clean, gcc                31.3s    30.3s     -1.0s (-3%)
  x86 defconfig, clean, clang              33.3s    31.7s     -1.6s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    38.7s    37.2s     -1.4s (-4%)
  x86 allmodconfig, touch mm/vma.c, clang  39.1s    36.4s     -2.6s (-7%)
Assisted-by LLM
---
 scripts/kallsyms.c      | 84 ++++++++++++++++++++++++++++++++++++-------------
 scripts/link-vmlinux.sh |  2 +-
 2 files changed, 64 insertions(+), 22 deletions(-)
scripts/kallsyms.c +63 -21
index 350d118c3b9e..89f5207f74d2 100644
@@ -5,7 +5,10 @@
  * This software may be used and distributed according to the terms
  * of the GNU General Public License, incorporated herein by reference.
  *
- * Usage: kallsyms [--all-symbols] in.map > out.S
+ * Usage: kallsyms [--all-symbols] [--pc-relative] in.map out.bin > out.S
+ *
+ *      The byte tables go to out.bin and are pulled into out.S with .incbin;
+ *  wider tables stay assembler source for endianness and relocations.
  *
  *      Table compression uses all the unused char codes on the symbols and
  *  maps these to the most used substrings (tokens). For instance, it might
@@ -102,7 +105,7 @@ static void sym_arr_free(struct sym_arr *arr)
 
 static void usage(void)
 {
-	fprintf(stderr, "Usage: kallsyms [--all-symbols] in.map > out.S\n");
+	fprintf(stderr, "Usage: kallsyms [--all-symbols] [--pc-relative] in.map out.bin > out.S\n");
 	exit(1);
 }
 
@@ -319,6 +322,26 @@ static void output_label(const char *label)
 	printf("%s:\n", label);
 }
 
+static long bin_pos(FILE *file)
+{
+	const long pos = ftell(file);
+
+	if (pos < 0) {
+		perror("kallsyms: ftell");
+		exit(EXIT_FAILURE);
+	}
+
+	return pos;
+}
+
+static void write_incbin(const char *filename, long start, long end)
+{
+	if (start >= end)
+		return;
+
+	printf("\t.incbin \"%s\", %ld, %ld\n", filename, start, end - start);
+}
+
 /* uncompress a compressed symbol. When this function is called, the best table
  * might still be compressed itself, so the function needs to be recursive */
 static int expand_symbol(const unsigned char *data, int len, char *result)
@@ -371,11 +394,12 @@ static void sort_symbols_by_name(void)
 	qsort(table, table_cnt, sizeof(table[0]), compare_names);
 }
 
-static void write_src(void)
+static void write_src(FILE *out_bin_file, const char *out_bin_name)
 {
-	unsigned int i, k, off;
+	unsigned int i, off;
 	unsigned int best_idx[256];
 	unsigned int *markers, markers_cnt;
+	long bin_start;
 	char buf[KSYM_NAME_LEN];
 
 	printf("\t.section .rodata, \"a\"\n");
@@ -390,6 +414,7 @@ static void write_src(void)
 	markers = xmalloc(sizeof(*markers) * markers_cnt);
 
 	output_label("kallsyms_names");
+	bin_start = bin_pos(out_bin_file);
 	off = 0;
 	for (i = 0; i < table_cnt; i++) {
 		if ((i & 0xFF) == 0)
@@ -413,26 +438,24 @@ static void write_src(void)
 		/* Encode length with ULEB128. */
 		if (table[i]->len <= 0x7F) {
 			/* Most symbols use a single byte for the length. */
-			printf("\t.byte 0x%02x", table[i]->len);
+			fputc(table[i]->len, out_bin_file);
 			off += table[i]->len + 1;
 		} else {
 			/* "Big" symbols use two bytes. */
-			printf("\t.byte 0x%02x, 0x%02x",
-				(table[i]->len & 0x7F) | 0x80,
-				(table[i]->len >> 7) & 0x7F);
+			fputc((table[i]->len & 0x7F) | 0x80, out_bin_file);
+			fputc((table[i]->len >> 7) & 0x7F, out_bin_file);
 			off += table[i]->len + 2;
 		}
-		for (k = 0; k < table[i]->len; k++)
-			printf(", 0x%02x", table[i]->sym[k]);
+		fwrite(table[i]->sym, 1, table[i]->len, out_bin_file);
 
 		/*
 		 * Now that we wrote out the compressed symbol name, restore the
-		 * original name and print it in the comment.
+		 * original name for the comments below.
 		 */
 		expand_symbol(table[i]->sym, table[i]->len, buf);
 		strcpy((char *)table[i]->sym, buf);
-		printf("\t/* %s */\n", table[i]->sym);
 	}
+	write_incbin(out_bin_name, bin_start, bin_pos(out_bin_file));
 	printf(".size kallsyms_names, . - kallsyms_names\n");
 	printf("\n");
 
@@ -445,13 +468,15 @@ static void write_src(void)
 	free(markers);
 
 	output_label("kallsyms_token_table");
+	bin_start = bin_pos(out_bin_file);
 	off = 0;
 	for (i = 0; i < 256; i++) {
 		best_idx[i] = off;
 		expand_symbol(best_table[i], best_table_len[i], buf);
-		printf("\t.asciz\t\"%s\"\n", buf);
+		fwrite(buf, 1, strlen(buf) + 1, out_bin_file);
 		off += strlen(buf) + 1;
 	}
+	write_incbin(out_bin_name, bin_start, bin_pos(out_bin_file));
 	printf(".size kallsyms_token_table, . - kallsyms_token_table\n");
 	printf("\n");
 
@@ -484,12 +509,13 @@ static void write_src(void)
 
 	sort_symbols_by_name();
 	output_label("kallsyms_seqs_of_names");
-	for (i = 0; i < table_cnt; i++)
-		printf("\t.byte 0x%02x, 0x%02x, 0x%02x\t/* %s */\n",
-			(unsigned char)(table[i]->seq >> 16),
-			(unsigned char)(table[i]->seq >> 8),
-			(unsigned char)(table[i]->seq >> 0),
-		       table[i]->sym);
+	bin_start = bin_pos(out_bin_file);
+	for (i = 0; i < table_cnt; i++) {
+		fputc(table[i]->seq >> 16, out_bin_file);
+		fputc(table[i]->seq >> 8, out_bin_file);
+		fputc(table[i]->seq >> 0, out_bin_file);
+	}
+	write_incbin(out_bin_name, bin_start, bin_pos(out_bin_file));
 	printf("\n");
 }
 
@@ -798,6 +824,9 @@ static void sort_symbols(void)
 
 int main(int argc, char **argv)
 {
+	const char *out_bin_name;
+	FILE *out_bin_file;
+
 	while (1) {
 		static const struct option long_options[] = {
 			{"all-symbols",     no_argument, &all_symbols,     1},
@@ -813,14 +842,27 @@ int main(int argc, char **argv)
 			usage();
 	}
 
-	if (optind >= argc)
+	if (optind + 2 != argc)
 		usage();
 
+	out_bin_name = argv[optind + 1];
+	out_bin_file = fopen(out_bin_name, "w");
+	if (!out_bin_file) {
+		perror(out_bin_name);
+		exit(EXIT_FAILURE);
+	}
+
 	read_map(argv[optind]);
 	shrink_table();
 	sort_symbols();
 	optimize_token_table();
-	write_src();
+	write_src(out_bin_file, out_bin_name);
+
+	/* Write errors are latched in the stream, so one check at the end covers them all. */
+	if (ferror(out_bin_file) || fclose(out_bin_file)) {
+		perror(out_bin_name);
+		exit(EXIT_FAILURE);
+	}
 
 	return 0;
 }
scripts/link-vmlinux.sh +1 -1
index ab0b8125c8cb..e88604150d2c 100755
@@ -132,7 +132,7 @@ kallsyms()
 	fi
 
 	info KSYMS "${2}.S"
-	scripts/kallsyms ${kallsymopt} "${1}" > "${2}.S"
+	scripts/kallsyms ${kallsymopt} "${1}" "${2}.bin" > "${2}.S"
 
 	info AS "${2}.o"
 	${CC} ${NOSTDINC_FLAGS} ${LINUXINCLUDE} ${KBUILD_CPPFLAGS} \
Signature · 1 line
2.55.0
#15 lore raw

PATCH v3 4/20 kbuild: do not sort nm output where the order is irrelevant

In reply to Lorenzo Stoakes (ARM)

Unless instructed otherwise, nm sorts by name.

There are places where this is unnecessary - an invocation from scripts/sorttable every vmlinux link, scripts/check-function-names.sh run after every vmlinux.o link, and the x86 VOFFSET and ZOFFSET listings between vmlinux and bzImage.

Both GNU nm and llvm-nm accept the same '-p' parameter to disable sorting in these instances, so use that to prevent this unnecessary work.

Each nm run on its own, x86-64, median of 5:

GNU nm 2.47 llvm-nm 22
before after delta before after delta
defconfig

  sorttable, nm -S vmlinux 0.080s 0.039s -0.041s   0.265s 0.113s -0.152s
  check-function-names.sh  0.072s 0.033s -0.039s   0.244s 0.102s -0.142s
  VOFFSET                  0.077s 0.034s -0.043s   0.261s 0.113s -0.148s
  ZOFFSET                  0.007s 0.005s -0.002s   0.005s 0.005s  0.000s

TOTAL -0.125s -0.442s

allmodconfig

  sorttable, nm -S vmlinux 0.156s 0.063s -0.093s   0.539s 0.223s -0.316s
  check-function-names.sh  0.149s 0.054s -0.095s   0.537s 0.217s -0.320s
  VOFFSET                  0.146s 0.052s -0.094s   0.524s 0.221s -0.303s
  ZOFFSET                  0.007s 0.005s -0.002s   0.006s 0.004s -0.002s

TOTAL -0.284s -0.941s

llvm-nm appears to be a lot slower than GNU nm, so these builds naturally improve the most.

The four run one after another in the serial tail of every build that links vmlinux so impact kernel builds directly.

In an allmodconfig the decompressor is built in parallel while the modules, so only the two before the vmlinux link contribute to build time.

The build outputs remain unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
---------------------------------

  x86 defconfig, touch mm/vma.c, gcc        9.7s     9.5s    -0.18s (-2%)
  x86 defconfig, touch mm/vma.c, clang      9.3s     9.0s    -0.27s (-3%)
  x86 defconfig, clean, gcc                30.3s    30.1s    -0.16s (-1%)
  x86 defconfig, clean, clang              31.7s    31.2s    -0.55s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  36.4s    35.8s    -0.67s (-2%)
Assisted-by LLM
---
 arch/x86/boot/Makefile            | 2 +-
 arch/x86/boot/compressed/Makefile | 2 +-
 scripts/check-function-names.sh   | 3 ++-
 scripts/link-vmlinux.sh           | 2 +-
 4 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/boot/Makefile +1 -1
index 3f9fb3698d66..4a9bce32586d 100644
@@ -74,7 +74,7 @@ SETUP_OBJS = $(addprefix $(obj)/,$(setup-y))
 sed-zoffset := -e 's/^\([0-9a-fA-F]*\) [a-zA-Z] \(startup_32\|efi.._stub_entry\|efi\(32\)\?_pe_entry\|input_data\|kernel_info\|_end\|_ehead\|_text\|_e\?data\|_e\?sbat\|z_.*\)$$/\#define ZO_\2 0x\1/p'
 
 quiet_cmd_zoffset = ZOFFSET $@
-      cmd_zoffset = $(NM) $< | sed -n $(sed-zoffset) > $@
+      cmd_zoffset = $(NM) -p $< | sed -n $(sed-zoffset) > $@
 
 targets += zoffset.h
 $(obj)/zoffset.h: $(obj)/compressed/vmlinux FORCE
arch/x86/boot/compressed/Makefile +1 -1
index 06934f9691d6..6ec5e031db1d 100644
@@ -76,7 +76,7 @@ HOST_EXTRACFLAGS += -I$(srctree)/tools/include
 sed-voffset := -e 's/^\([0-9a-fA-F]*\) [ABbCDGRSTtVW] \(_text\|__start_rodata\|_sinittext\|__inittext_end\|__bss_start\|_end\)$$/\#define VO_\2 _AC(0x\1,UL)/p'
 
 quiet_cmd_voffset = VOFFSET $@
-      cmd_voffset = $(NM) $< | sed -n $(sed-voffset) > $@
+      cmd_voffset = $(NM) -p $< | sed -n $(sed-voffset) > $@
 
 targets += ../voffset.h
 
scripts/check-function-names.sh +2 -1
index 08071133e5a5..94883e690627 100755
@@ -13,7 +13,8 @@ if [ ! -f "$objfile" ]; then
 	exit 1
 fi
 
-bad_symbols=$(${NM:-nm} "$objfile" | awk '$2 ~ /^[TtWw]$/ {print $3}' | grep -E '^(startup|exit|split|unlikely|hot|unknown)(\.|$)')
+bad_symbols=$(${NM:-nm} -p "$objfile" | awk '$2 ~ /^[TtWw]$/ {print $3}' |
+	      grep -E '^(startup|exit|split|unlikely|hot|unknown)(\.|$)')
 
 if [ -n "$bad_symbols" ]; then
 	echo "$bad_symbols" | while read -r sym; do
scripts/link-vmlinux.sh +1 -1
index e88604150d2c..970ca10f8fa9 100755
@@ -161,7 +161,7 @@ mksysmap()
 
 sorttable()
 {
-	${NM} -S ${1} > .tmp_vmlinux.nm-sort
+	${NM} -p -S ${1} > .tmp_vmlinux.nm-sort
 	${objtree}/scripts/sorttable -s .tmp_vmlinux.nm-sort ${1}
 }
 
Signature · 1 line
2.55.0
Reviewed-by on v3 4/20
#16 lore raw

Re: [PATCH v3 04/20] kbuild: do not sort nm output where the order is irrelevant

Quoted 7 lines · Lorenzo Stoakes (ARM)

There are places where this is unnecessary - an invocation from scripts/sorttable every vmlinux link, scripts/check-function-names.sh run after every vmlinux.o link, and the x86 VOFFSET and ZOFFSET listings between vmlinux and bzImage.
[...]
before after delta
---------------------------------

Quoted 8 lines
  x86 defconfig, touch mm/vma.c, gcc        9.7s     9.5s    -0.18s (-2%)
  x86 defconfig, touch mm/vma.c, clang      9.3s     9.0s    -0.27s (-3%)
  x86 defconfig, clean, gcc                30.3s    30.1s    -0.16s (-1%)
  x86 defconfig, clean, clang              31.7s    31.2s    -0.55s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  36.4s    35.8s    -0.67s (-2%)
Assisted-by LLM

Not a huge boost, but it's a trivial change with a deterministic improvement.

Signature · 1 line
Kees Cook
Reviewed-by on v3 4/20
#17 lore raw

Re: [PATCH v3 04/20] kbuild: do not sort nm output where the order is irrelevant

In reply to Lorenzo Stoakes (ARM)
Quoted 49 lines · Lorenzo Stoakes (ARM)

Unless instructed otherwise, nm sorts by name.

There are places where this is unnecessary - an invocation from scripts/sorttable every vmlinux link, scripts/check-function-names.sh run after every vmlinux.o link, and the x86 VOFFSET and ZOFFSET listings between vmlinux and bzImage.

Both GNU nm and llvm-nm accept the same '-p' parameter to disable sorting in these instances, so use that to prevent this unnecessary work.

Each nm run on its own, x86-64, median of 5:

GNU nm 2.47 llvm-nm 22
before after delta before after delta
defconfig

  sorttable, nm -S vmlinux 0.080s 0.039s -0.041s   0.265s 0.113s -0.152s
  check-function-names.sh  0.072s 0.033s -0.039s   0.244s 0.102s -0.142s
  VOFFSET                  0.077s 0.034s -0.043s   0.261s 0.113s -0.148s
  ZOFFSET                  0.007s 0.005s -0.002s   0.005s 0.005s  0.000s

TOTAL -0.125s -0.442s

allmodconfig

  sorttable, nm -S vmlinux 0.156s 0.063s -0.093s   0.539s 0.223s -0.316s
  check-function-names.sh  0.149s 0.054s -0.095s   0.537s 0.217s -0.320s
  VOFFSET                  0.146s 0.052s -0.094s   0.524s 0.221s -0.303s
  ZOFFSET                  0.007s 0.005s -0.002s   0.006s 0.004s -0.002s

TOTAL -0.284s -0.941s

llvm-nm appears to be a lot slower than GNU nm, so these builds naturally improve the most.

The four run one after another in the serial tail of every build that links vmlinux so impact kernel builds directly.

In an allmodconfig the decompressor is built in parallel while the modules, so only the two before the vmlinux link contribute to build time.

The build outputs remain unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
---------------------------------

  x86 defconfig, touch mm/vma.c, gcc        9.7s     9.5s    -0.18s (-2%)
  x86 defconfig, touch mm/vma.c, clang      9.3s     9.0s    -0.27s (-3%)
  x86 defconfig, clean, gcc                30.3s    30.1s    -0.16s (-1%)
  x86 defconfig, clean, clang              31.7s    31.2s    -0.55s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  36.4s    35.8s    -0.67s (-2%)
Quoted 9 lines
Assisted-by LLM
---
 arch/x86/boot/Makefile            | 2 +-
 arch/x86/boot/compressed/Makefile | 2 +-
 scripts/check-function-names.sh   | 3 ++-
 scripts/link-vmlinux.sh           | 2 +-
 4 files changed, 5 insertions(+), 4 deletions(-)

Thanks!

Signature · 1 line
Nicolas
#18 lore raw

PATCH v3 5/20 kbuild: only emit vmlinux relocations when required

In reply to Lorenzo Stoakes (ARM)

A kernel build consists of more than one linking pass on vmlinux.o and vmlinux, at minimum two, and with CONFIG_KALLSYMS and BTF enabled on x86-64 for example there are 5 such stages.

For architectures that build their own relocation tables (x86, riscv, mips, s390), vmlinux is linked with the --emit-relocs parameter specified.

However, this is only required on the final vmlinux link.

Symbol tables of trial links preceding it don't need it because they already check that System.map matches kallsyms symbols on each build.

GNU ld is slow at emitting relocation tables, so this results in a reduction in build time.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------
x86 defconfig, touch mm/vma.c, gcc 9.5s 9.1s -0.42s (-4%)

  x86 defconfig, clean, gcc                30.1s    29.5s    -0.59s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    37.2s    35.8s     -1.4s (-4%)

Note that this has little impact on LLVM ld which performs this operation more efficiently.

Assisted-by LLM
---
 Makefile                | 2 +-
 scripts/link-vmlinux.sh | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)
Makefile +1 -1
index 0f1b80100b47..dd4c10afbb7f 100644
@@ -1263,7 +1263,7 @@ LDFLAGS_vmlinux += --orphan-handling=$(CONFIG_LD_ORPHAN_WARN_LEVEL)
 endif
 
 ifneq ($(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS),)
-LDFLAGS_vmlinux	+= --emit-relocs --discard-none
+LDFLAGS_vmlinux	+= --discard-none
 endif
 
 # Align the architecture of userspace programs with the kernel
scripts/link-vmlinux.sh +5 -0
index 970ca10f8fa9..ed5ff97c0667 100755
@@ -96,6 +96,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && is_enabled CONFIG_ARCH_VMLINUX_NEEDS_RELOCS; then
+		ldflags="${ldflags} ${wl}--emit-relocs"
+	fi
+
 	if [ -n "${generate_map}" ];  then
 		ldflags="${ldflags} ${wl}-Map=vmlinux.map"
 	fi
Signature · 1 line
2.55.0
Reviewed-by on v3 5/20
#19 lore raw

Re: [PATCH v3 05/20] kbuild: only emit vmlinux relocations when required

Quoted 38 lines · Lorenzo Stoakes (ARM)

A kernel build consists of more than one linking pass on vmlinux.o and vmlinux, at minimum two, and with CONFIG_KALLSYMS and BTF enabled on x86-64 for example there are 5 such stages.

For architectures that build their own relocation tables (x86, riscv, mips, s390), vmlinux is linked with the --emit-relocs parameter specified.

However, this is only required on the final vmlinux link.

Symbol tables of trial links preceding it don't need it because they already check that System.map matches kallsyms symbols on each build.

GNU ld is slow at emitting relocation tables, so this results in a reduction in build time.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------
x86 defconfig, touch mm/vma.c, gcc 9.5s 9.1s -0.42s (-4%)

  x86 defconfig, clean, gcc                30.1s    29.5s    -0.59s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    37.2s    35.8s     -1.4s (-4%)

Note that this has little impact on LLVM ld which performs this operation more efficiently.

Assisted-by LLM
---
 Makefile                | 2 +-
 scripts/link-vmlinux.sh | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)
Makefile +0 -0
index 0f1b80100b47..dd4c10afbb7f 100644

Makefile LDFLAGS_vmlinux += --orphan-handling=$(CONFIG_LD_ORPHAN_WARN_LEVEL) · line 1267

Quoted 6 lines
Makefile +1 -1
@@ -1263,7 +1263,7 @@ LDFLAGS_vmlinux += --orphan-handling=$(CONFIG_LD_ORPHAN_WARN_LEVEL)
 endif
 
 ifneq ($(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS),)
-LDFLAGS_vmlinux	+= --emit-relocs --discard-none
+LDFLAGS_vmlinux	+= --discard-none
 endif

Nit: I think a comment here is worth adding, like in link-vmlinux.sh. They're separate files, and it's kind of weird that ...NEEDS_RELOCS doesn't actually add --emit-relocs here unless you go find how --emit-relocs is used later.

Quoted 8 lines
Makefile +0 -0
 # Align the architecture of userspace programs with the kernel
scripts/link-vmlinux.sh +0 -0
index 970ca10f8fa9..ed5ff97c0667 100755
@@ -96,6 +96,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"

scripts/link-vmlinux.sh vmlinux_link() · line 106

Quoted 10 lines
scripts/link-vmlinux.sh +5 -0
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && is_enabled CONFIG_ARCH_VMLINUX_NEEDS_RELOCS; then
+		ldflags="${ldflags} ${wl}--emit-relocs"
+	fi
+
 	if [ -n "${generate_map}" ];  then
 		ldflags="${ldflags} ${wl}-Map=vmlinux.map"
 	fi

But yeah, otherwise, another "don't generate something that doesn't get used" improvement. :)

Signature · 1 line
Kees Cook
#20 lore raw

Re: [PATCH v3 05/20] kbuild: only emit vmlinux relocations when required

Quoted 41 lines · Kees Cook
Quoted 40 lines · Lorenzo Stoakes (ARM)

A kernel build consists of more than one linking pass on vmlinux.o and vmlinux, at minimum two, and with CONFIG_KALLSYMS and BTF enabled on x86-64 for example there are 5 such stages.

For architectures that build their own relocation tables (x86, riscv, mips, s390), vmlinux is linked with the --emit-relocs parameter specified.

However, this is only required on the final vmlinux link.

Symbol tables of trial links preceding it don't need it because they already check that System.map matches kallsyms symbols on each build.

GNU ld is slow at emitting relocation tables, so this results in a reduction in build time.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------
x86 defconfig, touch mm/vma.c, gcc 9.5s 9.1s -0.42s (-4%)

  x86 defconfig, clean, gcc                30.1s    29.5s    -0.59s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    37.2s    35.8s     -1.4s (-4%)

Note that this has little impact on LLVM ld which performs this operation more efficiently.

Assisted-by LLM
---
 Makefile                | 2 +-
 scripts/link-vmlinux.sh | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)
Makefile +0 -0
index 0f1b80100b47..dd4c10afbb7f 100644
@@ -1263,7 +1263,7 @@ LDFLAGS_vmlinux += --orphan-handling=$(CONFIG_LD_ORPHAN_WARN_LEVEL)
 endif
 
Quoted 9 lines

Makefile LDFLAGS_vmlinux += --orphan-handling=$(CONFIG_LD_ORPHAN_WARN_LEVEL) · line 1267

Quoted 4 lines
Makefile +1 -1
 ifneq ($(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS),)
-LDFLAGS_vmlinux	+= --emit-relocs --discard-none
+LDFLAGS_vmlinux	+= --discard-none
 endif

Nit: I think a comment here is worth adding, like in link-vmlinux.sh. They're separate files, and it's kind of weird that ...NEEDS_RELOCS doesn't actually add --emit-relocs here unless you go find how --emit-relocs is used later.

Ack will add!

Quoted 11 lines
Quoted 11 lines
Makefile +0 -0
 # Align the architecture of userspace programs with the kernel
scripts/link-vmlinux.sh +0 -0
index 970ca10f8fa9..ed5ff97c0667 100755
@@ -96,6 +96,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
Quoted 11 lines

scripts/link-vmlinux.sh vmlinux_link() · line 106

Quoted 8 lines
scripts/link-vmlinux.sh +5 -0
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && is_enabled CONFIG_ARCH_VMLINUX_NEEDS_RELOCS; then
+		ldflags="${ldflags} ${wl}--emit-relocs"
+	fi
+
 	if [ -n "${generate_map}" ];  then
 		ldflags="${ldflags} ${wl}-Map=vmlinux.map"
 	fi

But yeah, otherwise, another "don't generate something that doesn't get used" improvement. :)

Yes :) it's funny how simple a lot of these changes are

- Don't do work you don't need to
- Cache stuff so you don't have to look it up again (a variant on the first one)
- Do other work at the same time

Quoted 2 lines

Thanks!

Quoted 3 lines

--
Kees Cook

--
Cheers, Lorenzo

Reviewed-by on v3 5/20
#21 lore raw

Re: [PATCH v3 05/20] kbuild: only emit vmlinux relocations when required

In reply to Lorenzo Stoakes (ARM)
Quoted 26 lines · Lorenzo Stoakes (ARM)

A kernel build consists of more than one linking pass on vmlinux.o and vmlinux, at minimum two, and with CONFIG_KALLSYMS and BTF enabled on x86-64 for example there are 5 such stages.

For architectures that build their own relocation tables (x86, riscv, mips, s390), vmlinux is linked with the --emit-relocs parameter specified.

However, this is only required on the final vmlinux link.

Symbol tables of trial links preceding it don't need it because they already check that System.map matches kallsyms symbols on each build.

GNU ld is slow at emitting relocation tables, so this results in a reduction in build time.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------
x86 defconfig, touch mm/vma.c, gcc 9.5s 9.1s -0.42s (-4%)

  x86 defconfig, clean, gcc                30.1s    29.5s    -0.59s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    37.2s    35.8s     -1.4s (-4%)

Note that this has little impact on LLVM ld which performs this operation more efficiently.

Quoted 7 lines
Assisted-by LLM
---
 Makefile                | 2 +-
 scripts/link-vmlinux.sh | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)

}

Signature · 1 line
Nicolas
#22 lore raw

PATCH v3 6/20 elf-parse: add section flags, symbol binding and a read-only mapping

In reply to Lorenzo Stoakes (ARM)

Extend elf-parse to be able to read the symbol table of vmlinux in kallsyms.

This requires the ability to open ELF files in read-only mode, so provide elf_map_ro() to do so.

It also requires accessors for section flags and symbol bindings, so provide these via shdr_flags() and sym_bind().

Also, check for the file being an ELF file first in elf_parse(). This is the logical thing to check for first, but additionally prevents kallsyms from having to check this it self.

Assisted-by LLM
---
 scripts/elf-parse.c | 48 +++++++++++++++++++++++++++++++++++-------------
 scripts/elf-parse.h | 19 +++++++++++++++++++
 2 files changed, 54 insertions(+), 13 deletions(-)
scripts/elf-parse.c +35 -13
index 99869ff91a8c..87aa95b1e5e1 100644
@@ -17,15 +17,21 @@ struct elf_funcs elf_parser;
  * Get the whole file as a programming convenience in order to avoid
  * malloc+lseek+read+free of many pieces.  If successful, then mmap
  * avoids copying unused pieces; else just read the whole file.
- * Open for both read and write.
+ * Open for both read and write if writable is true, otherwise open
+ * read-only.
  */
-static void *map_file(char const *fname, size_t *size)
+static void *map_file(char const *fname, size_t *size, bool writable)
 {
-	int fd;
+	int fd, prot = PROT_READ, flags = MAP_PRIVATE;
 	struct stat sb;
 	void *addr = NULL;
 
-	fd = open(fname, O_RDWR);
+	if (writable) {
+		prot |= PROT_WRITE;
+		flags = MAP_SHARED;
+	}
+
+	fd = open(fname, writable ? O_RDWR : O_RDONLY);
 	if (fd < 0) {
 		perror(fname);
 		return NULL;
@@ -39,7 +45,7 @@ static void *map_file(char const *fname, size_t *size)
 		goto out;
 	}
 
-	addr = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+	addr = mmap(0, sb.st_size, prot, flags, fd, 0);
 	if (addr == MAP_FAILED) {
 		fprintf(stderr, "Could not mmap file: %s\n", fname);
 		goto out;
@@ -57,6 +63,12 @@ static int elf_parse(const char *fname, void *addr, uint32_t types)
 	Elf_Ehdr *ehdr = addr;
 	uint16_t type;
 
+	if (memcmp(ELFMAG, ehdr->e32.e_ident, SELFMAG) != 0 ||
+	    ehdr->e32.e_ident[EI_VERSION] != EV_CURRENT) {
+		fprintf(stderr, "unrecognized ELF file %s\n", fname);
+		return -1;
+	}
+
 	switch (ehdr->e32.e_ident[EI_DATA]) {
 	case ELFDATA2LSB:
 		elf_parser.r	= rle;
@@ -78,12 +90,6 @@ static int elf_parse(const char *fname, void *addr, uint32_t types)
 		return -1;
 	}
 
-	if (memcmp(ELFMAG, ehdr->e32.e_ident, SELFMAG) != 0 ||
-	    ehdr->e32.e_ident[EI_VERSION] != EV_CURRENT) {
-		fprintf(stderr, "unrecognized ELF file %s\n", fname);
-		return -1;
-	}
-
 	type = elf_parser.r2(&ehdr->e32.e_type);
 	if (!((1 << type) & types)) {
 		fprintf(stderr, "Invalid ELF type file %s\n", fname);
@@ -103,7 +109,9 @@ static int elf_parse(const char *fname, void *addr, uint32_t types)
 		elf_parser.shdr_name		= shdr32_name;
 		elf_parser.shdr_type		= shdr32_type;
 		elf_parser.shdr_entsize		= shdr32_entsize;
+		elf_parser.shdr_flags		= shdr32_flags;
 		elf_parser.sym_type		= sym32_type;
+		elf_parser.sym_bind		= sym32_bind;
 		elf_parser.sym_name		= sym32_name;
 		elf_parser.sym_value		= sym32_value;
 		elf_parser.sym_shndx		= sym32_shndx;
@@ -133,7 +141,9 @@ static int elf_parse(const char *fname, void *addr, uint32_t types)
 		elf_parser.shdr_name		= shdr64_name;
 		elf_parser.shdr_type		= shdr64_type;
 		elf_parser.shdr_entsize		= shdr64_entsize;
+		elf_parser.shdr_flags		= shdr64_flags;
 		elf_parser.sym_type		= sym64_type;
+		elf_parser.sym_bind		= sym64_bind;
 		elf_parser.sym_name		= sym64_name;
 		elf_parser.sym_value		= sym64_value;
 		elf_parser.sym_shndx		= sym64_shndx;
@@ -174,12 +184,13 @@ int elf_map_long_size(void *addr)
 	return ehdr->e32.e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
 }
 
-void *elf_map(char const *fname, size_t *size, uint32_t types)
+static void *__elf_map(char const *fname, size_t *size, uint32_t types,
+		       bool writable)
 {
 	void *addr;
 	int ret;
 
-	addr = map_file(fname, size);
+	addr = map_file(fname, size, writable);
 	if (!addr)
 		return NULL;
 
@@ -192,6 +203,17 @@ void *elf_map(char const *fname, size_t *size, uint32_t types)
 	return addr;
 }
 
+void *elf_map(char const *fname, size_t *size, uint32_t types)
+{
+	return __elf_map(fname, size, types, true);
+}
+
+/* For tools that only read the file. */
+void *elf_map_ro(char const *fname, size_t *size, uint32_t types)
+{
+	return __elf_map(fname, size, types, false);
+}
+
 void elf_unmap(void *addr, size_t size)
 {
 	munmap(addr, size);
scripts/elf-parse.h +19 -0
index f4411e03069d..453286e63032 100644
@@ -37,10 +37,12 @@ struct elf_funcs {
 	uint64_t (*shdr_offset)(Elf_Shdr *shdr);
 	uint64_t (*shdr_size)(Elf_Shdr *shdr);
 	uint64_t (*shdr_entsize)(Elf_Shdr *shdr);
+	uint64_t (*shdr_flags)(Elf_Shdr *shdr);
 	uint32_t (*shdr_link)(Elf_Shdr *shdr);
 	uint32_t (*shdr_name)(Elf_Shdr *shdr);
 	uint32_t (*shdr_type)(Elf_Shdr *shdr);
 	uint8_t (*sym_type)(Elf_Sym *sym);
+	uint8_t (*sym_bind)(Elf_Sym *sym);
 	uint32_t (*sym_name)(Elf_Sym *sym);
 	uint64_t (*sym_value)(Elf_Sym *sym);
 	uint16_t (*sym_shndx)(Elf_Sym *sym);
@@ -143,6 +145,7 @@ SHDR_ADDR(addr)
 SHDR_ADDR(offset)
 SHDR_ADDR(size)
 SHDR_ADDR(entsize)
+SHDR_ADDR(flags)
 
 SHDR_WORD(link)
 SHDR_WORD(name)
@@ -211,6 +214,21 @@ static inline uint8_t sym_type(Elf_Sym *sym)
 	return elf_parser.sym_type(sym);
 }
 
+static inline uint8_t sym64_bind(Elf_Sym *sym)
+{
+	return ELF64_ST_BIND(sym->e64.st_info);
+}
+
+static inline uint8_t sym32_bind(Elf_Sym *sym)
+{
+	return ELF32_ST_BIND(sym->e32.st_info);
+}
+
+static inline uint8_t sym_bind(Elf_Sym *sym)
+{
+	return elf_parser.sym_bind(sym);
+}
+
 SYM_ADDR(value)
 SYM_WORD(name)
 SYM_HALF(shndx)
@@ -298,6 +316,7 @@ static inline void w8le(uint64_t val, uint64_t *x)
 }
 
 void *elf_map(char const *fname, size_t *size, uint32_t types);
+void *elf_map_ro(char const *fname, size_t *size, uint32_t types);
 void elf_unmap(void *addr, size_t size);
 int elf_map_machine(void *addr);
 int elf_map_long_size(void *addr);
Signature · 1 line
2.55.0
#24 lore raw

PATCH v3 7/20 kallsyms: reimplement mksysmap in C

In reply to Lorenzo Stoakes (ARM)

mksysmap is a sed script consisting of 30 patterns which link-vmlinux.sh uses to generate *.syms files, and which kallsyms is then called against to generate *.kallsyms files, with the final vmlinux build ultimately generating System.map.

For an x86-64 allmodconfig build, this involves three nm runs over a 250 MiB file and half a million lines written and read each time - 0.5s per pass for llvm-nm, and 0.2s for GNU nm, with parsing on top of that.

This is unnecessary, instead have kallsyms simply read the ELF file directly making use of the existing elf-parse library in scripts/.

This changes kallsyms such that its input is no longer the output from nm, but rather an ELF file.

However, if the input file is empty, it outputs an empty table, which retains the same behaviour on first pass that the build system expects.

System.map is byte-identical to nm | mksysmap for GNU nm and llvm-nm on two x86 configurations each, and for llvm-nm on arm64, arm, s390 and loongarch defconfigs, so are the kallsyms tables of every pass.

Relinking vmlinux, link steps included:

                        before    after
  allmodconfig clang     9.1s     7.9s
  allmodconfig gcc       7.8s     7.6s
  defconfig clang        3.7s     3.0s
  defconfig gcc          3.5s     3.4s

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        9.1s     8.6s    -0.43s (-5%)
  x86 defconfig, touch mm/vma.c, clang      9.0s     8.0s     -1.1s (-12%)
  x86 defconfig, clean, gcc                29.5s    28.9s    -0.64s (-2%)
  x86 defconfig, clean, clang              31.2s    29.8s     -1.4s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    35.8s    35.0s    -0.77s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  35.8s    33.7s     -2.0s (-6%)
Assisted-by LLM
---
 scripts/Makefile          |   4 +-
 scripts/kallsyms-sysmap.c | 269 ++++++++++++++++++++++++++++++++++++++++++++++
 scripts/kallsyms.c        | 162 ++++++++++++++++------------
 scripts/kallsyms.h        |  44 ++++++++
 scripts/link-vmlinux.sh   |  15 +--
 scripts/mksysmap          |  94 ----------------
 6 files changed, 415 insertions(+), 173 deletions(-)
scripts/Makefile +3 -1
index 3434a82a119f..d46932113b5f 100644
@@ -3,7 +3,7 @@
 # scripts contains sources for various helper programs used throughout
 # the kernel for the build process.
 
-hostprogs-always-$(CONFIG_KALLSYMS)			+= kallsyms
+hostprogs-always-y				+= kallsyms
 hostprogs-always-$(BUILD_C_RECORDMCOUNT)		+= recordmcount
 hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT)		+= sorttable
 hostprogs-always-$(CONFIG_ASN1)				+= asn1_compiler
@@ -13,6 +13,7 @@ hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_builder
 hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_gen
 hostprogs-always-$(CONFIG_TRACEPOINTS)			+= tracepoint-update
 
+kallsyms-objs := kallsyms.o kallsyms-sysmap.o elf-parse.o
 sorttable-objs := sorttable.o elf-parse.o
 tracepoint-update-objs := tracepoint-update.o elf-parse.o
 
@@ -30,6 +31,7 @@ rustdoc_test_builder-rust := y
 rustdoc_test_gen-rust := y
 
 HOSTCFLAGS_tracepoint-update.o = -I$(srctree)/tools/include
+HOSTCFLAGS_kallsyms-sysmap.o = -I$(srctree)/tools/include
 HOSTCFLAGS_elf-parse.o = -I$(srctree)/tools/include
 HOSTCFLAGS_sorttable.o = -I$(srctree)/tools/include
 HOSTLDLIBS_sorttable = -lpthread
scripts/kallsyms-sysmap.c new file +269 -0

269 lines not on this page · raw message

scripts/kallsyms.c +91 -71

275 lines not on this page · raw message

scripts/kallsyms.h new file +44 -0

44 lines not on this page · raw message

scripts/link-vmlinux.sh +8 -7
index ed5ff97c0667..c520741f85c2 100755
@@ -123,11 +123,15 @@ kallsymso_changed()
 	! cmp -s "${kallsymso_prev}.sym" "${kallsymso}.sym"
 }
 
-# Create ${2}.o file with all symbols from the ${1} object file
+# Create ${2}.o with the kallsyms tables for ${1} (the vmlinux, or an empty
+# listing for the first pass); list the symbols used in ${3} if given.
 kallsyms()
 {
 	local kallsymopt;
 
+	if [ -n "${3:-}" ]; then
+		kallsymopt="--sysmap=${3}"
+	fi
 	if is_enabled CONFIG_KALLSYMS_ALL; then
 		kallsymopt="${kallsymopt} --all-symbols"
 	fi
@@ -150,18 +154,15 @@ kallsyms()
 # Perform kallsyms for the given temporary vmlinux.
 sysmap_and_kallsyms()
 {
-	mksysmap "${1}" "${1}.syms"
-	kallsyms "${1}.syms" "${1}.kallsyms"
-
+	kallsyms "${1}" "${1}.kallsyms" "${1}.syms"
 	kallsyms_sysmap=${1}.syms
 }
 
 # Create map file with all symbols from ${1}
-# See mksymap for additional details
 mksysmap()
 {
-	info NM ${2}
-	${NM} -n "${1}" | sed -f "${srctree}/scripts/mksysmap" > "${2}"
+	info SYSMAP ${2}
+	scripts/kallsyms --sysmap="${2}" "${1}"
 }
 
 sorttable()
scripts/mksysmap deleted +0 -94

94 lines not on this page · raw message

Signature · 1 line
2.55.0
#25 lore raw

Re: [PATCH v3 07/20] kallsyms: reimplement mksysmap in C

Quoted 112 lines · Lorenzo Stoakes (ARM)

mksysmap is a sed script consisting of 30 patterns which link-vmlinux.sh uses to generate *.syms files, and which kallsyms is then called against to generate *.kallsyms files, with the final vmlinux build ultimately generating System.map.

For an x86-64 allmodconfig build, this involves three nm runs over a 250 MiB file and half a million lines written and read each time - 0.5s per pass for llvm-nm, and 0.2s for GNU nm, with parsing on top of that.

This is unnecessary, instead have kallsyms simply read the ELF file directly making use of the existing elf-parse library in scripts/.

This changes kallsyms such that its input is no longer the output from nm, but rather an ELF file.

However, if the input file is empty, it outputs an empty table, which retains the same behaviour on first pass that the build system expects.

System.map is byte-identical to nm | mksysmap for GNU nm and llvm-nm on two x86 configurations each, and for llvm-nm on arm64, arm, s390 and loongarch defconfigs, so are the kallsyms tables of every pass.

Relinking vmlinux, link steps included:

                        before    after
  allmodconfig clang     9.1s     7.9s
  allmodconfig gcc       7.8s     7.6s
  defconfig clang        3.7s     3.0s
  defconfig gcc          3.5s     3.4s

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        9.1s     8.6s    -0.43s (-5%)
  x86 defconfig, touch mm/vma.c, clang      9.0s     8.0s     -1.1s (-12%)
  x86 defconfig, clean, gcc                29.5s    28.9s    -0.64s (-2%)
  x86 defconfig, clean, clang              31.2s    29.8s     -1.4s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    35.8s    35.0s    -0.77s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  35.8s    33.7s     -2.0s (-6%)
Assisted-by LLM
---
 scripts/Makefile          |   4 +-
 scripts/kallsyms-sysmap.c | 269 ++++++++++++++++++++++++++++++++++++++++++++++
 scripts/kallsyms.c        | 162 ++++++++++++++++------------
 scripts/kallsyms.h        |  44 ++++++++
 scripts/link-vmlinux.sh   |  15 +--
 scripts/mksysmap          |  94 ----------------
 6 files changed, 415 insertions(+), 173 deletions(-)
scripts/Makefile +3 -1
index 3434a82a119f..d46932113b5f 100644
@@ -3,7 +3,7 @@
 # scripts contains sources for various helper programs used throughout
 # the kernel for the build process.
 
-hostprogs-always-$(CONFIG_KALLSYMS)			+= kallsyms
+hostprogs-always-y				+= kallsyms
 hostprogs-always-$(BUILD_C_RECORDMCOUNT)		+= recordmcount
 hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT)		+= sorttable
 hostprogs-always-$(CONFIG_ASN1)				+= asn1_compiler
@@ -13,6 +13,7 @@ hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_builder
 hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_gen
 hostprogs-always-$(CONFIG_TRACEPOINTS)			+= tracepoint-update
 
+kallsyms-objs := kallsyms.o kallsyms-sysmap.o elf-parse.o
 sorttable-objs := sorttable.o elf-parse.o
 tracepoint-update-objs := tracepoint-update.o elf-parse.o
 
@@ -30,6 +31,7 @@ rustdoc_test_builder-rust := y
 rustdoc_test_gen-rust := y
 
 HOSTCFLAGS_tracepoint-update.o = -I$(srctree)/tools/include
+HOSTCFLAGS_kallsyms-sysmap.o = -I$(srctree)/tools/include
 HOSTCFLAGS_elf-parse.o = -I$(srctree)/tools/include
 HOSTCFLAGS_sorttable.o = -I$(srctree)/tools/include
 HOSTLDLIBS_sorttable = -lpthread
scripts/kallsyms-sysmap.c new file +25 -0
new file mode 100644
index 000000000000..64b2e11d0344
@@ -0,0 +1,269 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Obtain symbols from vmlinux for usage by kallsyms. Replaces mksysmap.
+ *
+ * To retain compatibility, it provides the same output as nm, only faster.
+ */
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <xalloc.h>
+
+#include "elf-parse.h"
+#include "kallsyms.h"
+
+/* The mapped file and its symbol table. */
+struct elf_file {
+	void *base;
+	size_t size;
+	const char *shdrs;
+	unsigned int shnum, shentsize;
+	const char *shstrtab;
+	Elf_Shdr *symtab;
+	const char *strtab;

scripts/kallsyms-sysmap.c line 35

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+	size_t nr_syms;
+};
+
+/* What mksysmap dropped from System.map, by name. */
+static const char *const sysmap_omit_prefixes[] = {
+	"$", ".L", "__efistub_", "__pi_$", "__pi_.L", "__kvm_nvhe_$",
+	"__kvm_nvhe_.L", "__kcfi_typeid_", "__kvm_nvhe___kcfi_typeid_",
+	"__pi___kcfi_typeid_", "__crc_", "__kstrtab_", "__kstrtabns_",
+	"__mod_device_table__",
+};

I really think these need to be 1 per line with the comments from scripts/mksysmap retained. It's going to be changed over time, and we want to be able to review the rationale for entries without having to dig through commit history.

scripts/kallsyms-sysmap.c line 41

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +6 -0
+static const char *const sysmap_omit_suffixes[] = {
+	"_from_arm", "_from_thumb", "_veneer",
+};
+static const char *const sysmap_omit_names[] = {
+	"L0", "_SDA_BASE_", "_SDA2_BASE_",
+};

Same for these 2 tables.

Quoted 15 lines
scripts/kallsyms-sysmap.c new file +15 -0
+
+/* __<alnum>*Thunk_: the linker's range extension thunks on arm. */
+static bool is_range_thunk(const char *name)
+{
+	const char *p;
+
+	if (!string_starts_with(name, "__"))
+		return false;
+	for (p = name + 2; isalnum((unsigned char)*p); p++)
+		;
+	return p - name >= 7 && *p == '_' && strncmp(p - 5, "Thunk", 5) == 0;
+}
+
+/* __UNIQUE_ID_modinfo_<n>: the MODULE_INFO() strings of built-in code. */
+static bool is_modinfo_id(const char *name)

scripts/kallsyms-sysmap.c line 66

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+{
+	static const char prefix[] = "__UNIQUE_ID_modinfo_";
+	const char *p;
+
+	if (!string_starts_with(name, prefix))
+		return false;
+	for (p = name + strlen(prefix); isdigit((unsigned char)*p); p++)
+		;
+	return !*p;
+}

I'm less excited about these "open coded" regular expression matches. Having to do this feels like it'll make future exceptions annoying to add. Can't there be another class of table that is just regular expressions? It is probably faster to keep the prefix/suffix/exact tables as-is, but is_range_thunk() and is_modinfo_id() just feel clunky compared to the more expressive re, e.g. r'^__UNIQUE_ID_modinfo[0-9]*$'

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+static bool sysmap_omits(const char *name, char type)
+{
+	size_t i;
+
+	/* Absolute, undefined and debugging symbols. */
+	if (type == 'a' || type == 'N' || type == 'U' || type == 'w')
+		return true;
+
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_prefixes); i++)
+		if (string_starts_with(name, sysmap_omit_prefixes[i]))

scripts/kallsyms-sysmap.c line 87

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+			return true;
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_suffixes); i++)
+		if (string_ends_with(name, sysmap_omit_suffixes[i]))
+			return true;
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_names); i++)
+		if (strcmp(name, sysmap_omit_names[i]) == 0)
+			return true;
+
+	return is_range_thunk(name) || is_modinfo_id(name) ||
+	       strstr(name, ".long_branch.") || strstr(name, ".plt_branch.");

And then mixing data-driven search with in-line patterns I don't like. The .long_branch. and .plt_branch. matches should be in a new "any position" table, IMO.

scripts/kallsyms-sysmap.c line 114

Quoted 7 lines
scripts/kallsyms-sysmap.c new file +7 -0
+/* nm's letter for a symbol defined in a section, as BFD classifies it. */
+static char section_symbol_type(Elf_Shdr *shdr, const char *secname)
+{
+	static const char *const debug_prefixes[] = {
+		".debug", ".zdebug", ".gnu.debuglto_.debug_",
+		".gnu.linkonce.wi.", ".line", ".stab",
+	};

I worry about maintenance overhead on this: are we going to have to chase changes to "nm" when other debug prefixes get added here?

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +6 -0
+	const uint64_t flags = shdr_flags(shdr);
+	size_t i;
+
+	if (flags & SHF_EXECINSTR)
+		return 't';
+	if (flags & SHF_ALLOC) {

scripts/kallsyms-sysmap.c line 130

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+		if (shdr_type(shdr) == SHT_NOBITS)
+			return 'b';
+		return flags & SHF_WRITE ? 'd' : 'r';
+	}
+	for (i = 0; i < ARRAY_SIZE(debug_prefixes); i++)
+		if (string_starts_with(secname, debug_prefixes[i]))
+			return 'N';
+	if (shdr_type(shdr) != SHT_NOBITS && !(flags & SHF_WRITE))
+		return 'n';
+	return '?';

And to that end: instead of "?" shouldn't this fail hard when a section symbol type is unknown to the tool?

Quoted 25 lines
scripts/kallsyms-sysmap.c new file +25 -0
+}
+
+/* The letter nm prints for a symbol, or 0 for one it leaves out. */
+static char elf_symbol_type(const struct elf_file *elf, Elf_Sym *sym)
+{
+	unsigned int bind = sym_bind(sym), type = sym_type(sym);
+	unsigned int shndx = sym_shndx(sym);
+	Elf_Shdr *shdr;
+	char c;
+
+	if (type == STT_SECTION || type == STT_FILE)
+		return 0;
+	if (shndx == SHN_COMMON)
+		return 'C';
+	if (shndx == SHN_UNDEF) {
+		if (bind == STB_WEAK)
+			return type == STT_OBJECT ? 'v' : 'w';
+		return 'U';
+	}
+	if (type == STT_GNU_IFUNC)
+		return 'i';
+	if (bind == STB_WEAK)
+		return type == STT_OBJECT ? 'V' : 'W';
+	if (bind == STB_GNU_UNIQUE)
+		return 'u';

scripts/kallsyms-sysmap.c line 165

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+	if (bind != STB_GLOBAL && bind != STB_LOCAL)
+		return '?';
+
+	if (shndx == SHN_ABS) {
+		c = 'a';
+	} else if (shndx < elf->shnum) {
+		shdr = elf_section(elf, shndx);
+		c = section_symbol_type(shdr, elf_section_name(elf, shdr));
+	} else {
+		return '?';

Same concerns...

Quoted 34 lines
scripts/kallsyms-sysmap.c new file +34 -0
+	}
+
+	return bind == STB_GLOBAL ? toupper(c) : c;
+}
+
+/* nm -n order: by address, then by name. */
+static int compare_symbols(const void *a, const void *b)
+{
+	const struct sysmap_symbol *sa = a, *sb = b;
+
+	if (sa->addr != sb->addr)
+		return sa->addr < sb->addr ? -1 : 1;
+	return strcmp(sa->name, sb->name);
+}
+
+static void elf_open(struct elf_file *elf, const char *path)
+{
+	Elf_Ehdr *ehdr;
+	unsigned int i;
+
+	elf->base = elf_map_ro(path, &elf->size, (1 << ET_EXEC) | (1 << ET_DYN));
+	if (!elf->base)
+		exit(EXIT_FAILURE);
+
+	ehdr = elf->base;
+	elf->shdrs = (const char *)elf->base + ehdr_shoff(ehdr);
+	elf->shnum = ehdr_shnum(ehdr);
+	elf->shentsize = ehdr_shentsize(ehdr);
+	elf->shstrtab = (const char *)elf->base +
+			shdr_offset(elf_section(elf, ehdr_shstrndx(ehdr)));
+
+	for (i = 0; i < elf->shnum && !elf->symtab; i++)
+		if (shdr_type(elf_section(elf, i)) == SHT_SYMTAB)
+			elf->symtab = elf_section(elf, i);

scripts/kallsyms-sysmap.c line 209

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+
+	if (!elf->symtab) {
+		fprintf(stderr, "%s: no symbol table\n", path);
+		exit(EXIT_FAILURE);
+	}
+
+	elf->strtab = (const char *)elf->base +
+		      shdr_offset(elf_section(elf, shdr_link(elf->symtab)));
+	elf->nr_syms = shdr_size(elf->symtab) / shdr_entsize(elf->symtab);
+}

These 2 functions kind of feel like they should live in elfparse instead?

Quoted 16 lines
scripts/kallsyms-sysmap.c new file +16 -0
+
+/* The symbols "nm -n | mksysmap" would list, in that order. */
+static struct sysmap_symbol *elf_read_symbols(const struct elf_file *elf,
+					   size_t *nr_kept)
+{
+	struct sysmap_symbol *syms = xmalloc(elf->nr_syms * sizeof(*syms));
+	size_t i, n = 0;
+
+	for (i = 1; i < elf->nr_syms; i++) {
+		Elf_Sym *sym = elf_symbol(elf, i);
+		const char *name = elf->strtab + sym_name(sym);
+		char type = elf_symbol_type(elf, sym);
+
+		if (!type || sysmap_omits(name, type))
+			continue;
+

scripts/kallsyms-sysmap.c line 235

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +10 -0
+		syms[n].addr = sym_value(sym);
+		syms[n].name = name;
+		syms[n].type = type;
+		n++;
+	}
+
+	qsort(syms, n, sizeof(*syms), compare_symbols);
+	*nr_kept = n;
+	return syms;
+}

And this one too, with maybe a "maybe_omit" callback passed in so this mksysmap could pass sysmap_omits in as?

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +1 -4
-static void read_map(const char *in)
+static void add_table_entry(struct sym_entry *sym)
 {
-	FILE *fp;
-	struct sym_entry *sym;
-	char *buf = NULL;

scripts/kallsyms-sysmap.c

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +4 -5
-	size_t buflen = 0;
+	sym->seq = table_cnt;
 
-	fp = fopen(in, "r");
-	if (!fp) {
-		perror(in);
-		exit(1);
+	if (table_cnt >= table_size) {
+		table_size += 10000;
+		table = xrealloc(table, sizeof(*table) * table_size);

I realize this is just moving logic around, but traditional xrealloc loop uses doubling. I think this was linear only because it wanted to jump-start the initial allocation size to 10000 entries. Could be:

	table_size = table_size ? table_size * 2 : 10000;

But maybe even that initial allocation number should be bumped up?

scripts/kallsyms-sysmap.c

Quoted 4 lines

[...]

scripts/kallsyms-sysmap.c new file +3 -0
+	if (optind + 1 == argc) {
+		read_elf(in, sysmap_out);
+		if (fclose(sysmap_out)) {

This needs to check ferror() too.

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +6 -0
+			perror(sysmap);
+			exit(EXIT_FAILURE);
+		}
+		return 0;
+	}
+
 	out_bin_name = argv[optind + 1];
 	out_bin_file = fopen(out_bin_name, "w");
 	if (!out_bin_file) {

scripts/kallsyms-sysmap.c int main(int argc, char **argv) · line 872

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +2 -1
@@ -852,7 +868,11 @@ int main(int argc, char **argv)
 		exit(EXIT_FAILURE);
 	}
 
-	read_map(argv[optind]);
+	read_elf(in, sysmap_out);
+	if (sysmap_out && fclose(sysmap_out)) {

Same: this needs to check ferror() too.

-Kees

Signature · 1 line
Kees Cook
#26 lore raw

Re: [PATCH v3 07/20] kallsyms: reimplement mksysmap in C

Quoted 120 lines · Kees Cook
Quoted 119 lines · Lorenzo Stoakes (ARM)

mksysmap is a sed script consisting of 30 patterns which link-vmlinux.sh uses to generate *.syms files, and which kallsyms is then called against to generate *.kallsyms files, with the final vmlinux build ultimately generating System.map.

For an x86-64 allmodconfig build, this involves three nm runs over a 250 MiB file and half a million lines written and read each time - 0.5s per pass for llvm-nm, and 0.2s for GNU nm, with parsing on top of that.

This is unnecessary, instead have kallsyms simply read the ELF file directly making use of the existing elf-parse library in scripts/.

This changes kallsyms such that its input is no longer the output from nm, but rather an ELF file.

However, if the input file is empty, it outputs an empty table, which retains the same behaviour on first pass that the build system expects.

System.map is byte-identical to nm | mksysmap for GNU nm and llvm-nm on two x86 configurations each, and for llvm-nm on arm64, arm, s390 and loongarch defconfigs, so are the kallsyms tables of every pass.

Relinking vmlinux, link steps included:

                        before    after
  allmodconfig clang     9.1s     7.9s
  allmodconfig gcc       7.8s     7.6s
  defconfig clang        3.7s     3.0s
  defconfig gcc          3.5s     3.4s

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        9.1s     8.6s    -0.43s (-5%)
  x86 defconfig, touch mm/vma.c, clang      9.0s     8.0s     -1.1s (-12%)
  x86 defconfig, clean, gcc                29.5s    28.9s    -0.64s (-2%)
  x86 defconfig, clean, clang              31.2s    29.8s     -1.4s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    35.8s    35.0s    -0.77s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  35.8s    33.7s     -2.0s (-6%)
Assisted-by LLM
---
 scripts/Makefile          |   4 +-
 scripts/kallsyms-sysmap.c | 269 ++++++++++++++++++++++++++++++++++++++++++++++
 scripts/kallsyms.c        | 162 ++++++++++++++++------------
 scripts/kallsyms.h        |  44 ++++++++
 scripts/link-vmlinux.sh   |  15 +--
 scripts/mksysmap          |  94 ----------------
 6 files changed, 415 insertions(+), 173 deletions(-)
scripts/Makefile +3 -1
index 3434a82a119f..d46932113b5f 100644
@@ -3,7 +3,7 @@
 # scripts contains sources for various helper programs used throughout
 # the kernel for the build process.
 
-hostprogs-always-$(CONFIG_KALLSYMS)			+= kallsyms
+hostprogs-always-y				+= kallsyms
 hostprogs-always-$(BUILD_C_RECORDMCOUNT)		+= recordmcount
 hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT)		+= sorttable
 hostprogs-always-$(CONFIG_ASN1)				+= asn1_compiler
@@ -13,6 +13,7 @@ hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_builder
 hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_gen
 hostprogs-always-$(CONFIG_TRACEPOINTS)			+= tracepoint-update
 
+kallsyms-objs := kallsyms.o kallsyms-sysmap.o elf-parse.o
 sorttable-objs := sorttable.o elf-parse.o
 tracepoint-update-objs := tracepoint-update.o elf-parse.o
 
@@ -30,6 +31,7 @@ rustdoc_test_builder-rust := y
 rustdoc_test_gen-rust := y
 
 HOSTCFLAGS_tracepoint-update.o = -I$(srctree)/tools/include
+HOSTCFLAGS_kallsyms-sysmap.o = -I$(srctree)/tools/include
 HOSTCFLAGS_elf-parse.o = -I$(srctree)/tools/include
 HOSTCFLAGS_sorttable.o = -I$(srctree)/tools/include
 HOSTLDLIBS_sorttable = -lpthread
scripts/kallsyms-sysmap.c new file +32 -0
new file mode 100644
index 000000000000..64b2e11d0344
@@ -0,0 +1,269 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Obtain symbols from vmlinux for usage by kallsyms. Replaces mksysmap.
+ *
+ * To retain compatibility, it provides the same output as nm, only faster.
+ */
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <xalloc.h>
+
+#include "elf-parse.h"
+#include "kallsyms.h"
+
+/* The mapped file and its symbol table. */
+struct elf_file {
+	void *base;
+	size_t size;
+	const char *shdrs;
+	unsigned int shnum, shentsize;
+	const char *shstrtab;
+	Elf_Shdr *symtab;
+	const char *strtab;
+	size_t nr_syms;
+};
+
+/* What mksysmap dropped from System.map, by name. */
+static const char *const sysmap_omit_prefixes[] = {
+	"$", ".L", "__efistub_", "__pi_$", "__pi_.L", "__kvm_nvhe_$",
+	"__kvm_nvhe_.L", "__kcfi_typeid_", "__kvm_nvhe___kcfi_typeid_",
Quoted 8 lines

scripts/kallsyms-sysmap.c line 35

Quoted 3 lines
scripts/kallsyms-sysmap.c new file +3 -0
+	"__pi___kcfi_typeid_", "__crc_", "__kstrtab_", "__kstrtabns_",
+	"__mod_device_table__",
+};

I really think these need to be 1 per line with the comments from scripts/mksysmap retained. It's going to be changed over time, and we want to be able to review the rationale for entries without having to dig through commit history.

Ack, done for v4.

Quoted 9 lines

scripts/kallsyms-sysmap.c line 41

Quoted 7 lines
scripts/kallsyms-sysmap.c new file +6 -0
+static const char *const sysmap_omit_suffixes[] = {
+	"_from_arm", "_from_thumb", "_veneer",
+};
+static const char *const sysmap_omit_names[] = {
+	"L0", "_SDA_BASE_", "_SDA2_BASE_",
+};

Same for these 2 tables.

Ack, done for v4.

Quoted 25 lines
Quoted 25 lines
scripts/kallsyms-sysmap.c new file +24 -0
+
+/* __<alnum>*Thunk_: the linker's range extension thunks on arm. */
+static bool is_range_thunk(const char *name)
+{
+	const char *p;
+
+	if (!string_starts_with(name, "__"))
+		return false;
+	for (p = name + 2; isalnum((unsigned char)*p); p++)
+		;
+	return p - name >= 7 && *p == '_' && strncmp(p - 5, "Thunk", 5) == 0;
+}
+
+/* __UNIQUE_ID_modinfo_<n>: the MODULE_INFO() strings of built-in code. */
+static bool is_modinfo_id(const char *name)
+{
+	static const char prefix[] = "__UNIQUE_ID_modinfo_";
+	const char *p;
+
+	if (!string_starts_with(name, prefix))
+		return false;
+	for (p = name + strlen(prefix); isdigit((unsigned char)*p); p++)
+		;
+	return !*p;
Quoted 8 lines

scripts/kallsyms-sysmap.c line 66

Quoted 1 line
scripts/kallsyms-sysmap.c new file +1 -0
+}

I'm less excited about these "open coded" regular expression matches. Having to do this feels like it'll make future exceptions annoying to add. Can't there be another class of table that is just regular expressions? It is probably faster to keep the prefix/suffix/exact tables as-is, but is_range_thunk() and is_modinfo_id() just feel clunky compared to the more expressive re, e.g. r'^__UNIQUE_ID_modinfo[0-9]*$'

I don't think it's too much of an issue, the two cases like this aren't too many lines of code, it seems a bit overkill, and I think that'd be the only use of regex here?

If a new pattern like this turns up it's easy enough to revisit it.

Quoted 17 lines
Quoted 17 lines
scripts/kallsyms-sysmap.c new file +16 -0
+static bool sysmap_omits(const char *name, char type)
+{
+	size_t i;
+
+	/* Absolute, undefined and debugging symbols. */
+	if (type == 'a' || type == 'N' || type == 'U' || type == 'w')
+		return true;
+
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_prefixes); i++)
+		if (string_starts_with(name, sysmap_omit_prefixes[i]))
+			return true;
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_suffixes); i++)
+		if (string_ends_with(name, sysmap_omit_suffixes[i]))
+			return true;
+	for (i = 0; i < ARRAY_SIZE(sysmap_omit_names); i++)
+		if (strcmp(name, sysmap_omit_names[i]) == 0)
Quoted 8 lines

scripts/kallsyms-sysmap.c line 87

Quoted 4 lines
scripts/kallsyms-sysmap.c new file +4 -0
+			return true;
+
+	return is_range_thunk(name) || is_modinfo_id(name) ||
+	       strstr(name, ".long_branch.") || strstr(name, ".plt_branch.");

And then mixing data-driven search with in-line patterns I don't like. The .long_branch. and .plt_branch. matches should be in a new "any position" table, IMO.

Ack done for v4 in sysmap_omit_patterns[].

Quoted 11 lines

scripts/kallsyms-sysmap.c line 114

Quoted 8 lines
scripts/kallsyms-sysmap.c new file +7 -0
+/* nm's letter for a symbol defined in a section, as BFD classifies it. */
+static char section_symbol_type(Elf_Shdr *shdr, const char *secname)
+{
+	static const char *const debug_prefixes[] = {
+		".debug", ".zdebug", ".gnu.debuglto_.debug_",
+		".gnu.linkonce.wi.", ".line", ".stab",
+	};

I worry about maintenance overhead on this: are we going to have to chase changes to "nm" when other debug prefixes get added here?

It mirrors what BFD has and it hasn't changed for years so I think it's fine :)

Quoted 12 lines
Quoted 12 lines
scripts/kallsyms-sysmap.c new file +11 -0
+	const uint64_t flags = shdr_flags(shdr);
+	size_t i;
+
+	if (flags & SHF_EXECINSTR)
+		return 't';
+	if (flags & SHF_ALLOC) {
+		if (shdr_type(shdr) == SHT_NOBITS)
+			return 'b';
+		return flags & SHF_WRITE ? 'd' : 'r';
+	}
+	for (i = 0; i < ARRAY_SIZE(debug_prefixes); i++)
Quoted 8 lines

scripts/kallsyms-sysmap.c line 130

Quoted 5 lines
scripts/kallsyms-sysmap.c new file +5 -0
+		if (string_starts_with(secname, debug_prefixes[i]))
+			return 'N';
+	if (shdr_type(shdr) != SHT_NOBITS && !(flags & SHF_WRITE))
+		return 'n';
+	return '?';

And to that end: instead of "?" shouldn't this fail hard when a section symbol type is unknown to the tool?

It mirrors what nm does (as with the rest of the code obv.) which prints '?' rather than failing, and that's never caused an issue, failling hard here would turn what wasn't a build failure into one so I think best to leave as-is?

Quoted 30 lines
Quoted 30 lines
scripts/kallsyms-sysmap.c new file +29 -0
+}
+
+/* The letter nm prints for a symbol, or 0 for one it leaves out. */
+static char elf_symbol_type(const struct elf_file *elf, Elf_Sym *sym)
+{
+	unsigned int bind = sym_bind(sym), type = sym_type(sym);
+	unsigned int shndx = sym_shndx(sym);
+	Elf_Shdr *shdr;
+	char c;
+
+	if (type == STT_SECTION || type == STT_FILE)
+		return 0;
+	if (shndx == SHN_COMMON)
+		return 'C';
+	if (shndx == SHN_UNDEF) {
+		if (bind == STB_WEAK)
+			return type == STT_OBJECT ? 'v' : 'w';
+		return 'U';
+	}
+	if (type == STT_GNU_IFUNC)
+		return 'i';
+	if (bind == STB_WEAK)
+		return type == STT_OBJECT ? 'V' : 'W';
+	if (bind == STB_GNU_UNIQUE)
+		return 'u';
+	if (bind != STB_GLOBAL && bind != STB_LOCAL)
+		return '?';
+
+	if (shndx == SHN_ABS) {
Quoted 8 lines

scripts/kallsyms-sysmap.c line 165

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +6 -0
+		c = 'a';
+	} else if (shndx < elf->shnum) {
+		shdr = elf_section(elf, shndx);
+		c = section_symbol_type(shdr, elf_section_name(elf, shdr));
+	} else {
+		return '?';

Same concerns...

See above

Quoted 39 lines
Quoted 39 lines
scripts/kallsyms-sysmap.c new file +38 -0
+	}
+
+	return bind == STB_GLOBAL ? toupper(c) : c;
+}
+
+/* nm -n order: by address, then by name. */
+static int compare_symbols(const void *a, const void *b)
+{
+	const struct sysmap_symbol *sa = a, *sb = b;
+
+	if (sa->addr != sb->addr)
+		return sa->addr < sb->addr ? -1 : 1;
+	return strcmp(sa->name, sb->name);
+}
+
+static void elf_open(struct elf_file *elf, const char *path)
+{
+	Elf_Ehdr *ehdr;
+	unsigned int i;
+
+	elf->base = elf_map_ro(path, &elf->size, (1 << ET_EXEC) | (1 << ET_DYN));
+	if (!elf->base)
+		exit(EXIT_FAILURE);
+
+	ehdr = elf->base;
+	elf->shdrs = (const char *)elf->base + ehdr_shoff(ehdr);
+	elf->shnum = ehdr_shnum(ehdr);
+	elf->shentsize = ehdr_shentsize(ehdr);
+	elf->shstrtab = (const char *)elf->base +
+			shdr_offset(elf_section(elf, ehdr_shstrndx(ehdr)));
+
+	for (i = 0; i < elf->shnum && !elf->symtab; i++)
+		if (shdr_type(elf_section(elf, i)) == SHT_SYMTAB)
+			elf->symtab = elf_section(elf, i);
+
+	if (!elf->symtab) {
+		fprintf(stderr, "%s: no symbol table\n", path);
+		exit(EXIT_FAILURE);
Quoted 8 lines

scripts/kallsyms-sysmap.c line 209

Quoted 6 lines
scripts/kallsyms-sysmap.c new file +6 -0
+	}
+
+	elf->strtab = (const char *)elf->base +
+		      shdr_offset(elf_section(elf, shdr_link(elf->symtab)));
+	elf->nr_syms = shdr_size(elf->symtab) / shdr_entsize(elf->symtab);
+}

These 2 functions kind of feel like they should live in elfparse instead?

Ack, updated this and patch 4 to share code for v4!

Quoted 22 lines
Quoted 22 lines
scripts/kallsyms-sysmap.c new file +21 -0
+
+/* The symbols "nm -n | mksysmap" would list, in that order. */
+static struct sysmap_symbol *elf_read_symbols(const struct elf_file *elf,
+					   size_t *nr_kept)
+{
+	struct sysmap_symbol *syms = xmalloc(elf->nr_syms * sizeof(*syms));
+	size_t i, n = 0;
+
+	for (i = 1; i < elf->nr_syms; i++) {
+		Elf_Sym *sym = elf_symbol(elf, i);
+		const char *name = elf->strtab + sym_name(sym);
+		char type = elf_symbol_type(elf, sym);
+
+		if (!type || sysmap_omits(name, type))
+			continue;
+
+		syms[n].addr = sym_value(sym);
+		syms[n].name = name;
+		syms[n].type = type;
+		n++;
+	}
Quoted 8 lines

scripts/kallsyms-sysmap.c line 235

Quoted 5 lines
scripts/kallsyms-sysmap.c new file +5 -0
+
+	qsort(syms, n, sizeof(*syms), compare_symbols);
+	*nr_kept = n;
+	return syms;
+}

And this one too, with maybe a "maybe_omit" callback passed in so this mksysmap could pass sysmap_omits in as?

This is pretty specific to this code so I think makes less sense to port this.

Quoted 22 lines
Quoted 7 lines
scripts/kallsyms-sysmap.c new file +1 -4
-static void read_map(const char *in)
+static void add_table_entry(struct sym_entry *sym)
 {
-	FILE *fp;
-	struct sym_entry *sym;
-	char *buf = NULL;

scripts/kallsyms-sysmap.c

Quoted 10 lines
scripts/kallsyms-sysmap.c new file +4 -5
-	size_t buflen = 0;
+	sym->seq = table_cnt;
 
-	fp = fopen(in, "r");
-	if (!fp) {
-		perror(in);
-		exit(1);
+	if (table_cnt >= table_size) {
+		table_size += 10000;
+		table = xrealloc(table, sizeof(*table) * table_size);

I realize this is just moving logic around, but traditional xrealloc loop uses doubling. I think this was linear only because it wanted to jump-start the initial allocation size to 10000 entries. Could be:

Quoted 1 line
	table_size = table_size ? table_size * 2 : 10000;

Ack, done for v4!

Quoted 2 lines

But maybe even that initial allocation number should be bumped up?

Not sure it's really worth it with doubling in place, better to assume less and use more I think, and the time taken for the realloc should be minimal in comparison to the run as a whole.

Quoted 7 lines

scripts/kallsyms-sysmap.c

Quoted 5 lines

[...]

scripts/kallsyms-sysmap.c new file +3 -0
+	if (optind + 1 == argc) {
+		read_elf(in, sysmap_out);
+		if (fclose(sysmap_out)) {

This needs to check ferror() too.

Ack, done for v4!

Quoted 14 lines
Quoted 14 lines
scripts/kallsyms-sysmap.c new file +6 -0
+			perror(sysmap);
+			exit(EXIT_FAILURE);
+		}
+		return 0;
+	}
+
 	out_bin_name = argv[optind + 1];
 	out_bin_file = fopen(out_bin_name, "w");
 	if (!out_bin_file) {
@@ -852,7 +868,11 @@ int main(int argc, char **argv)
 		exit(EXIT_FAILURE);
 	}
 
Quoted 5 lines

scripts/kallsyms-sysmap.c int main(int argc, char **argv) · line 872

Quoted 3 lines
scripts/kallsyms-sysmap.c new file +2 -1
-	read_map(argv[optind]);
+	read_elf(in, sysmap_out);
+	if (sysmap_out && fclose(sysmap_out)) {

Same: this needs to check ferror() too.

Ack, done for v4!

Quoted 6 lines

-Kees

--
Kees Cook

--
Cheers, Lorenzo

#27 lore raw

Re: [PATCH v3 07/20] kallsyms: reimplement mksysmap in C

Quoted 6 lines · Lorenzo Stoakes (ARM)
Quoted 3 lines · Kees Cook

On Thu, Sep 17, 2026 at 05:06:17PM +0100, Lorenzo Stoakes (ARM) wrote:

These 2 functions kind of feel like they should live in elfparse instead?

Ack, updated this and patch 4 to share code for v4!

Patch 6 even :)

--
Cheers, Lorenzo

#28 lore raw

PATCH v3 8/20 kbuild: cache list, composite object state per object

In reply to Lorenzo Stoakes (ARM)

When each object's command line is expanded, kbuild has to figure out on multiple occasions whether it's built-in or part of a module and which composite object it belongs to.

This causes the time spent on each directory in the kernel tree to grow O(n^2) with its object count, which is especially problematic for instance in drivers/gpu/drm/amd/amdgpu with 310 objects.

No-op builds (i.e. make -j $(nproc) when nothing has changed) are particularly impacted by this.

Fix the issue by caching this data and looking it up instead of getting it over and over again.

This has a particularly large impact on allmodconfig builds.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, no-op make, gcc            1.1s     1.1s    -0.02s (-2%)
  x86 defconfig, no-op make, clang          1.3s     1.3s    -0.01s (-1%)
  x86 allmodconfig, no-op make, gcc        15.3s    14.5s    -0.83s (-5%)
  x86 allmodconfig, no-op make, clang      16.2s    15.5s    -0.65s (-4%)
  x86 allmodconfig, touch mm/vma.c, gcc    35.0s    34.3s    -0.77s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  33.7s    33.2s    -0.51s (-2%)
Assisted-by LLM
---
 scripts/Makefile.build | 8 ++++++++
 scripts/Makefile.lib   | 7 +++----
 2 files changed, 11 insertions(+), 4 deletions(-)
scripts/Makefile.build +8 -0
index 4349108e75e1..2cabfe85b798 100644
@@ -122,6 +122,14 @@ multi-obj-m	:= $(addprefix $(obj)/, $(multi-obj-m))
 subdir-ym	:= $(addprefix $(obj)/, $(subdir-ym))
 endif
 
+# Cache which list each object is in and which composite objects it belongs to,
+# once per object for $(part-of-builtin), $(part-of-module) and $(modname-multi).
+$(foreach o, $(real-obj-y) $(lib-y), $(eval part-of-builtin_$o := y))
+$(foreach o, $(real-obj-m), $(eval part-of-module_$o := y))
+$(foreach m, $(multi-obj-ym), \
+	$(foreach o, $(call suffix-search, $m, .o, -objs -y -m), \
+		$(eval modname-multi_$o += $(m:.o=))))
+
 ifndef obj
 $(warning kbuild: Makefile.build is included improperly)
 endif
scripts/Makefile.lib +3 -4
index 0a4fdd8bd975..2f447bc25e7b 100644
@@ -2,8 +2,7 @@
 
 # Finds the multi-part object the current object will be linked into.
 # If the object belongs to two or more multi-part objects, list them all.
-modname-multi = $(sort $(foreach m,$(multi-obj-ym),\
-		$(if $(filter $*.o, $(call suffix-search, $m, .o, -objs -y -m)),$(m:.o=))))
+modname-multi = $(sort $(modname-multi_$*.o))
 
 __modname = $(or $(modname-multi),$(basetarget))
 
@@ -149,8 +148,8 @@ endif
 # If $(is-kernel-object) is 'y', this object will be linked to vmlinux or modules
 is-kernel-object = $(or $(part-of-builtin),$(part-of-module))
 
-part-of-builtin = $(if $(filter $(basename $@).o, $(real-obj-y) $(lib-y)),y)
-part-of-module = $(if $(filter $(basename $@).o, $(real-obj-m)),y)
+part-of-builtin = $(part-of-builtin_$(basename $@).o)
+part-of-module = $(part-of-module_$(basename $@).o)
 quiet_modtag = $(if $(part-of-module),[M],   )
 
 modkern_cflags =                                          \
Signature · 1 line
2.55.0
Reviewed-by on v3 8/20
#29 lore raw

Re: [PATCH v3 08/20] kbuild: cache list, composite object state per object

Quoted 2 lines · Lorenzo Stoakes (ARM)

Fix the issue by caching this data and looking it up instead of getting it over and over again.

Nit: I would describe this as "calculate these once". It _is_ caching, but I think with Makefiles there is an implication the "caching" means "write to disk". But maybe that's just me.

Quoted 1 line

This has a particularly large impact on allmodconfig builds.

Love it. :)

Signature · 1 line
Kees Cook
Reviewed-by
#30 lore raw

Re: [PATCH v3 08/20] kbuild: cache list, composite object state per object

Quoted 7 lines · Kees Cook
Quoted 2 lines · Lorenzo Stoakes (ARM)

Fix the issue by caching this data and looking it up instead of getting it over and over again.

Nit: I would describe this as "calculate these once". It _is_ caching, but I think with Makefiles there is an implication the "caching" means "write to disk". But maybe that's just me.

+1

Signature · 1 line
Nicolas
#31 lore raw

Re: [PATCH v3 08/20] kbuild: cache list, composite object state per object

Quoted 8 lines · Nicolas Schier
Quoted 7 lines · Kees Cook
Quoted 2 lines · Lorenzo Stoakes (ARM)

Fix the issue by caching this data and looking it up instead of getting it over and over again.

Nit: I would describe this as "calculate these once". It _is_ caching, but I think with Makefiles there is an implication the "caching" means "write to disk". But maybe that's just me.

Ack!

Quoted 4 lines

+1

And thanks! (also to Kees :)

Quoted 3 lines

--
Nicolas

--
Cheers, Lorenzo

#32 lore raw

PATCH v3 9/20 kbuild: implement and use depcheck to check dependency timestamps

In reply to Lorenzo Stoakes (ARM)

Each object's .cmd file lists its header dependencies, which often consists of over a thousand dependencies.

When little has changed in the tree, this is what make spends most of its time doing, spending over a second, single-threaded when parsing larger directory trees.

It performs considerably more work that is actually necessary to get the job done.

This can be done faster in C, so implement scripts/basic/depcheck to do so.

It does as little work as possible, reading the .cmd files from a directory's targets and running stat on each dependency only a single time.

It generates a fragment holding only the saved command line for a target whose dependencies all exist and are older than it, and the entire .cmd file for any other.

That way, Makefile.build simply includes the fragment and the amount of work make has to do is significantly reduced when there is not much work to do.

If the operation fails, kbuild falls back to using .cmd files.

The result is exactly the same as before.

For drivers/gpu/drm/amd/amdgpu in an allmodconfig tree the fragment is a fifth of the size of the .cmd files, make reads it in 10ms instead of 380ms, and the instance goes from 2.2s to 0.4s.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, no-op make, gcc            1.1s    0.78s    -0.30s (-28%)
  x86 defconfig, no-op make, clang          1.3s    0.94s    -0.34s (-27%)
  x86 allmodconfig, no-op make, gcc        14.5s    12.9s     -1.6s (-11%)
  x86 allmodconfig, no-op make, clang      15.5s    14.2s     -1.3s (-9%)
  x86 allmodconfig, touch mm/vma.c, gcc    34.3s    33.9s    -0.33s (-1%)
  x86 allmodconfig, touch mm/vma.c, clang  33.2s    32.2s    -0.98s (-3%)
Assisted-by LLM
---
 Makefile                 |   1 +
 scripts/Makefile.build   |  14 +-
 scripts/basic/.gitignore |   1 +
 scripts/basic/Makefile   |   2 +-
 scripts/basic/depcheck.c | 441 +++++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 457 insertions(+), 2 deletions(-)
Makefile +1 -0
index dd4c10afbb7f..8105123bcf4d 100644
@@ -2237,6 +2237,7 @@ clean: $(clean-dirs)
 	$(call cmd,rmfiles)
 	@find . $(RCS_FIND_IGNORE) \
 		\( -name '*.[aios]' -o -name '*.rsi' -o -name '*.ko' -o -name '.*.cmd' \
+		-o -name '.depcheck.mk' -o -name '.depcheck.mk.tmp' \
 		-o -name '*.ko.*' -o -name '*.o.thinlto.bc' \
 		-o -name '*.dtb' -o -name '*.dtbo' \
 		-o -name '*.dtb.S' -o -name '*.dtbo.S' \
scripts/Makefile.build +13 -1
index 2cabfe85b798..b9093b39cc2f 100644
@@ -592,7 +592,19 @@ $(obj)/: $(if $(KBUILD_BUILTIN), $(targets-for-builtin)) \
 
 existing-targets := $(wildcard $(sort $(targets)))
 
--include $(foreach f,$(existing-targets),$(dir $(f)).$(notdir $(f)).cmd)
+cmd-files := $(foreach f,$(existing-targets),$(dir $(f)).$(notdir $(f)).cmd)
+
+# depcheck checks timestamps first and outputs only saved command lines of
+# up-to-date targets, falling back to .cmd files if it fails.
+depcheck := $(wildcard $(objtree)/scripts/basic/depcheck)
+
+ifneq ($(and $(depcheck),$(cmd-files)),)
+ifeq ($(shell $(depcheck) $(obj)/.depcheck.mk $(cmd-files) && echo ok),ok)
+cmd-files := $(obj)/.depcheck.mk
+endif
+endif
+
+-include $(cmd-files)
 
 # Create directories for object files if they do not exist
 obj-dirs := $(sort $(patsubst %/,%, $(dir $(targets))))
scripts/basic/.gitignore +1 -0
index 07c195f605a1..761ee14f9477 100644
@@ -1,3 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
+/depcheck
 /fixdep
 /randstruct.seed
scripts/basic/Makefile +1 -1
index fb8e2c38fbc7..ff98780e474d 100644
@@ -2,7 +2,7 @@
 #
 # fixdep: used to generate dependency information during build process
 
-hostprogs-always-y	+= fixdep
+hostprogs-always-y	+= fixdep depcheck
 
 # randstruct: the seed is needed before building the gcc-plugin or
 # before running a Clang kernel build.
scripts/basic/depcheck.c new file +441 -0

441 lines not on this page · raw message

Signature · 1 line
2.55.0
#33 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

Quoted 4 lines · Lorenzo Stoakes (ARM)

This can be done faster in C, so implement scripts/basic/depcheck to do so.

It does as little work as possible, reading the .cmd files from a directory's targets and running stat on each dependency only a single time.

Doesn't this run the risk of missing transitive deps?

C.cmd: C.o depends on A.c and B.c and B.h
B.cmd: B.h depends on B.data and B.script

depcheck looks at C.o and B.h's times and is happy so it drops C.cmd file, but then see B.script has changed compared to B.h, so it keeps B.cmd, and then the build runs and doesn't have the C.o dep list any more, and C.o goes unbuilt?

Also, I don't think this handles if_changed commands at all? The kbuild rebuild condition is timestamps plus if_changed's command-line check.

Quoted 23 lines
scripts/basic/depcheck.c new file +12 -0
new file mode 100644
index 000000000000..622101c33650
@@ -0,0 +1,441 @@
[...]
+/* What fixdep writes, see above. */
+#define DEPS_PREFIX		"deps_"
+#define DEPS_RULE_PREFIX	"$(" DEPS_PREFIX
+#define RULE_SUFFIX		":"
+#define LINE_CONTINUATION	" \\"
+#define WILDCARD_OPEN		"$(wildcard "
+#define WILDCARD_CLOSE		")"
+#define CMD_SUFFIX		".cmd"
[...]
+static bool is_blank(char chr)
[...]
+static bool str_ends_with(const char *str, const char *suffix)
[...]
+static bool line_starts_with(const struct line *line, const char *prefix)
[...]
+static bool line_ends_with(const struct line *line, const char *suffix)

scripts/basic/depcheck.c line 122

Quoted 10 lines
scripts/basic/depcheck.c new file +5 -0
[...]
+static bool line_is_blank(const struct line *line)
[...]
+static bool line_is_continued(const struct line *line)
[...]
+static void line_strip_continuation(struct line *line)
[...]
+static void line_trim(struct line *line)
[...]
+static bool next_line(const char **pos, const char *end, struct line *line)

There is a lot of sting handling in here. I know you're going for speed, but it just feels like a python script doing all this would be much more readable without wrecking speed compared to C much. Yes, C will win out, but the maintainability of this helper does not fill me with joy. :P

Quoted 7 lines

[...]

scripts/basic/depcheck.c new file +6 -0
+static const struct dep *lookup_dep(const char *path)
+{
+	const unsigned int key = hash_str(path);
+	struct dep *dep;
+	struct stat st;
+

scripts/basic/depcheck.c line 162

Quoted 10 lines
scripts/basic/depcheck.c new file +10 -0
+	hash_for_each_possible(dep_table, dep, hnode, key) {
+		if (!strcmp(dep->path, path))
+			return dep;
+	}
+
+	dep = xmalloc(sizeof(*dep) + strlen(path) + 1);
+	strcpy(dep->path, path);
+	dep->exists = !stat(path, &st);
+	if (dep->exists)
+		dep->mtime = st.st_mtim;

I realize you only check "mtime" after an "exists" check, but I bristle at leaving a time-stamp uninitialized. Can we just add an "else dep->mtime = 0" here?

-Kees

Signature · 1 line
Kees Cook
#34 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

Quoted 11 lines · Kees Cook
Quoted 4 lines · Lorenzo Stoakes (ARM)

This can be done faster in C, so implement scripts/basic/depcheck to do so.

It does as little work as possible, reading the .cmd files from a directory's targets and running stat on each dependency only a single time.

Doesn't this run the risk of missing transitive deps?

C.cmd: C.o depends on A.c and B.c and B.h
B.cmd: B.h depends on B.data and B.script

Quoted 7 lines

depcheck looks at C.o and B.h's times and is happy so it drops C.cmd file, but then see B.script has changed compared to B.h, so it keeps B.cmd, and then the build runs and doesn't have the C.o dep list any more, and C.o goes unbuilt?

Also, I don't think this handles if_changed commands at all? The kbuild rebuild condition is timestamps plus if_changed's command-line check.

tl;dr: I spent way too long looking at this. I think my conclusion is "Hm, this makes some cases of missed Makefile deps on generated files harder to find, but there don't *appear* to be any obviously wrong instances of this in the tree."

Long version:

There does appear to be a problem in the case of generated targets where the Makefile deps are build-order correct but lack explicit deps. As in, a clean build generates the needed dependencies due to some prior explicit Makefile rule dependency, and a later source-level "#include" for the generated file exists (and the build doesn't fail since the included file got generated before the source that "#include"d it got built), and then the normal dep tracking (-Wp,-MMD,... -> .cmd) catches it and any direct changes to that dep would normally get noticed going forward on incremental builds.

However, with the depcheck .cmd pruning, changes to transitive deps (either via file contents or Kconfig options) will go unnoticed during incremental builds without that explicit dep (but stock doesn't miss it). Though actually it's kind of worse because it'll get noticed on rebuild #N+1 for N level of transitive depth, so something will break, and then you build again, and the changes from 2 builds ago suddenly get rebuilt...

I think you maybe encountered an instance of this in your series, too, but it got exposed due to a clean build no longer having the ordering correct:
https://lore.kernel.org/lkml/[email protected]/

See the trailing diff for a demo:

git apply demo.diff
make O=b defconfig

  # simulate a earlier-stage header generation...
  make O=b lib/byfile_anchor.o lib/byconf_anchor.o
  make O=b lib/
  # trigger 1: the header's input file changes
  echo FROMFILE-two > lib/byfile_gen.in
  make O=b lib/
  # trigger 2: a Kconfig value changes; no file is touched
  ./scripts/config --file b/.config --set-str LOCALVERSION -demo2
  make O=b lib/
  # what each object ended up holding
  strings b/lib/byfile_anchor.o | grep FROMFILE-    # FROMFILE-two   both trees
  strings b/lib/byfile_victim.o | grep FROMFILE-    # FROMFILE-two   stock
                                                    # FROMFILE-one   patched  <-- stale
  strings b/lib/byconf_anchor.o | grep CONF-        # CONF--demo2    both trees
  strings b/lib/byconf_victim.o | grep CONF-        # CONF--demo2    stock
                                                    # CONF-          patched  <-- stale

This means adding depcheck would silently expose any current (and future) missing explicit deps on generated files where those files get generated by either an earlier build stage or an earlier rule. :(

I went looking for the kind of missed Makefile dep for a generated file, and while it's not a very grep-able condition, I did look at stuff that fell into include/generated/, but it's safe due to the prepare/archprepare ordering AFAICT. So then I looked at places where -I had $(obj) added to it, and all of those seemed to have explicit Makefile deps too. Well, all except for arch/x86/boot/compressed/sev-handle-vc.c which includes "../../lib/inat.c" but that seems safe today due to ordering from arch/x86/lib/ being needed before arch/x86/boot/compressed/.

So, yeah, it makes me nervous, and it may make incremental builds less idempotent. But I can't really find extant problems and the demo is slightly contrived, but not exactly an impossible situation.

-Kees

lib/Makefile +33 -0
index dfab958327c5c..aed0bd9eb7d6a 100644
@@ -350,3 +350,36 @@ CONTEXT_ANALYSIS_test_context-analysis.o := y
 obj-$(CONFIG_CONTEXT_ANALYSIS_TEST) += test_context-analysis.o
 
 subdir-$(CONFIG_FORTIFY_SOURCE) += test_fortify
+
+# --- depcheck demo ---
+obj-y += byfile_anchor.o byfile_victim.o byconf_anchor.o byconf_victim.o
+
+quiet_cmd_byfile = GENFILE $@
+      cmd_byfile = printf '\#define BYFILE_STR "%s"\n' "$$(cat $<)" > $@
+
+quiet_cmd_byconf = GENCONF $@
+      cmd_byconf = printf '\#define BYCONF_STR "CONF-%s"\n' '$(CONFIG_LOCALVERSION)' > $@
+
+# Regenerated when its input file changes.
+$(obj)/byfile_gen.h: $(src)/byfile_gen.in FORCE
+	$(call if_changed,byfile)
+
+# No input file: regenerated only when its command line changes, which here
+# means when CONFIG_LOCALVERSION changes. No file is touched.
+$(obj)/byconf_gen.h: FORCE
+	$(call if_changed,byconf)
+
+targets += byfile_gen.h byconf_gen.h
+
+# The anchors declare the dependency. That is what generates the headers on
+# a clean build: fixdep only records a header once the object has compiled
+# successfully, so on a first build there is no .cmd file to rely on. The
+# victims include the same headers without declaring them, so the only
+# record of that edge is the deps_ list in their .cmd files.
+$(obj)/byfile_anchor.o: $(obj)/byfile_gen.h
+$(obj)/byconf_anchor.o: $(obj)/byconf_gen.h
+
+CFLAGS_byfile_anchor.o += -I$(obj)
+CFLAGS_byfile_victim.o += -I$(obj)
+CFLAGS_byconf_anchor.o += -I$(obj)
+CFLAGS_byconf_victim.o += -I$(obj)
lib/byconf_anchor.c new file +3 -0
new file mode 100644
index 0000000000000..8035eaa352a3b
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byconf_gen.h"
+const char byconf_anchor_marker[] = BYCONF_STR;
lib/byconf_victim.c new file +3 -0
new file mode 100644
index 0000000000000..285a8de8bdf6e
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byconf_gen.h"
+const char byconf_victim_marker[] = BYCONF_STR;
lib/byfile_anchor.c new file +3 -0
new file mode 100644
index 0000000000000..9ea0b8ad55963
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byfile_gen.h"
+const char byfile_anchor_marker[] = BYFILE_STR;
lib/byfile_gen.in new file +1 -0
new file mode 100644
index 0000000000000..7da9e5e0cd83c
@@ -0,0 +1 @@
+FROMFILE-one
lib/byfile_victim.c new file +3 -0
new file mode 100644
index 0000000000000..763c5ef8f1514
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byfile_gen.h"
+const char byfile_victim_marker[] = BYFILE_STR;
Signature · 1 line
Kees Cook
#35 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

Quoted 90 lines · Kees Cook
Quoted 11 lines · Kees Cook
Quoted 4 lines · Lorenzo Stoakes (ARM)

This can be done faster in C, so implement scripts/basic/depcheck to do so.

It does as little work as possible, reading the .cmd files from a directory's targets and running stat on each dependency only a single time.

Doesn't this run the risk of missing transitive deps?

C.cmd: C.o depends on A.c and B.c and B.h
B.cmd: B.h depends on B.data and B.script

Quoted 7 lines

depcheck looks at C.o and B.h's times and is happy so it drops C.cmd file, but then see B.script has changed compared to B.h, so it keeps B.cmd, and then the build runs and doesn't have the C.o dep list any more, and C.o goes unbuilt?

Also, I don't think this handles if_changed commands at all? The kbuild rebuild condition is timestamps plus if_changed's command-line check.

tl;dr: I spent way too long looking at this. I think my conclusion is "Hm, this makes some cases of missed Makefile deps on generated files harder to find, but there don't *appear* to be any obviously wrong instances of this in the tree."

Long version:

There does appear to be a problem in the case of generated targets where the Makefile deps are build-order correct but lack explicit deps. As in, a clean build generates the needed dependencies due to some prior explicit Makefile rule dependency, and a later source-level "#include" for the generated file exists (and the build doesn't fail since the included file got generated before the source that "#include"d it got built), and then the normal dep tracking (-Wp,-MMD,... -> .cmd) catches it and any direct changes to that dep would normally get noticed going forward on incremental builds.

However, with the depcheck .cmd pruning, changes to transitive deps (either via file contents or Kconfig options) will go unnoticed during incremental builds without that explicit dep (but stock doesn't miss it). Though actually it's kind of worse because it'll get noticed on rebuild #N+1 for N level of transitive depth, so something will break, and then you build again, and the changes from 2 builds ago suddenly get rebuilt...

I think you maybe encountered an instance of this in your series, too, but it got exposed due to a clean build no longer having the ordering correct:
https://lore.kernel.org/lkml/[email protected]/

See the trailing diff for a demo:

git apply demo.diff
make O=b defconfig

  # simulate a earlier-stage header generation...
  make O=b lib/byfile_anchor.o lib/byconf_anchor.o
  make O=b lib/
  # trigger 1: the header's input file changes
  echo FROMFILE-two > lib/byfile_gen.in
  make O=b lib/
  # trigger 2: a Kconfig value changes; no file is touched
  ./scripts/config --file b/.config --set-str LOCALVERSION -demo2
  make O=b lib/
  # what each object ended up holding
  strings b/lib/byfile_anchor.o | grep FROMFILE-    # FROMFILE-two   both trees
  strings b/lib/byfile_victim.o | grep FROMFILE-    # FROMFILE-two   stock
                                                    # FROMFILE-one   patched  <-- stale
  strings b/lib/byconf_anchor.o | grep CONF-        # CONF--demo2    both trees
  strings b/lib/byconf_victim.o | grep CONF-        # CONF--demo2    stock
                                                    # CONF-          patched  <-- stale

This means adding depcheck would silently expose any current (and future) missing explicit deps on generated files where those files get generated by either an earlier build stage or an earlier rule. :(

I went looking for the kind of missed Makefile dep for a generated file, and while it's not a very grep-able condition, I did look at stuff that fell into include/generated/, but it's safe due to the prepare/archprepare ordering AFAICT. So then I looked at places where -I had $(obj) added to it, and all of those seemed to have explicit Makefile deps too. Well, all except for arch/x86/boot/compressed/sev-handle-vc.c which includes "../../lib/inat.c" but that seems safe today due to ordering from arch/x86/lib/ being needed before arch/x86/boot/compressed/.

Quoted 3 lines

So, yeah, it makes me nervous, and it may make incremental builds less idempotent. But I can't really find extant problems and the demo is slightly contrived, but not exactly an impossible situation.

Ack thanks for this!

There is definitely an issue here, your example is fine in the stock kernel but one run late in v3.

Solution is to have depcheck treat any dependency that is itself a target of the same run as never being 'fresh' (it already reads every .cmd file in the directory so has all the dependency information it needs), so that's fixed in v4.

Confirmed that it fixes the demo'd bug here, that touching a header rebuilds exactly the same objects as it did before and that noop build perf was not harmed by the change.

Quoted 91 lines
(quoted diff) +0 -1
-Kees
lib/Makefile +33 -0
index dfab958327c5c..aed0bd9eb7d6a 100644
@@ -350,3 +350,36 @@ CONTEXT_ANALYSIS_test_context-analysis.o := y
 obj-$(CONFIG_CONTEXT_ANALYSIS_TEST) += test_context-analysis.o
 
 subdir-$(CONFIG_FORTIFY_SOURCE) += test_fortify
+
+# --- depcheck demo ---
+obj-y += byfile_anchor.o byfile_victim.o byconf_anchor.o byconf_victim.o
+
+quiet_cmd_byfile = GENFILE $@
+      cmd_byfile = printf '\#define BYFILE_STR "%s"\n' "$$(cat $<)" > $@
+
+quiet_cmd_byconf = GENCONF $@
+      cmd_byconf = printf '\#define BYCONF_STR "CONF-%s"\n' '$(CONFIG_LOCALVERSION)' > $@
+
+# Regenerated when its input file changes.
+$(obj)/byfile_gen.h: $(src)/byfile_gen.in FORCE
+	$(call if_changed,byfile)
+
+# No input file: regenerated only when its command line changes, which here
+# means when CONFIG_LOCALVERSION changes. No file is touched.
+$(obj)/byconf_gen.h: FORCE
+	$(call if_changed,byconf)
+
+targets += byfile_gen.h byconf_gen.h
+
+# The anchors declare the dependency. That is what generates the headers on
+# a clean build: fixdep only records a header once the object has compiled
+# successfully, so on a first build there is no .cmd file to rely on. The
+# victims include the same headers without declaring them, so the only
+# record of that edge is the deps_ list in their .cmd files.
+$(obj)/byfile_anchor.o: $(obj)/byfile_gen.h
+$(obj)/byconf_anchor.o: $(obj)/byconf_gen.h
+
+CFLAGS_byfile_anchor.o += -I$(obj)
+CFLAGS_byfile_victim.o += -I$(obj)
+CFLAGS_byconf_anchor.o += -I$(obj)
+CFLAGS_byconf_victim.o += -I$(obj)
lib/byconf_anchor.c new file +3 -0
new file mode 100644
index 0000000000000..8035eaa352a3b
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byconf_gen.h"
+const char byconf_anchor_marker[] = BYCONF_STR;
lib/byconf_victim.c new file +3 -0
new file mode 100644
index 0000000000000..285a8de8bdf6e
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byconf_gen.h"
+const char byconf_victim_marker[] = BYCONF_STR;
lib/byfile_anchor.c new file +3 -0
new file mode 100644
index 0000000000000..9ea0b8ad55963
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byfile_gen.h"
+const char byfile_anchor_marker[] = BYFILE_STR;
lib/byfile_gen.in new file +1 -0
new file mode 100644
index 0000000000000..7da9e5e0cd83c
@@ -0,0 +1 @@
+FROMFILE-one
lib/byfile_victim.c new file +3 -1
new file mode 100644
index 0000000000000..763c5ef8f1514
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "byfile_gen.h"
+const char byfile_victim_marker[] = BYFILE_STR;
 
 
--
Quoted 1 line

Kees Cook

--
Cheers, Lorenzo

#36 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

Quoted 10 lines · Lorenzo Stoakes (ARM)
Quoted 3 lines · Kees Cook

So, yeah, it makes me nervous, and it may make incremental builds less idempotent. But I can't really find extant problems and the demo is slightly contrived, but not exactly an impossible situation.

Ack thanks for this!

There is definitely an issue here, your example is fine in the stock kernel but one run late in v3.

Quoted 8 lines

Solution is to have depcheck treat any dependency that is itself a target of the same run as never being 'fresh' (it already reads every .cmd file in the directory so has all the dependency information it needs), so that's fixed in v4.

Confirmed that it fixes the demo'd bug here, that touching a header rebuilds exactly the same objects as it did before and that noop build perf was not harmed by the change.

Oh very nice! Thank you for finding a solution there. :)

Signature · 1 line
Kees Cook
#37 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

In reply to Kees Cook
Quoted 8 lines · Kees Cook
Quoted 4 lines · Lorenzo Stoakes (ARM)

This can be done faster in C, so implement scripts/basic/depcheck to do so.

It does as little work as possible, reading the .cmd files from a directory's targets and running stat on each dependency only a single time.

Doesn't this run the risk of missing transitive deps?

Quoted 7 lines

C.cmd: C.o depends on A.c and B.c and B.h
B.cmd: B.h depends on B.data and B.script

depcheck looks at C.o and B.h's times and is happy so it drops C.cmd file, but then see B.script has changed compared to B.h, so it keeps B.cmd, and then the build runs and doesn't have the C.o dep list any more, and C.o goes unbuilt?

No, B.h's .cmd file is still in the fragment with the full dependency list, so make remakes B.h from B.script and C.o's saved command line is there too.

But, as you mention in the follow up :), it screws up on next bit - C.o depending on B.h with B.h just remade. Will reply to your follow-up on that!

Quoted 3 lines

Also, I don't think this handles if_changed commands at all? The kbuild rebuild condition is timestamps plus if_changed's command-line check.

It does, the fragment always has the saved command line, only the dependency list is dropped, so if_changed compares the same as before.

Quoted 31 lines
Quoted 31 lines
scripts/basic/depcheck.c new file +15 -0
new file mode 100644
index 000000000000..622101c33650
@@ -0,0 +1,441 @@
[...]
+/* What fixdep writes, see above. */
+#define DEPS_PREFIX		"deps_"
+#define DEPS_RULE_PREFIX	"$(" DEPS_PREFIX
+#define RULE_SUFFIX		":"
+#define LINE_CONTINUATION	" \\"
+#define WILDCARD_OPEN		"$(wildcard "
+#define WILDCARD_CLOSE		")"
+#define CMD_SUFFIX		".cmd"
[...]
+static bool is_blank(char chr)
[...]
+static bool str_ends_with(const char *str, const char *suffix)
[...]
+static bool line_starts_with(const struct line *line, const char *prefix)
[...]
+static bool line_ends_with(const struct line *line, const char *suffix)
[...]
+static bool line_is_blank(const struct line *line)
[...]
+static bool line_is_continued(const struct line *line)
[...]
+static void line_strip_continuation(struct line *line)
[...]
Quoted 8 lines

scripts/basic/depcheck.c line 122

Quoted 3 lines
scripts/basic/depcheck.c new file +2 -0
+static void line_trim(struct line *line)
[...]
+static bool next_line(const char **pos, const char *end, struct line *line)

There is a lot of sting handling in here. I know you're going for speed, but it just feels like a python script doing all this would be much more readable without wrecking speed compared to C much. Yes, C will win out, but the maintainability of this helper does not fill me with joy. :P

Well I had the LLM look at that and for an allmodconfig python's startup time would take 40s of CPU time _alone_ and it'd kill the no op improvement. So C it has to be :)

Quoted 14 lines
Quoted 14 lines

[...]

scripts/basic/depcheck.c new file +12 -0
+static const struct dep *lookup_dep(const char *path)
+{
+	const unsigned int key = hash_str(path);
+	struct dep *dep;
+	struct stat st;
+
+	hash_for_each_possible(dep_table, dep, hnode, key) {
+		if (!strcmp(dep->path, path))
+			return dep;
+	}
+
+	dep = xmalloc(sizeof(*dep) + strlen(path) + 1);
Quoted 8 lines

scripts/basic/depcheck.c line 162

Quoted 4 lines
scripts/basic/depcheck.c new file +4 -0
+	strcpy(dep->path, path);
+	dep->exists = !stat(path, &st);
+	if (dep->exists)
+		dep->mtime = st.st_mtim;

I realize you only check "mtime" after an "exists" check, but I bristle at leaving a time-stamp uninitialized. Can we just add an "else dep->mtime = 0" here?

Ack, done for v4!

Quoted 5 lines

-Kees

--
Kees Cook

--
Cheers, Lorenzo

#38 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

Quoted 23 lines · Lorenzo Stoakes (ARM)
Quoted 13 lines · Kees Cook
Quoted 13 lines

[...]

scripts/basic/depcheck.c new file +12 -0
+static const struct dep *lookup_dep(const char *path)
+{
+	const unsigned int key = hash_str(path);
+	struct dep *dep;
+	struct stat st;
+
+	hash_for_each_possible(dep_table, dep, hnode, key) {
+		if (!strcmp(dep->path, path))
+			return dep;
+	}
+
+	dep = xmalloc(sizeof(*dep) + strlen(path) + 1);
Quoted 8 lines

scripts/basic/depcheck.c line 162

Quoted 4 lines
scripts/basic/depcheck.c new file +4 -0
+	strcpy(dep->path, path);
+	dep->exists = !stat(path, &st);
+	if (dep->exists)
+		dep->mtime = st.st_mtim;

I realize you only check "mtime" after an "exists" check, but I bristle at leaving a time-stamp uninitialized. Can we just add an "else dep->mtime = 0" here?

Quoted 1 line

Ack, done for v4!

Actually I think it's nicer to just make this xmalloc() an xcalloc() here, dep->mtime is a struct timespec and setting that to zero gets ugly :)

Quoted 9 lines
Quoted 6 lines

-Kees

--
Kees Cook

--
Cheers, Lorenzo

--
Cheers, Lorenzo

#39 lore raw

Re: [PATCH v3 09/20] kbuild: implement and use depcheck to check dependency timestamps

In reply to Lorenzo Stoakes (ARM)
Quoted 5 lines · Lorenzo Stoakes (ARM)
Quoted 4 lines · Kees Cook
Quoted 2 lines · Lorenzo Stoakes (ARM)

[...]
+static bool next_line(const char **pos, const char *end, struct line *line)

Quoted 8 lines
Quoted 4 lines

There is a lot of string handling in here. I know you're going for speed, but it just feels like a python script doing all this would be much more readable without wrecking speed compared to C much. Yes, C will win out, but the maintainability of this helper does not fill me with joy. :P

Well I had the LLM look at that and for an allmodconfig python's startup time would take 40s of CPU time _alone_ and it'd kill the no op improvement. So C it has to be :)

Yikes, that's huge. C it is. ;)

Signature · 1 line
Kees Cook
#40 lore raw

PATCH v3 10/20 kbuild: move the toolchain checks into init/Kconfig.toolchain

In reply to Lorenzo Stoakes (ARM)

init/Kconfig opens with two hundred lines identifying the compiler, assembler, linker and rustc and probing which options they support, none of it to do with init.

Move them into their own file, sourced from the top of init/Kconfig, so that the next commit can add to them without growing init/Kconfig further.

No functional change.

Assisted-by LLM
---
 init/Kconfig           | 197 +-----------------------------------------------
 init/Kconfig.toolchain | 198 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 196 deletions(-)
init/Kconfig +1 -196
index 8583d9f06c52..b44a9482cdc9 100644
@@ -1,201 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
-config CC_VERSION_TEXT
-	string
-	default "$(CC_VERSION_TEXT)"
-	help
-	  This is used in unclear ways:
-
-	  - Re-run Kconfig when the compiler is updated
-	    The 'default' property references the environment variable,
-	    CC_VERSION_TEXT so it is recorded in include/config/auto.conf.cmd.
-	    When the compiler is updated, Kconfig will be invoked.
-
-	  - Ensure full rebuild when the compiler is updated
-	    include/linux/compiler-version.h contains this option in the comment
-	    line so fixdep adds include/config/CC_VERSION_TEXT into the
-	    auto-generated dependency. When the compiler is updated, syncconfig
-	    will touch it and then every file will be rebuilt.
-
-config CC_IS_GCC
-	def_bool $(success,test "$(cc-name)" = GCC)
-
-config GCC_VERSION
-	int
-	default $(cc-version) if CC_IS_GCC
-	default 0
-
-config CC_IS_CLANG
-	def_bool $(success,test "$(cc-name)" = Clang)
-
-config CLANG_VERSION
-	int
-	default $(cc-version) if CC_IS_CLANG
-	default 0
-
-config AS_IS_GNU
-	def_bool $(success,test "$(as-name)" = GNU)
-
-config AS_IS_LLVM
-	def_bool $(success,test "$(as-name)" = LLVM)
-
-config AS_VERSION
-	int
-	# Use clang version if this is the integrated assembler
-	default CLANG_VERSION if AS_IS_LLVM
-	default $(as-version)
-
-config LD_IS_BFD
-	def_bool $(success,test "$(ld-name)" = BFD)
-
-config LD_VERSION
-	int
-	default $(ld-version) if LD_IS_BFD
-	default 0
-
-config LD_IS_LLD
-	def_bool $(success,test "$(ld-name)" = LLD)
-
-config LLD_VERSION
-	int
-	default $(ld-version) if LD_IS_LLD
-	default 0
-
-config RUSTC_VERSION
-	int
-	default $(rustc-version)
-	help
-	  It does not depend on `RUST` since that one may need to use the version
-	  in a `depends on`.
-
-config RUST_IS_AVAILABLE
-	def_bool $(success,$(srctree)/scripts/rust_is_available.sh)
-	help
-	  This shows whether a suitable Rust toolchain is available (found).
-
-	  Please see Documentation/rust/quick-start.rst for instructions on how
-	  to satisfy the build requirements of Rust support.
-
-	  In particular, the Makefile target 'rustavailable' is useful to check
-	  why the Rust toolchain is not being detected.
-
-config RUSTC_LLVM_VERSION
-	int
-	default $(rustc-llvm-version)
-
-config RUSTC_LLVM_MAJOR_VERSION
-	int
-	default $(shell,expr $(rustc-llvm-version) / 10000)
 
-config RUSTC_CLANG_LLVM_COMPATIBLE
-	bool
-	default y if CC_IS_CLANG && RUSTC_LLVM_MAJOR_VERSION = $(shell,expr $(cc-version) / 10000)
-	help
-	  This indicates whether Rust and Clang use LLVM of the same major
-	  version.
-
-	  Operations involving handling LLVM IR or bitcode (e.g. cross-language
-	  LTO) require the same LLVM major version to work properly. For best
-	  compatibility it is recommended that the exact same LLVM is used.
-
-config ARCH_HAS_CC_CAN_LINK
-	bool
-
-config CC_CAN_LINK
-	bool
-	default ARCH_CC_CAN_LINK if ARCH_HAS_CC_CAN_LINK
-	default $(cc_can_link_user,$(m64-flag)) if 64BIT
-	default $(cc_can_link_user,$(m32-flag))
-
-# Fixed in GCC 14, 13.3, 12.4 and 11.5
-# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113921
-config GCC_ASM_GOTO_OUTPUT_BROKEN
-	bool
-	depends on CC_IS_GCC
-	default y if GCC_VERSION < 110500
-	default y if GCC_VERSION >= 120000 && GCC_VERSION < 120400
-	default y if GCC_VERSION >= 130000 && GCC_VERSION < 130300
-
-config CC_HAS_ASM_GOTO_OUTPUT
-	def_bool y
-	depends on !GCC_ASM_GOTO_OUTPUT_BROKEN
-	depends on $(success,echo 'int foo(int x) { asm goto ("": "=r"(x) ::: bar); return x; bar: return 0; }' | $(CC) -x c - -c -o /dev/null)
-
-config CC_HAS_ASM_GOTO_TIED_OUTPUT
-	depends on CC_HAS_ASM_GOTO_OUTPUT
-	# Detect buggy gcc and clang, fixed in gcc-11 clang-14.
-	def_bool $(success,echo 'int foo(int *x) { asm goto (".long (%l[bar]) - .": "+m"(*x) ::: bar); return *x; bar: return 0; }' | $CC -x c - -c -o /dev/null)
-
-config TOOLS_SUPPORT_RELR
-	def_bool $(success,env "CC=$(CC)" "LD=$(LD)" "NM=$(NM)" "OBJCOPY=$(OBJCOPY)" $(srctree)/scripts/tools-support-relr.sh)
-
-config CC_HAS_ASM_INLINE
-	def_bool $(success,echo 'void foo(void) { asm inline (""); }' | $(CC) -x c - -c -o /dev/null)
-
-config CC_HAS_ASSUME
-	bool
-	# clang needs to be at least 19.1.0 since the meaning of the assume
-	# attribute changed:
-	# https://github.com/llvm/llvm-project/commit/c44fa3e8a9a44c2e9a575768a3c185354b9f6c17
-	default y if CC_IS_CLANG && CLANG_VERSION >= 190100
-	# supported since gcc 13.1.0
-	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106654
-	default y if CC_IS_GCC && GCC_VERSION >= 130100
-
-config CC_HAS_NO_PROFILE_FN_ATTR
-	def_bool $(success,echo '__attribute__((no_profile_instrument_function)) int x();' | $(CC) -x c - -c -o /dev/null -Werror)
-
-config CC_HAS_COUNTED_BY
-	bool
-	# clang needs to be at least 20.1.0 to avoid potential crashes
-	# when building structures that contain __counted_by
-	# https://github.com/ClangBuiltLinux/linux/issues/2114
-	# https://github.com/llvm/llvm-project/commit/160fb1121cdf703c3ef5e61fb26c5659eb581489
-	default y if CC_IS_CLANG && CLANG_VERSION >= 200100
-	# supported since gcc 15.1.0
-	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
-	default y if CC_IS_GCC && GCC_VERSION >= 150100
-
-config CC_HAS_COUNTED_BY_PTR
-	bool
-	# supported since clang 22
-	default y if CC_IS_CLANG && CLANG_VERSION >= 220100
-	# supported since gcc 16.0.0
-	default y if CC_IS_GCC && GCC_VERSION >= 160000
-
-config CC_HAS_BROKEN_COUNTED_BY_REF
-	bool
-	# https://github.com/llvm/llvm-project/issues/182575
-	default y if CC_IS_CLANG && CLANG_VERSION < 220100
-
-config CC_HAS_ALLOC_TOKEN
-	def_bool $(cc-option,-falloc-token-max=123)
-
-config CC_HAS_MULTIDIMENSIONAL_NONSTRING
-	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
-
-config LD_CAN_USE_KEEP_IN_OVERLAY
-	# ld.lld prior to 21.0.0 did not support KEEP within an overlay description
-	# https://github.com/llvm/llvm-project/pull/130661
-	def_bool LD_IS_BFD || LLD_VERSION >= 210000
-
-config RUSTC_HAS_SPAN_FILE
-	def_bool RUSTC_VERSION >= 108800
-
-config RUSTC_HAS_UNNECESSARY_TRANSMUTES
-	def_bool RUSTC_VERSION >= 108800
-
-config RUSTC_HAS_FILE_WITH_NUL
-	def_bool RUSTC_VERSION >= 108900
-
-config RUSTC_HAS_FILE_AS_C_STR
-	def_bool RUSTC_VERSION >= 109100
-
-config RUSTC_HAS_SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS
-	def_bool RUSTC_VERSION >= 109800
-
-config PAHOLE_VERSION
-	int
-	default "$(PAHOLE_VERSION)"
+source "init/Kconfig.toolchain"
 
 config CONSTRUCTORS
 	bool
init/Kconfig.toolchain new file +198 -0

198 lines not on this page · raw message

Signature · 1 line
2.55.0
#41 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 11 lines · Lorenzo Stoakes (ARM)

Move them into their own file, sourced from the top of init/Kconfig, so that the next commit can add to them without growing init/Kconfig further.

No functional change.

Assisted-by LLM
---
 init/Kconfig           | 197 +-----------------------------------------------
 init/Kconfig.toolchain | 198 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 196 deletions(-)

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

I defer to kbuild folks, though.

-Kees

Signature · 1 line
Kees Cook
#42 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 13 lines · Kees Cook
Quoted 11 lines · Lorenzo Stoakes (ARM)

Move them into their own file, sourced from the top of init/Kconfig, so that the next commit can add to them without growing init/Kconfig further.

No functional change.

Assisted-by LLM
---
 init/Kconfig           | 197 +-----------------------------------------------
 init/Kconfig.toolchain | 198 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 196 deletions(-)
Quoted 8 lines

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

I defer to kbuild folks, though.

We talked about this previously:

https://lore.kernel.org/aqPW1FsBVYHSWl1r@gremlin/

I do feel like scripts/ is a better location given that these are really things internal to Kbuild but I also see where Lorenzo is coming from that scripts/ is a little weird for this to live for discoverability, especially if we want people to put checks here instead of in a Makefile directly. To be honest, it would be kind of nice to separate the Kbuild parts of scripts into their own directory to make it clear what Kbuild uses versus what users/contributors should use but that is obviously too big of a project to tackle as a prerequisite for this.

Signature · 2 lines
Cheers,
Nathan
#43 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 27 lines · Nathan Chancellor
Quoted 13 lines · Kees Cook
Quoted 11 lines · Lorenzo Stoakes (ARM)

Move them into their own file, sourced from the top of init/Kconfig, so that the next commit can add to them without growing init/Kconfig further.

No functional change.

Assisted-by LLM
---
 init/Kconfig           | 197 +-----------------------------------------------
 init/Kconfig.toolchain | 198 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 196 deletions(-)
Quoted 8 lines

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

I defer to kbuild folks, though.

We talked about this previously:

https://lore.kernel.org/aqPW1FsBVYHSWl1r@gremlin/

Quoted 8 lines

I do feel like scripts/ is a better location given that these are really things internal to Kbuild but I also see where Lorenzo is coming from that scripts/ is a little weird for this to live for discoverability, especially if we want people to put checks here instead of in a Makefile directly. To be honest, it would be kind of nice to separate the Kbuild parts of scripts into their own directory to make it clear what Kbuild uses versus what users/contributors should use but that is obviously too big of a project to tackle as a prerequisite for this.

Yeah it just seemed really weird/surprising to me (in the sense of 'principle of least surprise') to put that in scripts/ and it doesn't seem that traditionally anything else like this lives there.

But if you guys feel strongly enough I can put it there.

And agreed probably a 'third place' is the right way, but probably not right as part of this series :)

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#44 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 37 lines · Lorenzo Stoakes (ARM)
Quoted 27 lines · Nathan Chancellor
Quoted 13 lines · Kees Cook
Quoted 11 lines · Lorenzo Stoakes (ARM)

Move them into their own file, sourced from the top of init/Kconfig, so that the next commit can add to them without growing init/Kconfig further.

No functional change.

Assisted-by LLM
---
 init/Kconfig           | 197 +-----------------------------------------------
 init/Kconfig.toolchain | 198 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 199 insertions(+), 196 deletions(-)
Quoted 8 lines

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

I defer to kbuild folks, though.

We talked about this previously:

https://lore.kernel.org/aqPW1FsBVYHSWl1r@gremlin/

Quoted 8 lines

I do feel like scripts/ is a better location given that these are really things internal to Kbuild but I also see where Lorenzo is coming from that scripts/ is a little weird for this to live for discoverability, especially if we want people to put checks here instead of in a Makefile directly. To be honest, it would be kind of nice to separate the Kbuild parts of scripts into their own directory to make it clear what Kbuild uses versus what users/contributors should use but that is obviously too big of a project to tackle as a prerequisite for this.

Quoted 8 lines

Yeah it just seemed really weird/surprising to me (in the sense of 'principle of least surprise') to put that in scripts/ and it doesn't seem that traditionally anything else like this lives there.

But if you guys feel strongly enough I can put it there.

And agreed probably a 'third place' is the right way, but probably not right as part of this series :)

yeah, then I'd also slightly favor scripts/ for now.

Kind regards,
Nicolas

#45 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 19 lines · Nicolas Schier
Quoted 18 lines · Lorenzo Stoakes (ARM)
Quoted 16 lines · Nathan Chancellor
Quoted 6 lines · Kees Cook

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

I do feel like scripts/ is a better location given that these are really things internal to Kbuild but I also see where Lorenzo is coming from that scripts/ is a little weird for this to live for discoverability, especially if we want people to put checks here instead of in a Makefile directly. To be honest, it would be kind of nice to separate the Kbuild parts of scripts into their own directory to make it clear what Kbuild uses versus what users/contributors should use but that is obviously too big of a project to tackle as a prerequisite for this.

Quoted 7 lines
Quoted 5 lines

Yeah it just seemed really weird/surprising to me (in the sense of 'principle of least surprise') to put that in scripts/ and it doesn't seem that traditionally anything else like this lives there.

But if you guys feel strongly enough I can put it there.

yeah, then I'd also slightly favor scripts/ for now.

Alright, I think scripts/Kconfig.toolchain wins then :)

Signature · 2 lines
Cheers,
Nathan
#46 lore raw

Re: [PATCH v3 10/20] kbuild: move the toolchain checks into init/Kconfig.toolchain

Quoted 24 lines · Nathan Chancellor
Quoted 23 lines · Nicolas Schier
Quoted 22 lines · Lorenzo Stoakes (ARM)
Quoted 8 lines · Nathan Chancellor
Quoted 6 lines · Kees Cook

Yeah, totally right to move to a separate file. I think, however, I would prefer this wasn't in init/ though. Kbuild uses scripts/ as its Makefile.$topic dumping ground, and Kconfig.include also lives there. To me, this new file should be scripts/Kconfig.toolchain instead. And arguably, this should be included by the top-level Kconfig rather than init/Kconfig...

Quoted 8 lines

I do feel like scripts/ is a better location given that these are really things internal to Kbuild but I also see where Lorenzo is coming from that scripts/ is a little weird for this to live for discoverability, especially if we want people to put checks here instead of in a Makefile directly. To be honest, it would be kind of nice to separate the Kbuild parts of scripts into their own directory to make it clear what Kbuild uses versus what users/contributors should use but that is obviously too big of a project to tackle as a prerequisite for this.

Yeah it just seemed really weird/surprising to me (in the sense of 'principle of least surprise') to put that in scripts/ and it doesn't seem that traditionally anything else like this lives there.

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

But if you guys feel strongly enough I can put it there.

yeah, then I'd also slightly favor scripts/ for now.

Alright, I think scripts/Kconfig.toolchain wins then :)

Ack, will switch it out for v4!

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#47 lore raw

PATCH v3 11/20 kbuild: avoid re-running compiler and linker probes

In reply to Lorenzo Stoakes (ARM)

Each kernel make invocation begins with ~30 compiler and linker runs each of which performs duplicate probe for a number of compiler and linker options.

This is useless work - the compiler and its version is known, so use these to determine which options are available, once.

A convention already exists for this - CC_HAS_xxx, LD_HAS_xxx in Kconfig files (for example, CC_HAS_COUNTED_BY), so convert these probes to Kconfig options where appropriate.

This change avoids a subtle issue with ppc32 (big endian) - clang doesn't accept -fno-stack-clash-protection on this sub-target, so keep this option in the Makefile.

With gcc and clang, defconfig and allmodconfig, the recorded command lines are unchanged, a build with nothing to do rebuilds nothing and W=1 continues to function correctly.

Doing this improves all builds, but has a particularly positive impact on no-op builds (builds where nothing has changed).

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, no-op make, gcc           0.78s    0.60s    -0.18s (-23%)
  x86 defconfig, no-op make, clang         0.94s    0.66s    -0.28s (-30%)
  x86 defconfig, touch mm/vma.c, gcc        8.6s     8.5s    -0.16s (-2%)
  x86 defconfig, touch mm/vma.c, clang      8.0s     7.7s    -0.24s (-3%)
  x86 defconfig, clean, clang              29.8s    29.4s    -0.37s (-1%)
  x86 allmodconfig, no-op make, gcc        12.9s    12.7s    -0.23s (-2%)
  x86 allmodconfig, no-op make, clang      14.2s    13.9s    -0.29s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  32.2s    31.9s    -0.30s (-1%)
Assisted-by LLM
---
 Makefile                              | 23 +++++------
 arch/arm64/kernel/pi/Makefile         |  2 +-
 arch/riscv/kernel/pi/Makefile         |  2 +-
 arch/x86/Kconfig                      | 17 ++++++++
 arch/x86/Makefile                     | 12 +++---
 drivers/firmware/efi/libstub/Makefile |  2 +-
 init/Kconfig.toolchain                | 74 +++++++++++++++++++++++++++++++++++
 scripts/Makefile.warn                 | 28 ++++++-------
 8 files changed, 126 insertions(+), 34 deletions(-)
Makefile +12 -11
index 8105123bcf4d..68df3446d111 100644
@@ -946,8 +946,8 @@ KBUILD_RUSTFLAGS += -Coverflow-checks=$(if $(CONFIG_RUST_OVERFLOW_CHECKS),y,n)
 ifdef CONFIG_CC_IS_GCC
 # gcc-10 renamed --param=allow-store-data-races=0 to
 # -fno-allow-store-data-races.
-KBUILD_CFLAGS	+= $(call cc-option,--param=allow-store-data-races=0)
-KBUILD_CFLAGS	+= $(call cc-option,-fno-allow-store-data-races)
+KBUILD_CFLAGS	+= $(if $(CONFIG_CC_HAS_ALLOW_STORE_DATA_RACES_PARAM),--param=allow-store-data-races=0)
+KBUILD_CFLAGS	+= $(if $(CONFIG_CC_HAS_NO_ALLOW_STORE_DATA_RACES),-fno-allow-store-data-races)
 endif
 
 ifdef CONFIG_READABLE_ASM
@@ -1011,18 +1011,20 @@ endif
 endif
 
 # Explicitly clear padding bits during variable initialization
-KBUILD_CFLAGS += $(call cc-option,-fzero-init-padding-bits=all)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_ZERO_INIT_PADDING_BITS),-fzero-init-padding-bits=all)
 
 # While VLAs have been removed, GCC produces unreachable stack probes
 # for the randomize_kstack_offset feature. Disable it for all compilers.
+# Probed here rather than in Kconfig as clang only accepts it for some
+# sub-targets, so the architecture's flags matter.
 KBUILD_CFLAGS	+= $(call cc-option, -fno-stack-clash-protection)
 
 # Get details on warnings generated due to GCC value tracking.
-KBUILD_CFLAGS	+= $(call cc-option, -fdiagnostics-show-context=2)
+KBUILD_CFLAGS	+= $(if $(CONFIG_CC_HAS_DIAGNOSTICS_SHOW_CONTEXT),-fdiagnostics-show-context=2)
 
 # Show inlining notes for __attribute__((warning/error)) call chains.
 # GCC supports this unconditionally while Clang 23+ provides a flag.
-KBUILD_CFLAGS	+= $(call cc-option, -fdiagnostics-show-inlining-chain)
+KBUILD_CFLAGS	+= $(if $(CONFIG_CC_HAS_DIAGNOSTICS_SHOW_INLINING_CHAIN),-fdiagnostics-show-inlining-chain)
 
 # Clear used registers at func exit (to reduce data lifetime and ROP gadgets).
 ifdef CONFIG_ZERO_CALL_USED_REGS
@@ -1033,7 +1035,7 @@ ifdef CONFIG_FUNCTION_TRACER
 ifdef CONFIG_FTRACE_MCOUNT_USE_CC
   CC_FLAGS_FTRACE	+= -mrecord-mcount
   ifdef CONFIG_HAVE_NOP_MCOUNT
-    ifeq ($(call cc-option-yn, -mnop-mcount),y)
+    ifdef CONFIG_CC_HAS_MNOP_MCOUNT
       CC_FLAGS_FTRACE	+= -mnop-mcount
       CC_FLAGS_USING	+= -DCC_USING_NOP_MCOUNT
     endif
@@ -1051,8 +1053,7 @@ ifdef CONFIG_FTRACE_MCOUNT_USE_RECORDMCOUNT
   endif
 endif
 ifdef CONFIG_HAVE_FENTRY
-  # s390-linux-gnu-gcc did not support -mfentry until gcc-9.
-  ifeq ($(call cc-option-yn, -mfentry),y)
+  ifdef CONFIG_CC_HAS_MFENTRY
     CC_FLAGS_FTRACE	+= -mfentry
     CC_FLAGS_USING	+= -DCC_USING_FENTRY
   endif
@@ -1160,7 +1161,7 @@ NOSTDINC_FLAGS += -nostdinc
 # the kernel uses only C99 flexible arrays for dynamically sized trailing
 # arrays. Enforce this for everything that may examine structure sizes and
 # perform bounds checking.
-KBUILD_CFLAGS += $(call cc-option, -fstrict-flex-arrays=3)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_STRICT_FLEX_ARRAYS),-fstrict-flex-arrays=3)
 
 # disable invalid "can't wrap" optimizations for signed / pointers
 KBUILD_CFLAGS	+= -fno-strict-overflow
@@ -1240,11 +1241,11 @@ LDFLAGS_vmlinux += --build-id=sha1
 # COMDAT-deduplicated sections. Use --force-group-allocation to resolve these
 # groups when linking modules. The option is available from ld.bfd 2.29 and
 # ld.lld 19.1.0.
-KBUILD_LDFLAGS_MODULE += $(call ld-option,--force-group-allocation)
+KBUILD_LDFLAGS_MODULE += $(if $(CONFIG_LD_HAS_FORCE_GROUP_ALLOCATION),--force-group-allocation)
 
 KBUILD_LDFLAGS	+= -z noexecstack
 ifeq ($(CONFIG_LD_IS_BFD),y)
-KBUILD_LDFLAGS	+= $(call ld-option,--no-warn-rwx-segments)
+KBUILD_LDFLAGS	+= $(if $(CONFIG_LD_HAS_NO_WARN_RWX_SEGMENTS),--no-warn-rwx-segments)
 endif
 
 ifeq ($(CONFIG_STRIP_ASM_SYMS),y)
arch/arm64/kernel/pi/Makefile +1 -1
index be92d73c25b2..5aa8dffe492b 100644
@@ -9,7 +9,7 @@ KBUILD_CFLAGS	:= $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) -fpie \
 		   -include $(srctree)/include/linux/hidden.h \
 		   -D__DISABLE_EXPORTS -ffreestanding -D__NO_FORTIFY \
 		   -fno-asynchronous-unwind-tables -fno-unwind-tables \
-		   $(call cc-option,-fno-addrsig)
+		   $(if $(CONFIG_CC_HAS_NO_ADDRSIG),-fno-addrsig)
 
 # this code may run with the MMU off so disable unaligned accesses
 CFLAGS_map_range.o += -mstrict-align
arch/riscv/kernel/pi/Makefile +1 -1
index bc098edac898..e0ed7ca7e347 100644
@@ -8,7 +8,7 @@ KBUILD_CFLAGS	:= $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) -fpie \
 		   -include $(srctree)/include/linux/hidden.h \
 		   -D__DISABLE_EXPORTS -ffreestanding \
 		   -fno-asynchronous-unwind-tables -fno-unwind-tables \
-		   $(call cc-option,-fno-addrsig)
+		   $(if $(CONFIG_CC_HAS_NO_ADDRSIG),-fno-addrsig)
 
 # Disable LTO
 KBUILD_CFLAGS	:= $(filter-out $(CC_FLAGS_LTO), $(KBUILD_CFLAGS))
arch/x86/Kconfig +17 -0
index 15fd9ec5ecac..be0624fee27a 100644
@@ -2364,6 +2364,23 @@ config CC_HAS_KCFI_ARITY
 	def_bool $(cc-option,-fsanitize=kcfi -fsanitize-kcfi-arity)
 	depends on CC_IS_CLANG && !RUST
 
+config CC_HAS_INDIRECT_BRANCH_CS_PREFIX
+	def_bool $(cc-option,-mindirect-branch-cs-prefix)
+
+config CC_HAS_CF_PROTECTION_NONE
+	def_bool $(cc-option,-fcf-protection=none)
+
+# with jump tables off: the compilers use NOTRACK for them, which kernel IBT
+# does not allow
+config CC_HAS_CF_PROTECTION_BRANCH
+	def_bool $(cc-option,-fcf-protection=branch -fno-jump-tables)
+
+config CC_HAS_FALIGN_JUMPS
+	def_bool $(cc-option,-falign-jumps=1)
+
+config CC_HAS_FALIGN_LOOPS
+	def_bool $(cc-option,-falign-loops=1)
+
 config FUNCTION_PADDING_CFI
 	int
 	default 59 if FUNCTION_ALIGNMENT_64B
arch/x86/Makefile +6 -6
index 598f178102ee..29bb515df9f6 100644
@@ -20,7 +20,7 @@ ifdef CONFIG_CC_IS_CLANG
 RETPOLINE_CFLAGS	:= -mretpoline-external-thunk
 RETPOLINE_VDSO_CFLAGS	:= -mretpoline
 endif
-RETPOLINE_CFLAGS	+= $(call cc-option,-mindirect-branch-cs-prefix)
+RETPOLINE_CFLAGS	+= $(if $(CONFIG_CC_HAS_INDIRECT_BRANCH_CS_PREFIX),-mindirect-branch-cs-prefix)
 
 ifdef CONFIG_MITIGATION_RETHUNK
 RETHUNK_CFLAGS		:= -mfunction-return=thunk-extern
@@ -52,7 +52,7 @@ REALMODE_CFLAGS	:= $(CC_FLAGS_DIALECT) -m16 -g -Os \
 		   -DDISABLE_BRANCH_PROFILING -D__DISABLE_EXPORTS \
 		   -Wall -Wstrict-prototypes -march=i386 -mregparm=3 \
 		   -fno-strict-aliasing -fomit-frame-pointer -fno-pic \
-		   -mno-mmx -mno-sse $(call cc-option,-fcf-protection=none)
+		   -mno-mmx -mno-sse $(if $(CONFIG_CC_HAS_CF_PROTECTION_NONE),-fcf-protection=none)
 
 REALMODE_CFLAGS += -ffreestanding
 REALMODE_CFLAGS += -fno-stack-protector
@@ -99,10 +99,10 @@ ifeq ($(CONFIG_X86_KERNEL_IBT),y)
 #
 #   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104816
 #
-KBUILD_CFLAGS += $(call cc-option,-fcf-protection=branch -fno-jump-tables)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_CF_PROTECTION_BRANCH),-fcf-protection=branch -fno-jump-tables)
 KBUILD_RUSTFLAGS += -Zcf-protection=branch $(if $(call rustc-min-version,109300),-Cjump-tables=n,-Zno-jump-tables)
 else
-KBUILD_CFLAGS += $(call cc-option,-fcf-protection=none)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_CF_PROTECTION_NONE),-fcf-protection=none)
 endif
 
 ifeq ($(CONFIG_X86_32),y)
@@ -138,10 +138,10 @@ else
         KBUILD_CFLAGS += -m64
 
         # Align jump targets to 1 byte, not the default 16 bytes:
-        KBUILD_CFLAGS += $(call cc-option,-falign-jumps=1)
+        KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_FALIGN_JUMPS),-falign-jumps=1)
 
         # Pack loops tightly as well:
-        KBUILD_CFLAGS += $(call cc-option,-falign-loops=1)
+        KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_FALIGN_LOOPS),-falign-loops=1)
 
         # Don't autogenerate traditional x87 instructions
         KBUILD_CFLAGS += -mno-80387
drivers/firmware/efi/libstub/Makefile +1 -1
index 77a2b2d74f3f..80058bbddaf5 100644
@@ -40,7 +40,7 @@ KBUILD_CFLAGS			:= $(subst $(CC_FLAGS_FTRACE),,$(cflags-y)) \
 				   -D__NO_FORTIFY \
 				   -ffreestanding \
 				   -fno-stack-protector \
-				   $(call cc-option,-fno-addrsig) \
+				   $(if $(CONFIG_CC_HAS_NO_ADDRSIG),-fno-addrsig) \
 				   -D__DISABLE_EXPORTS
 
 #
init/Kconfig.toolchain +74 -0

80 lines not on this page · raw message

scripts/Makefile.warn +14 -14
index 35af7d6c6d18..83d274fcbfaf 100644
@@ -17,7 +17,7 @@ KBUILD_CFLAGS += -Werror=strict-prototypes
 KBUILD_CFLAGS += -Wno-format-security
 KBUILD_CFLAGS += -Wno-trigraphs
 KBUILD_CFLAGS += -Wno-frame-address
-KBUILD_CFLAGS += $(call cc-option, -Wno-address-of-packed-member)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_ADDRESS_OF_PACKED_MEMBER),-Wno-address-of-packed-member)
 KBUILD_CFLAGS += -Wmissing-declarations
 KBUILD_CFLAGS += -Wmissing-prototypes
 
@@ -30,8 +30,8 @@ KBUILD_CFLAGS-$(CONFIG_CC_NO_ARRAY_BOUNDS) += -Wno-array-bounds
 ifdef CONFIG_CC_IS_CLANG
 # Clang checks for overflow/truncation with '%p', while GCC does not:
 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111219
-KBUILD_CFLAGS += $(call cc-option, -Wno-format-overflow-non-kprintf)
-KBUILD_CFLAGS += $(call cc-option, -Wno-format-truncation-non-kprintf)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_FORMAT_OVERFLOW_NON_KPRINTF),-Wno-format-overflow-non-kprintf)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_FORMAT_TRUNCATION_NON_KPRINTF),-Wno-format-truncation-non-kprintf)
 
 # Clang may emit a warning when a const variable, such as the dummy variables
 # in typecheck(), or const member of an aggregate type are not initialized,
@@ -43,7 +43,7 @@ KBUILD_CFLAGS += $(call cc-option, -Wno-format-truncation-non-kprintf)
 # disabled with this same switch, there should not be too much coverage lost
 # because -Wuninitialized will still flag when an uninitialized const variable
 # is used.
-KBUILD_CFLAGS += $(call cc-option, -Wno-default-const-init-unsafe)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_DEFAULT_CONST_INIT_UNSAFE),-Wno-default-const-init-unsafe)
 else
 
 # gcc inanely warns about local variables called 'main'
@@ -54,7 +54,7 @@ endif
 KBUILD_CFLAGS += -Wno-type-limits
 
 # These result in bogus false positives
-KBUILD_CFLAGS += $(call cc-option, -Wno-dangling-pointer)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_DANGLING_POINTER),-Wno-dangling-pointer)
 
 # Stack Variable Length Arrays (VLAs) must not be used in the kernel.
 # Function array parameters should, however, be usable, but -Wvla will
@@ -62,7 +62,7 @@ KBUILD_CFLAGS += $(call cc-option, -Wno-dangling-pointer)
 # types, so depend on GCC for now to keep stack VLAs out of the tree.
 # https://github.com/llvm/llvm-project/issues/57098
 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98217
-KBUILD_CFLAGS += $(call cc-option,-Wvla-larger-than=1)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WVLA_LARGER_THAN),-Wvla-larger-than=1)
 
 # disable pointer signed / unsigned warnings in gcc 4.0
 KBUILD_CFLAGS += -Wno-pointer-sign
@@ -73,11 +73,11 @@ KBUILD_CFLAGS += -Wno-pointer-sign
 KBUILD_CFLAGS += -Wcast-function-type
 
 # Currently, disable -Wstringop-overflow for GCC 11, globally.
-KBUILD_CFLAGS-$(CONFIG_CC_NO_STRINGOP_OVERFLOW) += $(call cc-option, -Wno-stringop-overflow)
-KBUILD_CFLAGS-$(CONFIG_CC_STRINGOP_OVERFLOW) += $(call cc-option, -Wstringop-overflow)
+KBUILD_CFLAGS-$(CONFIG_CC_NO_STRINGOP_OVERFLOW) += $(if $(CONFIG_CC_HAS_WSTRINGOP_OVERFLOW),-Wno-stringop-overflow)
+KBUILD_CFLAGS-$(CONFIG_CC_STRINGOP_OVERFLOW) += $(if $(CONFIG_CC_HAS_WSTRINGOP_OVERFLOW),-Wstringop-overflow)
 
 # Currently, disable -Wunterminated-string-initialization as broken
-KBUILD_CFLAGS += $(call cc-option, -Wno-unterminated-string-initialization)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_UNTERMINATED_STRING_INITIALIZATION),-Wno-unterminated-string-initialization)
 
 # The allocators already balk at large sizes, so silence the compiler
 # warnings for bounds checks involving those possible values. While
@@ -100,10 +100,10 @@ KBUILD_CFLAGS += -Werror=date-time
 KBUILD_CFLAGS += -Werror=incompatible-pointer-types
 
 # Require designated initializers for all marked structures
-KBUILD_CFLAGS += $(call cc-option,-Werror=designated-init)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WERROR_DESIGNATED_INIT),-Werror=designated-init)
 
 # Warn if there is an enum types mismatch
-KBUILD_CFLAGS += $(call cc-option,-Wenum-conversion)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WENUM_CONVERSION),-Wenum-conversion)
 
 KBUILD_CFLAGS += -Wunused
 
@@ -125,12 +125,12 @@ else
 # Suppress them by using -Wno... except for W=1.
 KBUILD_CFLAGS += -Wno-unused-but-set-variable
 KBUILD_CFLAGS += -Wno-unused-const-variable
-KBUILD_CFLAGS += $(call cc-option, -Wno-packed-not-aligned)
-KBUILD_CFLAGS += $(call cc-option, -Wno-format-overflow)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_PACKED_NOT_ALIGNED),-Wno-packed-not-aligned)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_FORMAT_OVERFLOW),-Wno-format-overflow)
 ifdef CONFIG_CC_IS_GCC
 KBUILD_CFLAGS += -Wno-format-truncation
 endif
-KBUILD_CFLAGS += $(call cc-option, -Wno-stringop-truncation)
+KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_WNO_STRINGOP_TRUNCATION),-Wno-stringop-truncation)
 
 KBUILD_CFLAGS += -Wno-override-init # alias for -Wno-initializer-overrides in clang
 
Signature · 1 line
2.55.0
#48 lore raw

Re: [PATCH v3 11/20] kbuild: avoid re-running compiler and linker probes

Quoted 10 lines · Lorenzo Stoakes (ARM)

Each kernel make invocation begins with ~30 compiler and linker runs each of which performs duplicate probe for a number of compiler and linker options.

This is useless work - the compiler and its version is known, so use these to determine which options are available, once.

A convention already exists for this - CC_HAS_xxx, LD_HAS_xxx in Kconfig files (for example, CC_HAS_COUNTED_BY), so convert these probes to Kconfig options where appropriate.

Yeah, I agree about the rationale here.

It does, however, now drive a long-time annoyance of mine to the top of
mind: the repetition of the compiler command-line options in two places:
the Kconfig and the Makefile. I dislike that pattern so much that I really really worked hard to use cc-option instead where ever I possibly could (though it continued to add to my growing concern about the repetition of running those checks all the time, so I'm motivated to see something like what you have here actually land).

But I would really like to find a way to avoid the duplication. It's fragile and it's weird and it's split across 2 files that don't always have an obvious relationship. I really don't like it. And with it being used for things that are "detected" (i.e. not part of always required builds), that fragility means typos may go unnoticed, etc.

We've had a need for some kind of kconfig "append to a list" logic that we've been working around in places, e.g. include/linux/lsm_count.h for how "count the list of enabled LSMs" got dealt with. If we could have had:

config LSM_LIST
list
separator " "

config SECURITY_SELINUX

	...
	append_to LSM_LIST
	...

We could just parse CONFIG_LSM_LIST directly. And I think we can do the same with this:

config CC_OPTION_LIST
list
separator " "

config CC_OPTION_ZERO_INIT_PADDING_BITS

	string
	default "$(cc-option-bit,-fzero-init-padding-bits=all)"
	append_to CC_OPTION_LIST

And the dump all of it into the Makefile in one via CONFIG_CC_OPTION_LIST

(And we'd need to implement ld-option-bit. Though really I think cc-option-bit should be renamed to cc-option-str or something)

But even without the new "list" Kconfig type, it'd be nicer to use the cc-option-bit string default method and dump all the newly created CC_OPTION_... strings into the makefile manually. The "append_to" idea could be a follow-up.

-Kees

Signature · 1 line
Kees Cook
#49 lore raw

Re: [PATCH v3 11/20] kbuild: avoid re-running compiler and linker probes

Quoted 56 lines · Kees Cook
Quoted 10 lines · Lorenzo Stoakes (ARM)

Each kernel make invocation begins with ~30 compiler and linker runs each of which performs duplicate probe for a number of compiler and linker options.

This is useless work - the compiler and its version is known, so use these to determine which options are available, once.

A convention already exists for this - CC_HAS_xxx, LD_HAS_xxx in Kconfig files (for example, CC_HAS_COUNTED_BY), so convert these probes to Kconfig options where appropriate.

Yeah, I agree about the rationale here.

It does, however, now drive a long-time annoyance of mine to the top of
mind: the repetition of the compiler command-line options in two places:
the Kconfig and the Makefile. I dislike that pattern so much that I really really worked hard to use cc-option instead where ever I possibly could (though it continued to add to my growing concern about the repetition of running those checks all the time, so I'm motivated to see something like what you have here actually land).

But I would really like to find a way to avoid the duplication. It's fragile and it's weird and it's split across 2 files that don't always have an obvious relationship. I really don't like it. And with it being used for things that are "detected" (i.e. not part of always required builds), that fragility means typos may go unnoticed, etc.

We've had a need for some kind of kconfig "append to a list" logic that we've been working around in places, e.g. include/linux/lsm_count.h for how "count the list of enabled LSMs" got dealt with. If we could have had:

config LSM_LIST
list
separator " "

config SECURITY_SELINUX

	...
	append_to LSM_LIST
	...

We could just parse CONFIG_LSM_LIST directly. And I think we can do the same with this:

config CC_OPTION_LIST
list
separator " "

config CC_OPTION_ZERO_INIT_PADDING_BITS

	string
	default "$(cc-option-bit,-fzero-init-padding-bits=all)"
	append_to CC_OPTION_LIST

And the dump all of it into the Makefile in one via CONFIG_CC_OPTION_LIST

Quoted 7 lines

(And we'd need to implement ld-option-bit. Though really I think cc-option-bit should be renamed to cc-option-str or something)

But even without the new "list" Kconfig type, it'd be nicer to use the cc-option-bit string default method and dump all the newly created CC_OPTION_... strings into the makefile manually. The "append_to" idea could be a follow-up.

While we could certainly try to cook something like this up, we could also avoid the split across two files by just defining the flags in Kconfig directly and using them in the Makefile through their symbol, like we already do for -Wimplicit-fallthrough. For example, instead of

  config CC_HAS_STRICT_FLEX_ARRAYS
      def_bool $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_STRICT_FLEX_ARRAYS),-fstrict-flex-arrays=3)

We would just do

  config CC_STRICT_FLEX_ARRAYS
      string
      default "-fstrict-flex-arrays=3" if $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(CONFIG_CC_STRICT_FLEX_ARRAYS)

While we still get the duplication (and we could look at getting rid of it with your cc-option-str idea or whatever), it is at least contained to the same location, so out of sync issues should be much rarer. I do diff Kconfigs so this might make certain issues with checks a little bit more obvious if something changes on the compiler side.

Signature · 2 lines
Cheers,
Nathan
#50 lore raw

Re: [PATCH v3 11/20] kbuild: avoid re-running compiler and linker probes

Quoted 18 lines · Nathan Chancellor

While we could certainly try to cook something like this up, we could also avoid the split across two files by just defining the flags in Kconfig directly and using them in the Makefile through their symbol, like we already do for -Wimplicit-fallthrough. For example, instead of

  config CC_HAS_STRICT_FLEX_ARRAYS
      def_bool $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_STRICT_FLEX_ARRAYS),-fstrict-flex-arrays=3)

We would just do

  config CC_STRICT_FLEX_ARRAYS
      string
      default "-fstrict-flex-arrays=3" if $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(CONFIG_CC_STRICT_FLEX_ARRAYS)
Quoted 5 lines

While we still get the duplication (and we could look at getting rid of it with your cc-option-str idea or whatever), it is at least contained to the same location, so out of sync issues should be much rarer. I do diff Kconfigs so this might make certain issues with checks a little bit more obvious if something changes on the compiler side.

Yeah, and note that cc-option-bit already exists. It's just a weird name is all and there isn't an ld-option-bit.

As for naming conventions, I think "CC_OPT_" would be a good prefix. And this works today with no change:

config CC_OPT_STRICT_FLEX_ARRAYS

	string
	default "$(cc-option-bit,-fstrict-flex-arrays=3)"

(do we need "def_string" now?)

Signature · 1 line
Kees Cook
#51 lore raw

Re: [PATCH v3 11/20] kbuild: avoid re-running compiler and linker probes

Quoted 19 lines · Kees Cook
Quoted 18 lines · Nathan Chancellor

While we could certainly try to cook something like this up, we could also avoid the split across two files by just defining the flags in Kconfig directly and using them in the Makefile through their symbol, like we already do for -Wimplicit-fallthrough. For example, instead of

  config CC_HAS_STRICT_FLEX_ARRAYS
      def_bool $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_STRICT_FLEX_ARRAYS),-fstrict-flex-arrays=3)

We would just do

  config CC_STRICT_FLEX_ARRAYS
      string
      default "-fstrict-flex-arrays=3" if $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(CONFIG_CC_STRICT_FLEX_ARRAYS)
Quoted 8 lines
Quoted 5 lines

While we still get the duplication (and we could look at getting rid of it with your cc-option-str idea or whatever), it is at least contained to the same location, so out of sync issues should be much rarer. I do diff Kconfigs so this might make certain issues with checks a little bit more obvious if something changes on the compiler side.

Yeah, and note that cc-option-bit already exists. It's just a weird name is all and there isn't an ld-option-bit.

Ah, I see. I worry that the current cc-option-bit is not sufficient for all options that we may want to test because it uses '-E' to stop after preprocessing (whereas some options may need to get to code generation to be validated properly) and it does not use $(CLANG_FLAGS) to properly set the target (so we might not get consistent results). I wonder if we would be better off refactoring cc-option-bit into cc-option-str that shares most of the machinery of cc-option. Then we could just add ld-option-str.

Quoted 6 lines

As for naming conventions, I think "CC_OPT_" would be a good prefix. And this works today with no change:

config CC_OPT_STRICT_FLEX_ARRAYS

	string
	default "$(cc-option-bit,-fstrict-flex-arrays=3)"

This does look pretty nice.

Quoted 1 line

(do we need "def_string" now?)

def_string would certainly make these even nicer.

Signature · 2 lines
Cheers,
Nathan
#52 lore raw

Re: [PATCH v3 11/20] kbuild: avoid re-running compiler and linker probes

Quoted 45 lines · Nathan Chancellor
Quoted 19 lines · Kees Cook
Quoted 18 lines · Nathan Chancellor

While we could certainly try to cook something like this up, we could also avoid the split across two files by just defining the flags in Kconfig directly and using them in the Makefile through their symbol, like we already do for -Wimplicit-fallthrough. For example, instead of

  config CC_HAS_STRICT_FLEX_ARRAYS
      def_bool $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(if $(CONFIG_CC_HAS_STRICT_FLEX_ARRAYS),-fstrict-flex-arrays=3)

We would just do

  config CC_STRICT_FLEX_ARRAYS
      string
      default "-fstrict-flex-arrays=3" if $(cc-option,-fstrict-flex-arrays=3)

  KBUILD_CFLAGS += $(CONFIG_CC_STRICT_FLEX_ARRAYS)
Quoted 8 lines
Quoted 5 lines

While we still get the duplication (and we could look at getting rid of it with your cc-option-str idea or whatever), it is at least contained to the same location, so out of sync issues should be much rarer. I do diff Kconfigs so this might make certain issues with checks a little bit more obvious if something changes on the compiler side.

Yeah, and note that cc-option-bit already exists. It's just a weird name is all and there isn't an ld-option-bit.

Ah, I see. I worry that the current cc-option-bit is not sufficient for all options that we may want to test because it uses '-E' to stop after preprocessing (whereas some options may need to get to code generation to be validated properly) and it does not use $(CLANG_FLAGS) to properly set the target (so we might not get consistent results). I wonder if we would be better off refactoring cc-option-bit into cc-option-str that shares most of the machinery of cc-option. Then we could just add ld-option-str.

Quoted 6 lines

As for naming conventions, I think "CC_OPT_" would be a good prefix. And this works today with no change:

config CC_OPT_STRICT_FLEX_ARRAYS

	string
	default "$(cc-option-bit,-fstrict-flex-arrays=3)"
Quoted 5 lines

This does look pretty nice.

Quoted 1 line

(do we need "def_string" now?)

def_string would certainly make these even nicer.

Agreed :)

Done for v4 (which now cites Kees's series as a dependency and hopefully will sit in the kbuild tree soon, maybe after 36d4a11b56aa?).

26/29 probes use cc-option-str, there were a few that had other conditionals but nice conversion in general!

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#53 lore raw

PATCH v3 12/20 modpost: cache section relocation mismatch state

In reply to Lorenzo Stoakes (ARM)

For every relocation modpost invokes check_section_mismatch() to determine whether there is any kind of mismatch between the source and destination, and if so which classification applies.

Each time it does this it invokes section_mismatch() which iterates through the sectioncheck[] array every time it's called.

When walked a relocation section the source is fixed and there aren't many targets, so the same names are looked up over and over again.

Therefore cache not only mismatch categorisation but also whether a mismatch even exists for a given section and look up the sections in the cache.

Special indices (undefined, absolute, common) take the uncached path as before.

This results in very significant speed ups for allmodconfig incremental builds.

modpost is on the serial tail of every build that links vmlinux.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        8.5s     8.3s    -0.14s (-2%)
  x86 defconfig, touch mm/vma.c, clang      7.7s     7.6s    -0.13s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    33.9s    29.4s     -4.5s (-13%)
  x86 allmodconfig, touch mm/vma.c, clang  31.9s    27.9s     -4.0s (-13%)
Assisted-by LLM
---
 scripts/mod/modpost.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 64 insertions(+), 2 deletions(-)
scripts/mod/modpost.c +64 -2
index 75374c64b8cc..0fd43c8a89ea 100644
@@ -1155,12 +1155,67 @@ static void check_export_symbol(struct module *mod, struct elf_info *elf,
 			 name);
 }
 
+/*
+ * mismatch_cache[section index] ->
+ *   0 - uncached.
+ *  -1 - no mismatch.
+ *  >0 - mismatch index + 1.
+ */
+static int *mismatch_cache;
+
+static void init_mismatch_cache(unsigned int num_sections)
+{
+	mismatch_cache = xcalloc(num_sections, sizeof(*mismatch_cache));
+}
+
+static void reset_mismatch_cache(unsigned int num_sections)
+{
+	memset(mismatch_cache, 0, num_sections * sizeof(*mismatch_cache));
+}
+
+static void free_mismatch_cache(void)
+{
+	free(mismatch_cache);
+	mismatch_cache = NULL;
+}
+
+static const struct sectioncheck
+*cache_mismatch(unsigned int secndx, const struct sectioncheck *mismatch)
+{
+	if (!mismatch) {
+		mismatch_cache[secndx] = -1;
+		return NULL;
+	}
+
+	mismatch_cache[secndx] = (mismatch - sectioncheck) + 1;
+	return mismatch;
+}
+
+static const struct sectioncheck *get_section_mismatch(const char *fromsec,
+		const struct elf_info *elf, unsigned int secndx)
+{
+	int cached;
+
+	if (secndx >= elf->num_sections)
+		return section_mismatch(fromsec, sec_name(elf, secndx));
+
+	cached = mismatch_cache[secndx];
+	if (cached < 0)
+		return NULL;
+	if (cached > 0)
+		return &sectioncheck[cached - 1];
+
+	return cache_mismatch(secndx,
+			      section_mismatch(fromsec, sec_name(elf, secndx)));
+}
+
 static void check_section_mismatch(struct module *mod, struct elf_info *elf,
 				   Elf_Sym *sym,
 				   unsigned int fsecndx, const char *fromsec,
 				   Elf_Addr faddr, Elf_Addr taddr)
 {
-	const char *tosec = sec_name(elf, get_secindex(elf, sym));
+	const unsigned int to_secndx = get_secindex(elf, sym);
+	const char *tosec = sec_name(elf, to_secndx);
 	const struct sectioncheck *mismatch;
 
 	if (module_enabled && elf->export_symbol_secndx == fsecndx) {
@@ -1168,7 +1223,7 @@ static void check_section_mismatch(struct module *mod, struct elf_info *elf,
 		return;
 	}
 
-	mismatch = section_mismatch(fromsec, tosec);
+	mismatch = get_section_mismatch(fromsec, elf, to_secndx);
 	if (!mismatch)
 		return;
 
@@ -1445,6 +1500,8 @@ static void check_sec_ref(struct module *mod, struct elf_info *elf)
 {
 	int i;
 
+	init_mismatch_cache(elf->num_sections);
+
 	/* Walk through all sections */
 	for (i = 0; i < elf->num_sections; i++) {
 		Elf_Shdr *sechdr = &elf->sechdrs[i];
@@ -1461,6 +1518,9 @@ static void check_sec_ref(struct module *mod, struct elf_info *elf)
 			if (match(secname, section_white_list))
 				continue;
 
+			/* Reset cache per-section. */
+			reset_mismatch_cache(elf->num_sections);
+
 			start = sym_get_data_by_offset(elf, i, 0);
 			stop = start + sechdr->sh_size;
 
@@ -1472,6 +1532,8 @@ static void check_sec_ref(struct module *mod, struct elf_info *elf)
 					    start, stop);
 		}
 	}
+
+	free_mismatch_cache();
 }
 
 static char *remove_dot(char *s)
Signature · 1 line
2.55.0
#54 lore raw

PATCH v3 13/20 modpost: emit module descriptors as assembly

In reply to Lorenzo Stoakes (ARM)

modpost generates a descriptor for every module in the form of a <module>.mod.c file with .modinfo strings, the __this_module descriptor, exported symbol tables and (with CONFIG_MODVERSIONS set), the CRC of imported symbols.

These files are compiled like any other kernel C file with all of the -include preamble, as well as including linux/module.h, header dependencies generated by fixdep of a few hundred headers, an objtool run and if LTO is being performed, a link is performed to generate native code.

On an x86-64 allmodconfig build 11,189 *.mod.c files are built, each taking ~0.24s of CPU time to compile, and module finalisation as a whole 6,300 CPU seconds, or 64 seconds of wall time when run over 128 threads.

It also generates ~1.3 GiB of *.mod.o.cmd files that every subsequent build has to read back.

Avoid all this by emitting the descriptors as assembly instead.

The layout required (size and alignment of struct module, struct modversion_info, the module's name offsets, init, and exit fields and whether the architecture uses PREL32 ksymtab references) can all be derived from scripts/mod/module-offsets.h.

The fields of __this_module are emitted in offset order rather than declaration order, as CONFIG_RANDSTRUCT shuffles struct module so the name, init and exit fields can land anywhere.

An assembly file avoids all of the issues previously mentioned so this conversion results in a very significant performance win on kernel build.

As a consequence of this change, since module-offsets.c includes linux/module.h, scripts/mod is now built after the generated headers in prepare0, rather than before.

Also update .gitignore and make clean to handle .mod.S files, but keep .mod.c files there to ensure that users do not end up with untracked changes/dirty trees after the change takes effect.

The sections were confirmed to be byte-for-byte identical to the C version produced - each of .modinfo, .gnu.linkonce.this_module, __ksymtab*, __ksymtab_strings, __kcrctab*, __kflagstab*, __versions, __version_ext_crcs, __version_ext_names and their relocations - for all 8,135 modules of a clang allmodconfig build with CONFIG_COMPILE_TEST off and CONFIG_MODVERSIONS, CONFIG_EXTENDED_MODVERSIONS and CONFIG_MODULE_SRCVERSION_ALL on, and for a sample built with gcc.

What differs is what the compiler added around them: the __UNIQUE_ID_* locals, the KASAN constructor for the .mod.c globals, and on x86 a .note.gnu.property that the linker already drops from any module containing an assembly file and the loader never reads.

None of these have any impact on the build, however.

x86_64 kernels built with gcc and clang, with CONFIG_MODVERSIONS, CONFIG_EXTENDED_MODVERSIONS and CONFIG_MODULE_SRCVERSION_ALL, were booted, every module and an external one loaded and unloaded, and the srcversions checked against modinfo, i386 and arm64 defconfigs (gcc and clang) and a ThinLTO build were also built as part of testing.

An x86_64 CONFIG_RANDSTRUCT_FULL build with clang, which places the name field after init and exit, was checked the same way and produces the same .gnu.linkonce.this_module sections and relocations as the C version.

On the x86_64 allmodconfig with clang 22, "make modules" with every *.mod.o and *.ko deleted goes from 64.5s (6,306 CPU-s) to 28.5s (518 CPU-s).

A consequence of this change is that the make jobs are now so small that make cannot dispatch them quick enough, however the next commit in the series addresses this issue.

This impacts clean and no-op builds with a large number of modules most noticeably.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 allmodconfig, no-op make, gcc        12.7s     2.3s    -10.4s (-82%)
  x86 allmodconfig, no-op make, clang      13.9s     2.8s    -11.2s (-80%)
  x86 allmodconfig, clean, gcc            342.6s   306.6s    -36.0s (-11%)
  x86 allmodconfig, clean, clang          340.1s   290.2s    -49.8s (-15%)
Assisted-by LLM
---
 .gitignore                   |   1 +
 Makefile                     |   4 +-
 include/linux/vermagic.h     |   2 +-
 scripts/Makefile.modfinal    |  10 +-
 scripts/Makefile.modpost     |   2 +-
 scripts/mod/.gitignore       |   1 +
 scripts/mod/Makefile         |   8 +
 scripts/mod/modpost.c        | 637 ++++++++++++++++++++++++++++++++-----------
 scripts/mod/module-offsets.c |  35 +++
 scripts/tags.sh              |   5 +-
 10 files changed, 530 insertions(+), 175 deletions(-)
.gitignore +1 -0
index 9875120ea7bd..00fc262b894b 100644
@@ -38,6 +38,7 @@
 *.lzo
 *.mod
 *.mod.c
+*.mod.S
 *.o
 *.o.*
 *.patch
Makefile +2 -2
index 68df3446d111..8263fc8a86b3 100644
@@ -1422,8 +1422,8 @@ archprepare: outputmakefile archheaders archscripts scripts include/config/kerne
 	include/generated/rustc_cfg remove-stale-files
 
 prepare0: archprepare
-	$(Q)$(MAKE) $(build)=scripts/mod
 	$(Q)$(MAKE) $(build)=. prepare
+	$(Q)$(MAKE) $(build)=scripts/mod
 
 # All the preparing..
 prepare: prepare0
@@ -2245,7 +2245,7 @@ clean: $(clean-dirs)
 		-o -name '*.dt.yaml' -o -name 'dtbs-list' \
 		-o -name '*.dwo' -o -name '*.lst' \
 		-o -name '*.su' -o -name '*.mod' \
-		-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
+		-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' -o -name '*.mod.S' \
 		-o -name '*.lex.c' -o -name '*.tab.[ch]' \
 		-o -name '*.asn1.[ch]' \
 		-o -name '*.symtypes' -o -name 'modules.order' \
include/linux/vermagic.h +1 -1
index 335c360d4f9b..09f05d02664c 100644
@@ -3,7 +3,7 @@
 #define _LINUX_VERMAGIC_H
 
 #ifndef INCLUDE_VERMAGIC
-#error "This header can be included from kernel/module.c or *.mod.c only"
+#error "This header can be included from kernel/module.c or scripts/module-common.c only"
 #endif
 
 #include <generated/utsrelease.h>
scripts/Makefile.modfinal +7 -3
index 01a37ec872b9..75e9effdf02c 100644
@@ -20,10 +20,14 @@ __modfinal: $(modules:%.o=%.ko)
 modname = $(notdir $(@:.mod.o=))
 part-of-module = y
 GCOV_PROFILE := n
-ccflags-remove-y := $(CC_FLAGS_CFI)
 
-%.mod.o: %.mod.c FORCE
-	$(call if_changed_rule,cc_o_c)
+# modpost lays the <module>.mod.S out completely (write_mod_S_file()), so it
+# needs only the assembler and no dependency tracking.
+quiet_cmd_as_mod_o = AS [M]  $@
+      cmd_as_mod_o = $(CC) $(_a_flags) $(modkern_aflags) -c -o $@ $<
+
+%.mod.o: %.mod.S FORCE
+	$(call if_changed,as_mod_o)
 
 .module-common.o: $(srctree)/scripts/module-common.c FORCE
 	$(call if_changed_rule,cc_o_c)
scripts/Makefile.modpost +1 -1
index d7d45067d08b..eecf5f5c99b4 100644
@@ -13,7 +13,7 @@
 # Stage 2 is handled by this file and does the following
 # 1) Find all modules listed in modules.order
 # 2) modpost is then used to
-# 3)  create one <module>.mod.c file per module
+# 3)  create one <module>.mod.S file per module
 # 4)  create one Module.symvers file with CRC for all exported symbols
 
 # Step 3 is used to place certain information in the module's ELF
scripts/mod/.gitignore +1 -0
index 0465ec33c9bf..620ab4362094 100644
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 /devicetable-offsets.h
+/module-offsets.h
 /elfconfig.h
 /mk_elfconfig
 /modpost
scripts/mod/Makefile +8 -0
index c729bc936bae..fbd5099e0441 100644
@@ -13,10 +13,18 @@ $(obj)/$(devicetable-offsets-file): $(obj)/devicetable-offsets.s FORCE
 
 targets += $(devicetable-offsets-file) devicetable-offsets.s
 
+module-offsets-file := module-offsets.h
+
+$(obj)/$(module-offsets-file): $(obj)/module-offsets.s FORCE
+	$(call filechk,offsets,__MODULE_OFFSETS_H__)
+
+targets += $(module-offsets-file) module-offsets.s
+
 # dependencies on generated files need to be listed explicitly
 
 $(obj)/modpost.o $(obj)/file2alias.o $(obj)/sumversion.o $(obj)/symsearch.o: $(obj)/elfconfig.h
 $(obj)/file2alias.o: $(obj)/$(devicetable-offsets-file)
+$(obj)/modpost.o: $(obj)/$(module-offsets-file)
 
 quiet_cmd_elfconfig = MKELF   $@
       cmd_elfconfig = $(obj)/mk_elfconfig < $< > $@
scripts/mod/modpost.c +471 -166

682 lines not on this page · raw message

scripts/mod/module-offsets.c new file +35 -0
new file mode 100644
index 000000000000..a336dd47aa33
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Layout of the structures modpost emits into *.mod.S, extracted from the
+ * target headers as devicetable-offsets.c does for the device tables.
+ */
+#define COMPILE_OFFSETS
+#include <linux/kbuild.h>
+#include <linux/module.h>
+
+int main(void)
+{
+	DEFINE(MOD_SIZEOF_LONG, sizeof(long));
+	DEFINE(MOD_PREL32_RELOCATIONS, IS_ENABLED(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS));
+	DEFINE(MOD_FUNC_PLABEL, IS_ENABLED(CONFIG_PARISC) && IS_ENABLED(CONFIG_64BIT));
+
+	DEFINE(MOD_SIZEOF_struct_module, sizeof(struct module));
+	DEFINE(MOD_ALIGNOF_struct_module, __alignof__(struct module));
+	OFFSET(MOD_OFF_module_name, module, name);
+	OFFSET(MOD_OFF_module_init, module, init);
+#ifdef CONFIG_MODULE_UNLOAD
+	OFFSET(MOD_OFF_module_exit, module, exit);
+#endif
+#if defined(CONFIG_M68K) && defined(CONFIG_MMU)
+	/* MODULE_ARCH_INIT: the only architecture where it is not all zeroes. */
+	OFFSET(MOD_OFF_module_arch_fixup_start, module, arch.fixup_start);
+	OFFSET(MOD_OFF_module_arch_fixup_end, module, arch.fixup_end);
+#endif
+	DEFINE(MOD_NAME_LEN, MODULE_NAME_LEN);
+
+	DEFINE(MOD_SIZEOF_struct_modversion_info, sizeof(struct modversion_info));
+	DEFINE(MOD_ALIGNOF_struct_modversion_info, __alignof__(struct modversion_info));
+	OFFSET(MOD_OFF_modversion_info_name, modversion_info, name);
+
+	return 0;
+}
scripts/tags.sh +3 -2
index 41e38df96984..c33d0f58a9d4 100755
@@ -14,8 +14,9 @@ fi
 
 # RCS_FIND_IGNORE has escaped ()s -- remove them.
 ignore="$(echo "$RCS_FIND_IGNORE" | sed 's|\\||g' )"
-# tags and cscope files should also ignore MODVERSION *.mod.c files
-ignore="$ignore ( -name *.mod.c ) -prune -o"
+# tags and cscope files should also ignore the modpost-generated *.mod.S files
+# and any *.mod.c left behind from before they were assembly
+ignore="$ignore ( -name *.mod.c -o -name *.mod.S ) -prune -o"
 
 # ignore arbitrary directories
 if [ -n "${IGNORE_DIRS}" ]; then
Signature · 1 line
2.55.0
#55 lore raw

PATCH v3 14/20 kbuild: batch module finalisation

In reply to Lorenzo Stoakes (ARM)

With the .mod.S change in place, module finalisation on allmodconfig builds consists of a large number of very short-lived jobs.

For allmodconfig x86-64 this can be on the order of ~22,000 jobs of a few milliseconds in duration each.

Each job entails processing ~22k .cmd files, so the combination of heavy overhead and small individual job results in a lot of unnecessary and repeated work even with all cores being utilised.

The solution is to batch by a number of jobs. Determining which value makes sense was done empirically.

On a 128-thread threadripper box doing an allmodconfig build, best of 2, *.ko, *.mod.o deleted each time:

    modules per chunk    instances    wall
    -----------------    ---------    ------
                    1        11171    10.22s
                    2         5586     6.72s
                    4         2793     4.97s
                    8         1397     4.26s
                   16          699     4.05s
                   32          350     4.05s
                   64          175     4.07s
                  128           88     4.05s
                  256           44     4.03s
                  512           22     4.18s

Wall time flattens for 16-256 module batches.

A slower/lower core machine will do better with fewer modules-per-batch, a faster/higher core machine will do better with more modules-per-batch.

Therefore, take the midpoint which works in the most margin in either direction - 128 modules per batch.

This naturally scales with module count too as the optimum gains are obtained with higher module count, so fewer batches in this case costs less overhead.

Each instance holds only its own modules' variables and the top-level one reads no per-module .cmd files at all, the same rules serve both levels, and an instance is told its chunk with modfinal-first=<index>.

Only the top-level instance builds .module-common.o, to the chunks it is a plain prerequisite, so no two instances ever write it.

"make modules" with every *.mod.o and *.ko deleted goes from 28.9s to 15.9s with clang 22. No-op "make modules" goes from 5.6s to 4.8s, as checking the 22,000 targets is spread over the chunks too.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 allmodconfig, no-op make, gcc         2.3s     1.4s    -0.85s (-38%)
  x86 allmodconfig, no-op make, clang       2.8s     1.8s    -0.94s (-34%)
  x86 allmodconfig, clean, gcc            306.6s   294.1s     -12.6s (-4%)
  x86 allmodconfig, clean, clang          290.2s   283.9s     -6.4s (-2%)
Assisted-by LLM
---
 scripts/Makefile.modfinal | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
scripts/Makefile.modfinal +29 -1
index 75e9effdf02c..4d5e6e1a0ff9 100644
@@ -13,9 +13,30 @@ include $(srctree)/scripts/Makefile.lib
 # find all modules listed in modules.order
 modules := $(call read-file, modules.order)
 
+modfinal-chunk-size := 128
+
+ifdef modfinal-first
+
+# this instance handles the chunk of modules.order starting at $(modfinal-first)
+modules := $(wordlist $(modfinal-first), $(words $(modules)), $(modules))
+modules := $(wordlist 1, $(modfinal-chunk-size), $(modules))
+
 __modfinal: $(modules:%.o=%.ko)
 	@:
 
+else
+
+modfinal-chunks := $(addprefix chunk-, $(shell seq 1 $(modfinal-chunk-size) $(words $(modules))))
+
+PHONY += $(modfinal-chunks)
+$(modfinal-chunks): .module-common.o
+	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modfinal modfinal-first=$(@:chunk-%=%)
+
+__modfinal: $(modfinal-chunks)
+	@:
+
+endif
+
 # modname and part-of-module are set to make c_flags define proper module flags
 modname = $(notdir $(@:.mod.o=))
 part-of-module = y
@@ -29,8 +50,11 @@ quiet_cmd_as_mod_o = AS [M]  $@
 %.mod.o: %.mod.S FORCE
 	$(call if_changed,as_mod_o)
 
+# Built by the top-level instance alone, the chunks take it as a plain file.
+ifndef modfinal-first
 .module-common.o: $(srctree)/scripts/module-common.c FORCE
 	$(call if_changed_rule,cc_o_c)
+endif
 
 ifneq ($(WARN_ON_UNUSED_TRACEPOINTS),)
 cmd_check_tracepoint = $(objtree)/scripts/tracepoint-update --module $<;
@@ -58,7 +82,11 @@ ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 endif
 	+$(call cmd,check_tracepoint)
 
-targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
+ifdef modfinal-first
+targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o)
+else
+targets += .module-common.o
+endif
 
 # Add FORCE to the prerequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
Signature · 1 line
2.55.0
Reviewed-by on v3 14/20
#56 lore raw

Re: [PATCH v3 14/20] kbuild: batch module finalisation

Quoted 29 lines · Lorenzo Stoakes (ARM)

With the .mod.S change in place, module finalisation on allmodconfig builds consists of a large number of very short-lived jobs.

For allmodconfig x86-64 this can be on the order of ~22,000 jobs of a few milliseconds in duration each.

Each job entails processing ~22k .cmd files, so the combination of heavy overhead and small individual job results in a lot of unnecessary and repeated work even with all cores being utilised.

The solution is to batch by a number of jobs. Determining which value makes sense was done empirically.

On a 128-thread threadripper box doing an allmodconfig build, best of 2, *.ko, *.mod.o deleted each time:

    modules per chunk    instances    wall
    -----------------    ---------    ------
                    1        11171    10.22s
                    2         5586     6.72s
                    4         2793     4.97s
                    8         1397     4.26s
                   16          699     4.05s
                   32          350     4.05s
                   64          175     4.07s
                  128           88     4.05s
                  256           44     4.03s
                  512           22     4.18s
Quoted 7 lines

Wall time flattens for 16-256 module batches.

A slower/lower core machine will do better with fewer modules-per-batch, a faster/higher core machine will do better with more modules-per-batch.

Therefore, take the midpoint which works in the most margin in either direction - 128 modules per batch.

This is easy to tweak, so if we get negative feedback on this for smaller machines, it's an easy fix.

Quoted 1 line
Signature · 1 line
Kees Cook
#57 lore raw

Re: [PATCH v3 14/20] kbuild: batch module finalisation

In reply to Lorenzo Stoakes (ARM)

+cc Petr

FYI that were some discussion on this in the v2 thread at [0], which will result in some changes for v4.

[0]:https://lore.kernel.org/all/arEZrFmXeCO4hZpP@gremlin

Quoted 129 lines · Lorenzo Stoakes (ARM)

With the .mod.S change in place, module finalisation on allmodconfig builds consists of a large number of very short-lived jobs.

For allmodconfig x86-64 this can be on the order of ~22,000 jobs of a few milliseconds in duration each.

Each job entails processing ~22k .cmd files, so the combination of heavy overhead and small individual job results in a lot of unnecessary and repeated work even with all cores being utilised.

The solution is to batch by a number of jobs. Determining which value makes sense was done empirically.

On a 128-thread threadripper box doing an allmodconfig build, best of 2, *.ko, *.mod.o deleted each time:

    modules per chunk    instances    wall
    -----------------    ---------    ------
                    1        11171    10.22s
                    2         5586     6.72s
                    4         2793     4.97s
                    8         1397     4.26s
                   16          699     4.05s
                   32          350     4.05s
                   64          175     4.07s
                  128           88     4.05s
                  256           44     4.03s
                  512           22     4.18s

Wall time flattens for 16-256 module batches.

A slower/lower core machine will do better with fewer modules-per-batch, a faster/higher core machine will do better with more modules-per-batch.

Therefore, take the midpoint which works in the most margin in either direction - 128 modules per batch.

This naturally scales with module count too as the optimum gains are obtained with higher module count, so fewer batches in this case costs less overhead.

Each instance holds only its own modules' variables and the top-level one reads no per-module .cmd files at all, the same rules serve both levels, and an instance is told its chunk with modfinal-first=<index>.

Only the top-level instance builds .module-common.o, to the chunks it is a plain prerequisite, so no two instances ever write it.

"make modules" with every *.mod.o and *.ko deleted goes from 28.9s to 15.9s with clang 22. No-op "make modules" goes from 5.6s to 4.8s, as checking the 22,000 targets is spread over the chunks too.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 allmodconfig, no-op make, gcc         2.3s     1.4s    -0.85s (-38%)
  x86 allmodconfig, no-op make, clang       2.8s     1.8s    -0.94s (-34%)
  x86 allmodconfig, clean, gcc            306.6s   294.1s     -12.6s (-4%)
  x86 allmodconfig, clean, clang          290.2s   283.9s     -6.4s (-2%)
Assisted-by LLM
---
 scripts/Makefile.modfinal | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
scripts/Makefile.modfinal +29 -2
index 75e9effdf02c..4d5e6e1a0ff9 100644
@@ -13,9 +13,30 @@ include $(srctree)/scripts/Makefile.lib
 # find all modules listed in modules.order
 modules := $(call read-file, modules.order)
 
+modfinal-chunk-size := 128
+
+ifdef modfinal-first
+
+# this instance handles the chunk of modules.order starting at $(modfinal-first)
+modules := $(wordlist $(modfinal-first), $(words $(modules)), $(modules))
+modules := $(wordlist 1, $(modfinal-chunk-size), $(modules))
+
 __modfinal: $(modules:%.o=%.ko)
 	@:
 
+else
+
+modfinal-chunks := $(addprefix chunk-, $(shell seq 1 $(modfinal-chunk-size) $(words $(modules))))
+
+PHONY += $(modfinal-chunks)
+$(modfinal-chunks): .module-common.o
+	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modfinal modfinal-first=$(@:chunk-%=%)
+
+__modfinal: $(modfinal-chunks)
+	@:
+
+endif
+
 # modname and part-of-module are set to make c_flags define proper module flags
 modname = $(notdir $(@:.mod.o=))
 part-of-module = y
@@ -29,8 +50,11 @@ quiet_cmd_as_mod_o = AS [M]  $@
 %.mod.o: %.mod.S FORCE
 	$(call if_changed,as_mod_o)
 
+# Built by the top-level instance alone, the chunks take it as a plain file.
+ifndef modfinal-first
 .module-common.o: $(srctree)/scripts/module-common.c FORCE
 	$(call if_changed_rule,cc_o_c)
+endif
 
 ifneq ($(WARN_ON_UNUSED_TRACEPOINTS),)
 cmd_check_tracepoint = $(objtree)/scripts/tracepoint-update --module $<;
@@ -58,7 +82,11 @@ ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 endif
 	+$(call cmd,check_tracepoint)
 
-targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
+ifdef modfinal-first
+targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o)
+else
+targets += .module-common.o
+endif
 
 # Add FORCE to the prerequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
 
--
Quoted 2 lines

2.55.0

--
Cheers, Lorenzo

#58 lore raw

PATCH v3 15/20 objtool: cache relocations, do less work, eliminate relocation hash

In reply to Lorenzo Stoakes (ARM)

Instruction relocations are looked up by destination in objtool via a hash which is keyed on a 16-byte (OFFSET_STRIDE) window within the section being walked.

It iterates through each 16-byte window, looking up relocations over several passes, before moving on to the next 16-byte window, caching only when a relocation is not found saving further lookups in this case.

Improve upon this by introducing a per-section relocation cache storing the first relocation at or after each 64-byte window of data (an empirically determined index range), indexed by chunk.

The lookup is implemented an array lookup and touches no shared state, so can be used from multiple threads.

This relies upon the entries within a section being sorted, which is the case for all sections supplied to objtool by the link step during the kernel build.

With this in place the relocation hash is unnecessary and removed. This saves ~90 MiB in peak memory usage for an allmodconfig build.

If anything is processed out of order, fall back to a linear scan.

DWARF sections are a special case - their relocations are never looked up by destination at all and only need to be on their symbol's list for elf_update_sym_relocs().

This is meaningful in practice as on an x86-64 kernel build with CONFIG_DEBUG_INFO set objtool processing of vmlinux.o is dominated by DWARF section processing.

For an allmodconfig build ~9 million relocations were hashed, and ~8.2 million of those were DWARF sections, which added overhead on cache miss and pollution of the hash table. This is now eliminated.

The output of objtool before and after this change was confirmed to be byte-for-byte identical both for x86_64 defconfig and allmodconfig with gcc and clang.

objtool on the gcc allmodconfig vmlinux.o goes from 10.5s to 9.0s, clang from 9.8s to 8.3s and gcc defconfig from 2.08s to 1.79s, with peak memory down ~90 MiB on allmodconfig.

objtool on vmlinux.o is on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        8.3s     8.2s    -0.14s (-2%)
  x86 defconfig, touch mm/vma.c, clang      7.6s     7.3s    -0.25s (-3%)
  x86 defconfig, clean, gcc                28.9s    28.6s    -0.22s (-1%)
  x86 defconfig, clean, clang              29.4s    29.1s    -0.28s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    29.4s    28.0s     -1.4s (-5%)
  x86 allmodconfig, touch mm/vma.c, clang  27.9s    26.2s     -1.7s (-6%)
Assisted-by LLM
---
 tools/objtool/elf.c                 | 204 ++++++++++++++++++++++++++++--------
 tools/objtool/include/objtool/elf.h |  10 +-
 2 files changed, 162 insertions(+), 52 deletions(-)
tools/objtool/elf.c +160 -44
index a791f4ea6ec1..8524d287621b 100644
@@ -316,45 +316,165 @@ struct symbol *find_global_symbol_by_name(const struct elf *elf, const char *nam
 	return NULL;
 }
 
-/* If there are multiple matches, return the first one in the range */
-struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
+static bool is_dwarf_section(struct section *sec)
+{
+	return !strncmp(sec->name, ".debug_", 7);
+}
+
+/* Index the first relocation at or after each 64 byte window of the base. */
+#define RELOC_CACHE_INDEX_SHIFT	6
+
+static unsigned long reloc_cache_index(unsigned long offset)
+{
+	return offset >> RELOC_CACHE_INDEX_SHIFT;
+}
+
+static void reloc_cache_free(struct section *rsec)
+{
+	free(rsec->reloc_cache);
+	rsec->reloc_cache = NULL;
+	rsec->nr_cache_windows = 0;
+	rsec->nr_indexed = 0;
+	rsec->sorted = false;
+}
+
+/* Grow the index to cover the base section, new windows start past the end. */
+static int reloc_cache_resize(struct section *rsec)
+{
+	const unsigned int nr_windows = reloc_cache_index(sec_size(rsec->base)) + 1;
+	unsigned int *cache;
+
+	if (nr_windows <= rsec->nr_cache_windows)
+		return 0;
+
+	cache = realloc(rsec->reloc_cache, nr_windows * sizeof(*cache));
+	if (!cache) {
+		ERROR_GLIBC("realloc");
+		return -1;
+	}
+
+	while (rsec->nr_cache_windows < nr_windows)
+		cache[rsec->nr_cache_windows++] = rsec->nr_indexed;
+	rsec->reloc_cache = cache;
+
+	return 0;
+}
+
+/*
+ * Index the next relocation. It must follow the previous one in position and
+ * offset, otherwise the section is scanned from now on.
+ */
+static int reloc_cache_add(struct section *rsec, unsigned int reloc_idx)
+{
+	const unsigned long offset = reloc_offset(&rsec->relocs[reloc_idx]);
+	const unsigned long window = reloc_cache_index(offset);
+	unsigned long first_window = 0;
+
+	if (reloc_idx != rsec->nr_indexed)
+		goto unsorted;
+
+	if (reloc_idx) {
+		const unsigned long prev = reloc_offset(&rsec->relocs[reloc_idx - 1]);
+
+		if (offset < prev)
+			goto unsorted;
+		first_window = reloc_cache_index(prev) + 1;
+	}
+
+	if (reloc_cache_resize(rsec))
+		return -1;
+	if (window >= rsec->nr_cache_windows)
+		goto unsorted;
+
+	while (first_window <= window)
+		rsec->reloc_cache[first_window++] = reloc_idx;
+	rsec->nr_indexed = reloc_idx + 1;
+
+	return 0;
+
+unsorted:
+	reloc_cache_free(rsec);
+	return 0;
+}
+
+static int init_reloc_cache(struct section *rsec)
+{
+	const unsigned int nr_relocs = sec_num_entries(rsec);
+	unsigned int reloc_idx;
+
+	rsec->sorted = true;
+	for (reloc_idx = 0; reloc_idx < nr_relocs; reloc_idx++) {
+		if (reloc_cache_add(rsec, reloc_idx))
+			return -1;
+		if (!rsec->sorted)
+			break;
+	}
+
+	return 0;
+}
+
+static bool reloc_in_range(struct reloc *reloc, unsigned long offset,
+			   unsigned int len)
+{
+	return reloc_offset(reloc) >= offset && reloc_offset(reloc) < offset + len;
+}
+
+/* The index gives a lower bound, scan on from there. */
+static struct reloc *find_reloc_sorted(struct section *rsec,
 				       unsigned long offset, unsigned int len)
 {
-	struct reloc *reloc, *r = NULL;
-	struct section *rsec;
-	unsigned long o;
+	const unsigned long cache_idx = reloc_cache_index(offset);
+	unsigned int reloc_idx;
 
-	rsec = sec->rsec;
-	if (!rsec)
+	if (cache_idx >= rsec->nr_cache_windows)
 		return NULL;
 
-	for_offset_range(o, offset, offset + len) {
-		elf_hash_for_each_possible(elf, reloc, reloc, hash,
-					   sec_offset_hash(rsec, o)) {
-			if (reloc->sec != rsec)
-				continue;
+	for (reloc_idx = rsec->reloc_cache[cache_idx];
+	     reloc_idx < rsec->nr_indexed; reloc_idx++) {
+		struct reloc *reloc = &rsec->relocs[reloc_idx];
 
-			if (reloc_offset(reloc) >= offset &&
-			    reloc_offset(reloc) < offset + len) {
-				if (!r || reloc_offset(reloc) < reloc_offset(r))
-					r = reloc;
-			}
-		}
-		if (r && (reloc_offset(r) & OFFSET_STRIDE_MASK) == o)
-			return r;
+		if (reloc_offset(reloc) >= offset)
+			return reloc_in_range(reloc, offset, len) ? reloc : NULL;
 	}
 
-	return r;
+	return NULL;
 }
 
-struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
+/* Out of order sections, only ever DWARF or one objtool grew that way. */
+static struct reloc *find_reloc_linear(struct section *rsec,
+				       unsigned long offset, unsigned int len)
 {
-	return find_reloc_by_dest_range(elf, sec, offset, 1);
+	struct reloc *reloc, *first = NULL;
+
+	for_each_reloc(rsec, reloc) {
+		if (!reloc->sec || !reloc_in_range(reloc, offset, len))
+			continue;
+
+		if (!first || reloc_offset(reloc) < reloc_offset(first))
+			first = reloc;
+	}
+
+	return first;
 }
 
-static bool is_dwarf_section(struct section *sec)
+/* If there are multiple matches, return the first one in the range. */
+struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
+				       unsigned long offset, unsigned int len)
 {
-	return !strncmp(sec->name, ".debug_", 7);
+	struct section *rsec = sec->rsec;
+
+	if (!rsec)
+		return NULL;
+
+	if (rsec->sorted)
+		return find_reloc_sorted(rsec, offset, len);
+
+	return find_reloc_linear(rsec, offset, len);
+}
+
+struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
+{
+	return find_reloc_by_dest_range(elf, sec, offset, 1);
 }
 
 static int read_sections(struct elf *elf)
@@ -1071,7 +1191,8 @@ struct reloc *elf_init_reloc(struct elf *elf, struct section *rsec,
 	set_reloc_type(elf, reloc, type);
 	set_reloc_addend(elf, reloc, addend);
 
-	elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
+	if (rsec->sorted && reloc_cache_add(rsec, reloc_idx))
+		return NULL;
 	set_sym_next_reloc(reloc, sym->relocs);
 	sym->relocs = reloc;
 
@@ -1125,16 +1246,13 @@ struct reloc *elf_init_reloc_data_sym(struct elf *elf, struct section *sec,
 
 static int read_relocs(struct elf *elf)
 {
-	unsigned long nr_reloc, max_reloc = 0;
+	unsigned long nr_reloc, max_reloc = 0, nr_linear = 0;
 	struct section *rsec;
 	struct reloc *reloc;
 	unsigned int symndx;
 	struct symbol *sym;
 	int i;
 
-	if (!elf_alloc_hash(reloc, elf->num_relocs))
-		return -1;
-
 	list_for_each_entry(rsec, &elf->sections, list) {
 		if (!is_reloc_sec(rsec))
 			continue;
@@ -1168,19 +1286,26 @@ static int read_relocs(struct elf *elf)
 				return -1;
 			}
 
-			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
 			set_sym_next_reloc(reloc, sym->relocs);
 			sym->relocs = reloc;
 
 			nr_reloc++;
 		}
 		max_reloc = max(max_reloc, nr_reloc);
+
+		/* DWARF relocs are never looked up, so are not worth indexing. */
+		if (is_dwarf_section(rsec->base))
+			continue;
+		if (init_reloc_cache(rsec))
+			return -1;
+		if (!rsec->sorted)
+			nr_linear += nr_reloc;
 	}
 
 	if (opts.stats) {
 		printf("max_reloc: %lu\n", max_reloc);
 		printf("num_relocs: %lu\n", elf->num_relocs);
-		printf("reloc_bits: %d\n", elf->reloc_bits);
+		printf("num_relocs_linear: %lu\n", nr_linear);
 	}
 
 	return 0;
@@ -1327,8 +1452,7 @@ struct elf *elf_create_file(GElf_Ehdr *ehdr, const char *name)
 	if (!elf_alloc_hash(section,		1000) ||
 	    !elf_alloc_hash(section_name,	1000) ||
 	    !elf_alloc_hash(symbol,		10000) ||
-	    !elf_alloc_hash(symbol_name,	10000) ||
-	    !elf_alloc_hash(reloc,		100000))
+	    !elf_alloc_hash(symbol_name,	10000))
 		return NULL;
 
 	null		= elf_create_section(elf, NULL, 0, 0, SHT_NULL, 0, 0);
@@ -1508,6 +1632,8 @@ struct section *elf_create_section(struct elf *elf, const char *name,
 	sec->sh.sh_type = type;
 	sec->sh.sh_addralign = align;
 	sec->sh.sh_flags = flags;
+	/* Relocations objtool adds are indexed as they come. */
+	sec->sorted = type == SHT_RELA;
 
 	if (name) {
 		sec->name = strdup(name);
@@ -1633,16 +1759,6 @@ static int elf_alloc_reloc(struct elf *elf, struct section *rsec)
 	}
 
 	memcpy(new_relocs, old_relocs, nr_relocs_old * sizeof(struct reloc));
-
-	for (int i = 0; i < nr_relocs_old; i++) {
-		struct reloc *old = &old_relocs[i];
-		struct reloc *new = &new_relocs[i];
-		u32 key = reloc_hash(old);
-
-		elf_hash_del(reloc, &old->hash, key);
-		elf_hash_add(reloc, &new->hash, key);
-	}
-
 	free(old_relocs);
 done:
 	rsec->relocs = new_relocs;
tools/objtool/include/objtool/elf.h +2 -8
index a82517a76a0f..ba18e188fc5f 100644
@@ -59,6 +59,8 @@ struct section {
 	const char *name;
 	int idx;
 	bool _changed, text, rodata, noinstr, init, truncate;
+	bool sorted;
+	unsigned int *reloc_cache, nr_cache_windows, nr_indexed;
 	struct reloc *relocs;
 	unsigned long nr_alloc_relocs;
 	struct section *twin;
@@ -106,7 +108,6 @@ struct symbol {
 };
 
 struct reloc {
-	struct elf_hash_node hash;
 	struct section *sec;
 	struct symbol *sym;
 	unsigned long _sym_next_reloc;
@@ -127,13 +128,11 @@ struct elf {
 	int symbol_name_bits;
 	int section_bits;
 	int section_name_bits;
-	int reloc_bits;
 
 	struct elf_hash_node **symbol_hash;
 	struct elf_hash_node **symbol_name_hash;
 	struct elf_hash_node **section_hash;
 	struct elf_hash_node **section_name_hash;
-	struct elf_hash_node **reloc_hash;
 
 	struct section *section_data;
 	struct symbol *symbol_data;
@@ -575,9 +574,4 @@ static inline u32 sec_offset_hash(struct section *sec, unsigned long offset)
 	return ol;
 }
 
-static inline u32 reloc_hash(struct reloc *reloc)
-{
-	return sec_offset_hash(reloc->sec, reloc_offset(reloc));
-}
-
 #endif /* _OBJTOOL_ELF_H */
Signature · 1 line
2.55.0
maintainer
#59 lore raw

Re: [PATCH v3 15/20] objtool: cache relocations, do less work, eliminate relocation hash

Quoted 3 lines · Lorenzo Stoakes (ARM)

This relies upon the entries within a section being sorted, which is the case for all sections supplied to objtool by the link step during the kernel build.

This is wrong (or at least actively misleading). Objtool doesn't *only* run on linked objects. In some configs it runs on individual .o files. And GCC doesn't sort relocs:

Relocation section '.rela.text' at offset 0xc0d0 contains 724 entries:
Offset Info Type Symbol's Value Symbol's Name + Addend
...

  0000000000005c50  0000009000000004 R_X86_64_PLT32         0000000000000000 _raw_spin_lock - 4
  0000000000005c65  0000009100000004 R_X86_64_PLT32         0000000000000000 _raw_spin_unlock - 4
  0000000000005c6d  0000019f00000004 R_X86_64_PLT32         0000000000000000 put_files_struct - 4
  000000000000004d  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4
  0000000000000075  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4
  00000000000000cd  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4

(JMP target relocations are emitted in a second pass, for whatever reason)

So the hash may actually be needed as a fallback after all. Or some other scheme.

Either way it's overkill to have more than a single fallback. No second fallback for "just in case". Attempting to search an unhashed section (DWARF) can just be a fatal error instead of the "just in case" WARN+linear fallback thing.

Quoted 5 lines
tools/objtool/elf.c +0 -1
@@ -1168,19 +1286,26 @@ static int read_relocs(struct elf *elf)
 				return -1;
 			}
 
-			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));

tools/objtool/elf.c static int read_relocs(struct elf *elf) · line 1298

Quoted 10 lines
tools/objtool/elf.c +4 -0
 			set_sym_next_reloc(reloc, sym->relocs);
 			sym->relocs = reloc;
 
 			nr_reloc++;
 		}
 		max_reloc = max(max_reloc, nr_reloc);
+
+		/* DWARF relocs are never looked up, so are not worth indexing. */
+		if (is_dwarf_section(rsec->base))
+			continue;

This DWARF reloc skipping is a standalone improvement, can you split this out to another patch?

Signature · 1 line
Josh
#60 lore raw

Re: [PATCH v3 15/20] objtool: cache relocations, do less work, eliminate relocation hash

Quoted 19 lines · Josh Poimboeuf
Quoted 3 lines · Lorenzo Stoakes (ARM)

This relies upon the entries within a section being sorted, which is the case for all sections supplied to objtool by the link step during the kernel build.

This is wrong (or at least actively misleading). Objtool doesn't *only* run on linked objects. In some configs it runs on individual .o files. And GCC doesn't sort relocs:

Relocation section '.rela.text' at offset 0xc0d0 contains 724 entries:
Offset Info Type Symbol's Value Symbol's Name + Addend
...

  0000000000005c50  0000009000000004 R_X86_64_PLT32         0000000000000000 _raw_spin_lock - 4
  0000000000005c65  0000009100000004 R_X86_64_PLT32         0000000000000000 _raw_spin_unlock - 4
  0000000000005c6d  0000019f00000004 R_X86_64_PLT32         0000000000000000 put_files_struct - 4
  000000000000004d  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4
  0000000000000075  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4
  00000000000000cd  0000008f00000004 R_X86_64_PLT32         0000000000000000 __x86_return_thunk - 4
Quoted 5 lines

(JMP target relocations are emitted in a second pass, for whatever reason)

So the hash may actually be needed as a fallback after all. Or some other scheme.

Ack, that's fair enough.

Definitely need something that isn't the linear scan as a truly worst case can be horrible.

I think the hash can be avoided though, Do the read_relocs() without ordering, track whether things are in order, on decode if sorted then just read from relocs[], if not can allocate an order[] array and qsort() and build the index over that.

So O(n lg n) at that point, but avoids bothering to sort for anything not looked up, works similarly for added sections.

So still avoids all of the hash stuff, but efficient when things are actually out of order.

Quoted 5 lines

Either way it's overkill to have more than a single fallback. No second fallback for "just in case". Attempting to search an unhashed section (DWARF) can just be a fatal error instead of the "just in case" WARN+linear fallback thing.

Honestly this is what I instinctively preferred, but objtool is not my realm so I worried there'd be some odd outlier thing that it'd somehow break!

Quoted 9 lines
Quoted 9 lines
tools/objtool/elf.c +0 -1
@@ -1168,19 +1286,26 @@ static int read_relocs(struct elf *elf)
 				return -1;
 			}
 
-			elf_hash_add(reloc, &reloc->hash, reloc_hash(reloc));
 			set_sym_next_reloc(reloc, sym->relocs);
 			sym->relocs = reloc;
 
Quoted 10 lines

tools/objtool/elf.c static int read_relocs(struct elf *elf) · line 1298

Quoted 7 lines
tools/objtool/elf.c +4 -0
 			nr_reloc++;
 		}
 		max_reloc = max(max_reloc, nr_reloc);
+
+		/* DWARF relocs are never looked up, so are not worth indexing. */
+		if (is_dwarf_section(rsec->base))
+			continue;

This DWARF reloc skipping is a standalone improvement, can you split this out to another patch?

Ack will do!

Quoted 3 lines

--
Josh

--
Cheers, Lorenzo

#61 lore raw

PATCH v3 16/20 objtool: size the instruction hash to the text

In reply to Lorenzo Stoakes (ARM)

The instruction hash is a fixed 2^20 buckets, which for an x86-64 allmodconfig vmlinux.o of ~16 million instructions leaves find_insn() walking chains of four or more entries.

Size it by the amount of text to be decoded instead, at one bucket per OFFSET_STRIDE window, as sec_offset_hash() keys on those and anything finer would sit empty.

This gives 2^20 buckets (8 MiB) for a defconfig vmlinux.o and 2^22 (32 MiB) for allmodconfig, so it is not an egregious use of memory.

The output of objtool before and after this change was confirmed to be byte-for-byte identical for x86_64 defconfig and allmodconfig.

On a 128-thread machine, objtool on the gcc allmodconfig vmlinux.o goes from 9.0s to 6.8s. A defconfig vmlinux.o already had 2^20 buckets and is unchanged.

objtool on vmlinux.o is on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 allmodconfig, touch mm/vma.c, gcc    28.0s    25.7s     -2.4s (-8%)
  x86 allmodconfig, touch mm/vma.c, clang  26.2s    24.1s     -2.0s (-8%)
Assisted-by LLM
---
 tools/objtool/check.c                   | 58 +++++++++++++++++++++++++++++++--
 tools/objtool/include/objtool/objtool.h |  3 +-
 tools/objtool/objtool.c                 |  1 -
 3 files changed, 58 insertions(+), 4 deletions(-)
tools/objtool/check.c +56 -2
index 464f6c9d9ff0..62a3e1d4e9e5 100644
@@ -38,12 +38,22 @@ struct disas_context *objtool_disas_ctx;
 
 size_t sym_name_max_len;
 
+static struct hlist_head *insn_hash_head(struct objtool_file *file,
+					 struct section *sec, unsigned long offset)
+{
+	/* Determine instruction hash based on section index and offset. */
+	const u32 sec_hash = sec_offset_hash(sec, offset);
+	const u32 hash = hash_min(sec_hash, file->insn_hash_bits);
+
+	return &file->insn_hash[hash];
+}
+
 struct instruction *find_insn(struct objtool_file *file,
 			      struct section *sec, unsigned long offset)
 {
 	struct instruction *insn;
 
-	hash_for_each_possible(file->insn_hash, insn, hash, sec_offset_hash(sec, offset)) {
+	hlist_for_each_entry(insn, insn_hash_head(file, sec, offset), hash) {
 		if (insn->sec == sec && insn->offset == offset)
 			return insn;
 	}
@@ -403,6 +413,44 @@ static void *cfi_hash_alloc(unsigned long size)
 static unsigned long nr_insns;
 static unsigned long nr_insns_visited;
 
+/*
+ * sec_offset_hash() keys on OFFSET_STRIDE windows, so the instructions of a
+ * window share a chain and buckets beyond one per window would sit empty.
+ */
+#define INSN_HASH_BYTES_PER_BUCKET	OFFSET_STRIDE
+#define INSN_HASH_MIN_BITS		10
+
+static unsigned long total_text_size(struct objtool_file *file)
+{
+	unsigned long size = 0;
+	struct section *sec;
+
+	for_each_sec(file->elf, sec)
+		if (is_text_sec(sec))
+			size += sec_size(sec);
+
+	return size;
+}
+
+static int alloc_insn_hash(struct objtool_file *file, unsigned long text_size)
+{
+	const unsigned long nr_buckets = text_size / INSN_HASH_BYTES_PER_BUCKET;
+	const int bits = ilog2(nr_buckets);
+
+	file->insn_hash_bits = max(INSN_HASH_MIN_BITS, bits);
+	file->insn_hash = calloc(1UL << file->insn_hash_bits,
+				 sizeof(*file->insn_hash));
+	if (!file->insn_hash) {
+		ERROR_GLIBC("calloc");
+		return -1;
+	}
+
+	if (opts.stats)
+		printf("insn_hash_bits: %d\n", file->insn_hash_bits);
+
+	return 0;
+}
+
 /*
  * Call the arch-specific instruction decoder for all the instructions and add
  * them to the global instruction list.
@@ -414,6 +462,9 @@ static int decode_instructions(struct objtool_file *file)
 	unsigned long offset;
 	struct instruction *insn;
 
+	if (alloc_insn_hash(file, total_text_size(file)))
+		return -1;
+
 	for_each_sec(file->elf, sec) {
 		struct instruction *insns = NULL;
 		u8 prev_len = 0;
@@ -474,7 +525,7 @@ static int decode_instructions(struct objtool_file *file)
 			if (insn->type == INSN_BUG)
 				insn->dead_end = true;
 
-			hash_add(file->insn_hash, &insn->hash, sec_offset_hash(sec, insn->offset));
+			hlist_add_head(&insn->hash, insn_hash_head(file, sec, insn->offset));
 			nr_insns++;
 		}
 
@@ -4802,6 +4853,9 @@ void free_insns(struct objtool_file *file)
 
 	for (chunk = chunks; chunk; chunk = chunk->next)
 		free(chunk->addr);
+
+	free(file->insn_hash);
+	file->insn_hash = NULL;
 }
 
 const char *objtool_disas_insn(struct instruction *insn)
tools/objtool/include/objtool/objtool.h +2 -1
index 6dc12a59ad00..79fe82b7397e 100644
@@ -21,7 +21,8 @@ struct pv_state {
 
 struct objtool_file {
 	struct elf *elf;
-	DECLARE_HASHTABLE(insn_hash, 20);
+	struct hlist_head *insn_hash;
+	int insn_hash_bits;
 	struct list_head retpoline_call_list;
 	struct list_head return_thunk_list;
 	struct list_head static_call_list;
tools/objtool/objtool.c +0 -1
index a4e139dee7e9..71e048f8582a 100644
@@ -29,7 +29,6 @@ struct objtool_file *objtool_open_read(const char *filename)
 	if (!file.elf)
 		return NULL;
 
-	hash_init(file.insn_hash);
 	INIT_LIST_HEAD(&file.retpoline_call_list);
 	INIT_LIST_HEAD(&file.return_thunk_list);
 	INIT_LIST_HEAD(&file.static_call_list);
Signature · 1 line
2.55.0
#62 lore raw

PATCH v3 17/20 objtool: decode instructions and resolve branch targets in parallel

In reply to Lorenzo Stoakes (ARM)

During a kernel build objtool is used to decode vmlinux.o's instructions and resolve every jump and call destination.

This forms a large part of the work objtool does during the build process, and it is all done in serial.

Decode these in parallel at a function granularity to speed things up, but limit this to invocations that pass --link, and only where the there is 8 MiB or more text to justify it.

In practice this limits this to processing vmlinux.o in the kernel build and modules are processed as they were before.

Only the instruction hash is shared between the threads and nothing is ever removed from it, so an insertion is a compare-and-swap on the bucket head.

Threading is limited to decoding and the jump pass, so the gain flattens out at 16 threads and any further threads were found to only add overhead.

When performing an allmodconfig build, the clang invocation of objtool when processing vmlinux.o took 5.93s on 1 thread, 4.56s on 8, 4.51s on 16 and 4.63s on 128.

Therefore cap the thread count at 16 or the number of CPUs, whichever is fewer.

The output of objtool before and after this change was confirmed to be byte-for-byte identical for x86_64 defconfig and allmodconfig with gcc and clang, and for a loongarch defconfig, where objtool runs on every object.

On a 128-thread machine, objtool on the clang allmodconfig vmlinux.o goes from 5.2s to 4.4s (6.5s to 4.4s together with the previous two patches), and on defconfig from 1.99s to 1.38s.

objtool on vmlinux.o is on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        8.2s     7.7s    -0.55s (-7%)
  x86 defconfig, touch mm/vma.c, clang      7.3s     6.9s    -0.44s (-6%)
  x86 defconfig, clean, gcc                28.6s    28.2s    -0.47s (-2%)
  x86 defconfig, clean, clang              29.1s    28.7s    -0.45s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    25.7s    23.7s     -2.0s (-8%)
  x86 allmodconfig, touch mm/vma.c, clang  24.1s    22.5s     -1.6s (-7%)
Assisted-by LLM
---
 tools/objtool/Makefile  |   2 +-
 tools/objtool/check.c   | 717 ++++++++++++++++++++++++++++++++++++------------
 tools/objtool/objtool.c |  14 +-
 3 files changed, 546 insertions(+), 187 deletions(-)
tools/objtool/Makefile +1 -1
index a4484fd22a96..2de50c3917ba 100644
@@ -63,7 +63,7 @@ INCLUDES := -I$(srctree)/tools/include \
 OBJTOOL_CFLAGS  := -std=gnu11 -fomit-frame-pointer -O2 -g $(WARNINGS)	\
 		   $(INCLUDES) $(LIBELF_FLAGS) $(LIBXXHASH_CFLAGS) $(HOSTCFLAGS)
 
-OBJTOOL_LDFLAGS := $(LIBSUBCMD) $(LIBELF_LIBS) $(LIBXXHASH_LIBS) $(HOSTLDFLAGS)
+OBJTOOL_LDFLAGS := $(LIBSUBCMD) $(LIBELF_LIBS) $(LIBXXHASH_LIBS) -lpthread $(HOSTLDFLAGS)
 
 # Allow old libelf to be used:
 elfshdr := $(shell echo '$(pound)include <libelf.h>' | $(HOSTCC) $(OBJTOOL_CFLAGS) -x c -E - 2>/dev/null | grep elf_getshdr)
tools/objtool/check.c +535 -182

830 lines not on this page · raw message

tools/objtool/objtool.c +10 -4
index 71e048f8582a..f472dfe7a773 100644
@@ -8,6 +8,7 @@
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>
+#include <pthread.h>
 #include <subcmd/exec-cmd.h>
 #include <subcmd/pager.h>
 #include <linux/kernel.h>
@@ -41,6 +42,8 @@ struct objtool_file *objtool_open_read(const char *filename)
 	return &file;
 }
 
+static pthread_mutex_t pv_ops_lock = PTHREAD_MUTEX_INITIALIZER;
+
 int objtool_pv_add(struct objtool_file *f, int idx, struct symbol *func)
 {
 	if (!opts.noinstr)
@@ -59,12 +62,15 @@ int objtool_pv_add(struct objtool_file *f, int idx, struct symbol *func)
 	    !strcmp(func->name, "_paravirt_ident_64"))
 		return 0;
 
+	pthread_mutex_lock(&pv_ops_lock);
+
 	/* already added this function */
-	if (!list_empty(&func->pv_target))
-		return 0;
+	if (list_empty(&func->pv_target)) {
+		list_add(&func->pv_target, &f->pv_ops[idx].targets);
+		f->pv_ops[idx].clean = false;
+	}
 
-	list_add(&func->pv_target, &f->pv_ops[idx].targets);
-	f->pv_ops[idx].clean = false;
+	pthread_mutex_unlock(&pv_ops_lock);
 	return 0;
 }
 
Signature · 1 line
2.55.0
maintainer
#63 lore raw

Re: [PATCH v3 17/20] objtool: decode instructions and resolve branch targets in parallel

Quoted 48 lines · Lorenzo Stoakes (ARM)

During a kernel build objtool is used to decode vmlinux.o's instructions and resolve every jump and call destination.

This forms a large part of the work objtool does during the build process, and it is all done in serial.

Decode these in parallel at a function granularity to speed things up, but limit this to invocations that pass --link, and only where the there is 8 MiB or more text to justify it.

In practice this limits this to processing vmlinux.o in the kernel build and modules are processed as they were before.

Only the instruction hash is shared between the threads and nothing is ever removed from it, so an insertion is a compare-and-swap on the bucket head.

Threading is limited to decoding and the jump pass, so the gain flattens out at 16 threads and any further threads were found to only add overhead.

When performing an allmodconfig build, the clang invocation of objtool when processing vmlinux.o took 5.93s on 1 thread, 4.56s on 8, 4.51s on 16 and 4.63s on 128.

Therefore cap the thread count at 16 or the number of CPUs, whichever is fewer.

The output of objtool before and after this change was confirmed to be byte-for-byte identical for x86_64 defconfig and allmodconfig with gcc and clang, and for a loongarch defconfig, where objtool runs on every object.

On a 128-thread machine, objtool on the clang allmodconfig vmlinux.o goes from 5.2s to 4.4s (6.5s to 4.4s together with the previous two patches), and on defconfig from 1.99s to 1.38s.

objtool on vmlinux.o is on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        8.2s     7.7s    -0.55s (-7%)
  x86 defconfig, touch mm/vma.c, clang      7.3s     6.9s    -0.44s (-6%)
  x86 defconfig, clean, gcc                28.6s    28.2s    -0.47s (-2%)
  x86 defconfig, clean, clang              29.1s    28.7s    -0.45s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    25.7s    23.7s     -2.0s (-8%)
  x86 allmodconfig, touch mm/vma.c, clang  24.1s    22.5s     -1.6s (-7%)
Quoted 7 lines
Assisted-by LLM
---
 tools/objtool/Makefile  |   2 +-
 tools/objtool/check.c   | 717 ++++++++++++++++++++++++++++++++++++------------
 tools/objtool/objtool.c |  14 +-
 3 files changed, 546 insertions(+), 187 deletions(-)

This is an interesting patch, but I'm not really convinced it's worth the pain.

Signature · 1 line
Josh
#64 lore raw

Re: [PATCH v3 17/20] objtool: decode instructions and resolve branch targets in parallel

Quoted 57 lines · Josh Poimboeuf
Quoted 48 lines · Lorenzo Stoakes (ARM)

During a kernel build objtool is used to decode vmlinux.o's instructions and resolve every jump and call destination.

This forms a large part of the work objtool does during the build process, and it is all done in serial.

Decode these in parallel at a function granularity to speed things up, but limit this to invocations that pass --link, and only where the there is 8 MiB or more text to justify it.

In practice this limits this to processing vmlinux.o in the kernel build and modules are processed as they were before.

Only the instruction hash is shared between the threads and nothing is ever removed from it, so an insertion is a compare-and-swap on the bucket head.

Threading is limited to decoding and the jump pass, so the gain flattens out at 16 threads and any further threads were found to only add overhead.

When performing an allmodconfig build, the clang invocation of objtool when processing vmlinux.o took 5.93s on 1 thread, 4.56s on 8, 4.51s on 16 and 4.63s on 128.

Therefore cap the thread count at 16 or the number of CPUs, whichever is fewer.

The output of objtool before and after this change was confirmed to be byte-for-byte identical for x86_64 defconfig and allmodconfig with gcc and clang, and for a loongarch defconfig, where objtool runs on every object.

On a 128-thread machine, objtool on the clang allmodconfig vmlinux.o goes from 5.2s to 4.4s (6.5s to 4.4s together with the previous two patches), and on defconfig from 1.99s to 1.38s.

objtool on vmlinux.o is on the serial tail of every build that links vmlinux, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        8.2s     7.7s    -0.55s (-7%)
  x86 defconfig, touch mm/vma.c, clang      7.3s     6.9s    -0.44s (-6%)
  x86 defconfig, clean, gcc                28.6s    28.2s    -0.47s (-2%)
  x86 defconfig, clean, clang              29.1s    28.7s    -0.45s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    25.7s    23.7s     -2.0s (-8%)
  x86 allmodconfig, touch mm/vma.c, clang  24.1s    22.5s     -1.6s (-7%)
Quoted 7 lines
Assisted-by LLM
---
 tools/objtool/Makefile  |   2 +-
 tools/objtool/check.c   | 717 ++++++++++++++++++++++++++++++++++++------------
 tools/objtool/objtool.c |  14 +-
 3 files changed, 546 insertions(+), 187 deletions(-)
Quoted 2 lines

This is an interesting patch, but I'm not really convinced it's worth the pain.

Obviously I defer to you as the maintainer :)

But I think the numbers are pretty significant, certainly for allmodconfig incremental it's a fairly significant chunk of the improvement.

Yes it's a relatively large-ish change but it's sensible and straight-forward one and certainly in the direction you'd expect to see changes in (parallelise things we can do less work where possible).

And note that the work is limited only to those tasks which have singificant data to process and only if --link is specified, so the scope is relatively small.

We could add a flag for this also potentially?

Obviously if you feel firmly that this isn't something you want I can also drop it but I think it is worth having.

One thing to note is that I went through a (bloody painful :) process of dropping everything that felt like bad RoI which the LLM came up with, it started at something crazy like 30-35 patches :)

(This was prior to reworking code, checking everything, etc. - gawd the schloppers have it easy not doing all that! :)

Anyway let me know what makes sense.

Quoted 3 lines

--
Josh

--
Cheers, Lorenzo

#65 lore raw

PATCH v3 18/20 rust: make exports.o depend on the headers generated for it

In reply to Lorenzo Stoakes (ARM)

rust/exports.c includes the exports_*_generated.h listing the symbols of the core, bindings, kernel and helpers objects, but this is not expressed in its Makefile.

This worked previously because the headers are always-y targets, and make prepare built all of the rust crates first, which is an implicit dependency.

Fix this as it is a dependency of the subsequent commit.

Assisted-by LLM
---
 rust/Makefile | 5 +++++
 1 file changed, 5 insertions(+)
rust/Makefile +5 -0
index da1a7409d984..74d21ae6f383 100644
@@ -728,6 +728,11 @@ endef
 $(obj)/helpers/helpers.o: $(src)/helpers/helpers.c $(recordmcount_source) FORCE
 	+$(call if_changed_rule,rust_cc_library)
 
+# The exported symbol lists are generated from the crates' objects.
+$(obj)/exports.o: $(obj)/exports_core_generated.h \
+    $(obj)/exports_bindings_generated.h $(obj)/exports_kernel_generated.h \
+    $(if $(CONFIG_RUST_INLINE_HELPERS),,$(obj)/exports_helpers_generated.h)
+
 # Disable symbol versioning for exports.o to avoid conflicts with the actual
 # symbol versions generated from Rust objects.
 $(obj)/exports.o: private skip_gendwarfksyms = 1
Signature · 1 line
2.55.0
#66 lore raw

PATCH v3 19/20 kbuild: build rust crates in parallel with the rest of the build

In reply to Lorenzo Stoakes (ARM)

When CONFIG_RUST is specified make prepare builds all of the rust components before descending into the tree.

This means nothing can be done until all of these are compiled, resulting in a stall at the start of every clean CONFIG_RUST build.

This also implicitly slows down every rust-capable LLVM allmodconfig build as this enables the CONFIG_RUST option.

Fix this by allowing rust crates to be built alongside the C code.

Remove the rust build from the make prepare step, then establish a dependency between rust code located elsewhere in the tree upon rust components contained in rust/.

Do this by establishing a top-level list of directories containing rust code, KBUILD_RUST_DIRS, upon which the dependency is expressed.

Finally, ensure that no rust code is located elsewhere and fail the build if any is found to ensure that nothing is missed in future.

Care is taken to ensure the rust/ dependency is also established for any module being built to account for external rust modules which rely upon it, and that only one rust/ build will be performed at any one time.

External rust modules builds are unaffected - make modules_prepare ... (where ... are other goals) will build rust/ first.

Every Rust and C object was confirmed to be byte-for-byte identical after this change.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------
x86 defconfig+RUST, clean 36.5s 32.6s -3.9s (-11%)
x86 allmodconfig, clean 297.0s 278.3s -18.7s (-6%)

Assisted-by LLM
---
 Kbuild                 |  5 +++++
 Makefile               | 13 ++++++++++++-
 scripts/Makefile.build |  5 ++++-
 3 files changed, 21 insertions(+), 2 deletions(-)
Kbuild +5 -0
index a6a0192dea08..9670556059dd 100644
@@ -115,3 +115,8 @@ obj-$(CONFIG_NET)	+= net/
 obj-y			+= virt/
 obj-y			+= $(ARCH_DRIVERS)
 obj-$(CONFIG_DRM_HEADER_TEST)	+= include/
+
+# Rust code elsewhere in the tree depends upon rust/.
+ifdef CONFIG_RUST
+$(KBUILD_RUST_DIRS): | rust
+endif
Makefile +12 -1
index 8263fc8a86b3..ede9cfeffd56 100644
@@ -1425,11 +1425,14 @@ prepare0: archprepare
 	$(Q)$(MAKE) $(build)=. prepare
 	$(Q)$(MAKE) $(build)=scripts/mod
 
+ifdef CONFIG_RUST
+export KBUILD_RUST_DIRS := drivers lib mm samples
+endif
+
 # All the preparing..
 prepare: prepare0
 ifdef CONFIG_RUST
 	+$(Q)$(CONFIG_SHELL) $(srctree)/scripts/rust_is_available.sh
-	$(Q)$(MAKE) $(build)=rust
 endif
 
 PHONY += remove-stale-files
@@ -1756,6 +1759,14 @@ modules: modules_prepare
 # Target to prepare building external modules
 modules_prepare: prepare
 	$(Q)$(MAKE) $(build)=scripts scripts/module.lds
+ifdef CONFIG_RUST
+# Avoid two instances of rust/ being built at any one time.
+ifneq ($(filter modules_prepare,$(MAKECMDGOALS)),)
+ifeq ($(filter all vmlinux modules %Image% dtbs rustdoc rusttest,$(MAKECMDGOALS)),)
+	$(Q)$(MAKE) $(build)=rust
+endif
+endif
+endif
 
 endif # CONFIG_MODULES
 
scripts/Makefile.build +4 -1
index b9093b39cc2f..77351d6006fa 100644
@@ -360,8 +360,11 @@ quiet_cmd_rustc_o_rs = $(RUSTC_OR_CLIPPY_QUIET) $(quiet_modtag) $@
 		$(cmd_ld_single)) \
 	$(cmd_objtool)
 
+rust-dir-ok = $(or $(KBUILD_EXTMOD),$(filter rust $(KBUILD_RUST_DIRS),$(firstword $(subst /, ,$@))))
+
+# Ensure that any rust code located elsewhere from rust/ is listed in KBUILD_RUST_DIRS.
 define rule_rustc_o_rs
-	$(call cmd_and_fixdep,rustc_o_rs)
+	$(if $(rust-dir-ok),,$(error $@: Rust code in a directory not listed in KBUILD_RUST_DIRS, see the top Makefile))$(call cmd_and_fixdep,rustc_o_rs)
 	$(call cmd,gen_objtooldep)
 endef
 
Signature · 1 line
2.55.0
#67 lore raw

PATCH v3 20/20 kbuild: compress the kernel with pigz if available

In reply to Lorenzo Stoakes (ARM)

The gzip step of a kernel build is very lengthy, especially for larger builds such as allmodconfig.

gzip itself cannot be run in parallel, however an alternative tool exists that can, providing the same feature set as gzip itself - pigz - which works as a drop-in replacement.

On a 128-core Threadripper, gzip -9 of a 36 MiB x86-64 vmlinux.bin takes 1.6s, and with pigz it takes 0.09s, so the performance increase is significant.

Therefore introduce the KPGZIP build variable which specifies the compressor to use for the kernel image and default it to pigz if available, or KGZIP otherwise (which itself defaults to gzip).

Modules, packaging and the embedded kernel configuration (CONFIG_IKCONFIG) continue to use KGZIP which defaults to a single-threaded gzip instance.

Module compression is run in parallel by make, so pigz offers no benefit there, packaging sits outside the build and the embedded configuration is too small to matter.

pigz is executed using scripts/jobserver-exec, which reserves the job slots make has free - necessary, as otherwise pigz would just grab unbounded CPUs.

The kernel image compression step is always performed at the end of the build so should typically have all job slots available.

pigz always provides byte-for-byte identical output across runs regardless of thread count, but pigz and gzip are not guaranteed to generate the same binary output, so reproducible builds must use the same tools consistently.

Also update Documentation/kbuild/kbuild.rst to describe KPGZIP and Documentation/process/changes.rst to list the optional pigz dependency.

While there, add entries for the other compressor programs.

Every x86 build ends with the compression of vmlinux.bin, 36MB for defconfig and over 200MB for allmodconfig, no-op builds are unchanged.

Whole build, 128-thread Threadripper 9980X, best of N runs:

before after delta
-------------------------------

  x86 defconfig, touch mm/vma.c, gcc        7.7s     6.0s     -1.7s (-22%)
  x86 defconfig, touch mm/vma.c, clang      6.9s     5.4s     -1.5s (-21%)
  x86 defconfig, clean, gcc                28.2s    26.3s     -1.8s (-6%)
  x86 defconfig, clean, clang              28.7s    27.2s     -1.5s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.4s     -8.3s (-35%)
  x86 allmodconfig, touch mm/vma.c, clang  22.5s    15.6s     -7.0s (-31%)
  x86 allmodconfig, clean, gcc            294.1s   278.6s     -15.5s (-5%)
  x86 allmodconfig, clean, clang          283.9s   266.8s     -17.1s (-6%)
---
 Documentation/kbuild/kbuild.rst   | 17 +++++++++++++++++
 Documentation/process/changes.rst |  8 ++++++++
 Makefile                          |  5 ++++-
 kernel/Makefile                   |  6 +++++-
 scripts/Makefile.lib              |  4 ++--
 scripts/jobserver-exec            |  3 ++-
 tools/lib/python/jobserver.py     | 13 +++++++++++++
 7 files changed, 51 insertions(+), 5 deletions(-)
Documentation/kbuild/kbuild.rst +17 -0
index 5a9013bacfb7..e71a692a559a 100644
@@ -110,6 +110,23 @@ HOSTLDLIBS
 ----------
 Additional libraries to link against when building host programs.
 
+KGZIP
+-----
+The gzip program used for compressed modules, packaging and the embedded
+kernel configuration. Defaults to gzip.
+
+KPGZIP
+------
+The gzip program used for the compressed kernel image. Defaults to pigz (a
+parallel implementation of gzip), run under scripts/jobserver-exec so that it
+uses the job slots make has free, if pigz is installed, otherwise to
+``KGZIP``. Set ``KPGZIP=`` on the make command line to use another program.
+
+KBZIP2, KLZOP, LZMA, LZ4, XZ, ZSTD
+----------------------------------
+The compressor programs for the other formats. Each defaults to the program
+of the same name.
+
 .. _userkbuildflags:
 
 USERCFLAGS
Documentation/process/changes.rst +8 -0
index 0aa232b117b5..28f2ca63318e 100644
@@ -55,6 +55,7 @@ nfs-utils              1.0.5            showmount --version
 openssl & libcrypto    1.0.0            openssl version
 pahole                 1.26             pahole --version
 pcmciautils            004              pccardctl -V
+pigz (optional)        2.4              pigz --version
 PPP                    2.4.0            pppd --version
 procps                 3.2.0            ps --version
 Python                 3.9.x            python3 --version
@@ -206,6 +207,13 @@ GNU AWK
 GNU AWK is needed if you want kernel builds to generate address range data for
 builtin modules (CONFIG_BUILTIN_MODULE_RANGES).
 
+pigz (optional)
+---------------
+
+pigz is a parallel implementation of gzip. If it is installed the compressed
+kernel image is produced with it rather than with gzip, see ``KPGZIP`` in
+Documentation/kbuild/kbuild.rst.
+
 System utilities
 ****************
 
Makefile +4 -1
index ede9cfeffd56..d50bcb480134 100644
@@ -568,6 +568,9 @@ LZMA		= lzma
 LZ4		= lz4
 XZ		= xz
 ZSTD		= zstd
+# The kernel image is compressed with pigz, on the job slots make has free,
+# if it is installed. Everything else uses KGZIP.
+KPGZIP		:= $(if $(shell command -v pigz 2>/dev/null),$(PYTHON3) $(abs_srctree)/scripts/jobserver-exec pigz -p %PARALLELISM%,$(KGZIP))
 TAR		= tar
 
 CHECKFLAGS     := -D__linux__ -Dlinux -D__STDC__ -Dunix -D__unix__ \
@@ -648,7 +651,7 @@ export RUSTC RUSTDOC RUSTFMT RUSTC_OR_CLIPPY_QUIET RUSTC_OR_CLIPPY BINDGEN LLVM_
 export HOSTRUSTC KBUILD_HOSTRUSTFLAGS
 export CPP AR NM STRIP OBJCOPY OBJDUMP READELF PAHOLE RESOLVE_BTFIDS LEX YACC AWK INSTALLKERNEL
 export PERL PYTHON3 CHECK CHECKFLAGS MAKE UTS_MACHINE HOSTCXX
-export KGZIP KBZIP2 KLZOP LZMA LZ4 XZ ZSTD TAR
+export KGZIP KPGZIP KBZIP2 KLZOP LZMA LZ4 XZ ZSTD TAR
 export KBUILD_HOSTCXXFLAGS KBUILD_HOSTLDFLAGS KBUILD_HOSTLDLIBS KBUILD_PROCMACROLDFLAGS LDFLAGS_MODULE
 export KBUILD_USERCFLAGS KBUILD_USERLDFLAGS
 
kernel/Makefile +5 -1
index 1e1a31673577..c64c82c96b40 100644
@@ -153,9 +153,13 @@ obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o
 
 $(obj)/configs.o: $(obj)/config_data.gz
 
+# .config is small, so it is compressed with gzip rather than the image compressor.
+quiet_cmd_gzip_config = GZIP    $@
+      cmd_gzip_config = cat $(real-prereqs) | $(KGZIP) -n -f -9 > $@
+
 targets += config_data config_data.gz
 $(obj)/config_data.gz: $(obj)/config_data FORCE
-	$(call if_changed,gzip)
+	$(call if_changed,gzip_config)
 
 filechk_cat = cat $<
 
scripts/Makefile.lib +2 -2
index 2f447bc25e7b..8936925d4d50 100644
@@ -332,11 +332,11 @@ quiet_cmd_ar = AR      $@
 quiet_cmd_objcopy = OBJCOPY $@
 cmd_objcopy = $(OBJCOPY) $(OBJCOPYFLAGS) $(OBJCOPYFLAGS_$(@F)) $< $@
 
-# Gzip
+# Gzip, for the kernel image
 # ---------------------------------------------------------------------------
 
 quiet_cmd_gzip = GZIP    $@
-      cmd_gzip = cat $(real-prereqs) | $(KGZIP) -n -f -9 > $@
+      cmd_gzip = cat $(real-prereqs) | $(KPGZIP) -n -f -9 > $@
 
 # Bzip2
 # ---------------------------------------------------------------------------
scripts/jobserver-exec +2 -1
index 21b319e6c9a5..89119acb1b9e 100755
@@ -4,7 +4,8 @@
 """
 Determines how many parallel tasks "make" is expecting, as it is
 not exposed via any special variables, reserves them all, runs a subprocess
-with PARALLELISM environment variable set, and releases the jobs back again.
+with PARALLELISM environment variable set and any %PARALLELISM% in its
+arguments replaced by the count, and releases the jobs back again.
 
 See:
     https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html#POSIX-Jobserver
tools/lib/python/jobserver.py +13 -0
index 0b1ffdf9f7a3..7e94635bf7d9 100755
@@ -29,6 +29,10 @@ $claim child to do the actual work.
 The end goal here is to keep the total number of build tasks under the
 limit established by the initial ``make -j$n_proc`` call.
 
+A command that takes its thread count on the command line rather than from
+the environment can use the ``%PARALLELISM%`` token in its arguments, which
+is replaced by the count, or by 1 when there is no jobserver.
+
 See:
     https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html#POSIX-Jobserver
 """
@@ -38,6 +42,8 @@ import os
 import subprocess
 import sys
 
+PARALLELISM_TOKEN = "%PARALLELISM%"
+
 def warn(text, *args):
     print(f'WARNING: {text}', *args, file = sys.stderr)
 
@@ -182,6 +188,9 @@ class JobserverExec:
         Run a command setting PARALLELISM env variable to the number of
         available job slots (claim) + 1, e.g. it will reserve claim slots
         to do the actual build work, plus one to monitor its children.
+
+        Any %PARALLELISM% in the command's arguments is replaced by the same
+        number, or by 1 when there is no jobserver.
         """
         self.open()             # Ensure that self.claim is set
 
@@ -192,4 +201,8 @@ class JobserverExec:
         if self.claim:
             os.environ["PARALLELISM"] = str(self.claim)
 
+        if not isinstance(cmd, str):
+            parallelism = str(self.claim or 1)
+            cmd = [arg.replace(PARALLELISM_TOKEN, parallelism) for arg in cmd]
+
         return subprocess.call(cmd, *args, **pwargs)
Signature · 1 line
2.55.0
Reviewed-by on v3 20/20
#68 lore raw

Re: [PATCH v3 20/20] kbuild: compress the kernel with pigz if available

Quoted 10 lines · Lorenzo Stoakes (ARM)
---
 Documentation/kbuild/kbuild.rst   | 17 +++++++++++++++++
 Documentation/process/changes.rst |  8 ++++++++
 Makefile                          |  5 ++++-
 kernel/Makefile                   |  6 +++++-
 scripts/Makefile.lib              |  4 ++--
 scripts/jobserver-exec            |  3 ++-
 tools/lib/python/jobserver.py     | 13 +++++++++++++
 7 files changed, 51 insertions(+), 5 deletions(-)

Awesome; I love it. (I may send a follow-up to improve the PARALLELISM token so things can define the fallback instead of the hard-coded "1", but there is only one place I found where that might be useful, and it will be totally separate from this.)

Signature · 1 line
Kees Cook
#69 lore raw

Re: [PATCH v3 20/20] kbuild: compress the kernel with pigz if available

Quoted 12 lines · Kees Cook
Quoted 10 lines · Lorenzo Stoakes (ARM)
---
 Documentation/kbuild/kbuild.rst   | 17 +++++++++++++++++
 Documentation/process/changes.rst |  8 ++++++++
 Makefile                          |  5 ++++-
 kernel/Makefile                   |  6 +++++-
 scripts/Makefile.lib              |  4 ++--
 scripts/jobserver-exec            |  3 ++-
 tools/lib/python/jobserver.py     | 13 +++++++++++++
 7 files changed, 51 insertions(+), 5 deletions(-)
Quoted 1 line

Awesome; I love it. (I may send a follow-up to improve the PARALLELISM

Thanks! :)

Quoted 3 lines

token so things can define the fallback instead of the hard-coded "1", but there is only one place I found where that might be useful, and it will be totally separate from this.)

Ack, seems like it's open season on improving this stuff now which is good I think!

I also believe there is more performance to be got in future series ;)

Quoted 2 lines

Thanks! :)

Quoted 3 lines

--
Kees Cook

--
Cheers, Lorenzo

Reviewed-by on v3 20/20
#70 lore raw

Re: [PATCH v3 20/20] kbuild: compress the kernel with pigz if available

In reply to Lorenzo Stoakes (ARM)

Hi Lorenzo,

Quoted 7 lines · Lorenzo Stoakes (ARM)

The gzip step of a kernel build is very lengthy, especially for larger builds such as allmodconfig.

...

Whole build, 128-thread Threadripper 9980X, best of N runs:

Quoted 10 lines

                                         before   after     delta
                                         -------------------------------
  x86 defconfig, touch mm/vma.c, gcc        7.7s     6.0s     -1.7s (-22%) x86 defconfig, touch mm/vma.c, clang      6.9s     5.4s     -1.5s (-21%) x86 defconfig, clean, gcc                28.2s    26.3s     -1.8s (-6%) x86 defconfig, clean, clang              28.7s    27.2s     -1.5s (-5%) x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.4s     -8.3s (-35%) x86 allmodconfig, touch mm/vma.c, clang  22.5s    15.6s     -7.0s (-31%) x86 allmodconfig, clean, gcc            294.1s   278.6s     -15.5s (-5%) x86 allmodconfig, clean, clang          283.9s   266.8s     -17.1s (-6%)

That's good to hear.

Quoted 10 lines

---
 Documentation/kbuild/kbuild.rst   | 17 +++++++++++++++++ Documentation/process/changes.rst |  8 ++++++++ Makefile                          |  5 ++++- kernel/Makefile                   |  6 +++++- scripts/Makefile.lib              |  4 ++--

Please add a line to
scripts/ver_linux

Quoted 12 lines

 scripts/jobserver-exec            |  3 ++- tools/lib/python/jobserver.py     | 13 +++++++++++++

 7 files changed, 51 insertions(+), 5 deletions(-)
Documentation/kbuild/kbuild.rst +0 -0
index 5a9013bacfb7..e71a692a559a 100644
@@ -110,6 +110,23 @@ HOSTLDLIBS

 ----------
 Additional libraries to link against when building host programs.

Documentation/kbuild/kbuild.rst HOSTLDLIBS · line 115

Quoted 3 lines
Documentation/kbuild/kbuild.rst +3 -0
+KGZIP
+-----
+The gzip program used for compressed modules, packaging and the embedded

Could you also add gzip to changes.rst and ver_linux while you are at it? Rest looks good to me.

Thanks
Manuel

Documentation/process/changes.rst nfs-utils              1.0.5            showmount --version

Quoted 22 lines
Documentation/kbuild/kbuild.rst +14 -0
+kernel configuration. Defaults to gzip.
+
+KPGZIP
+------
+The gzip program used for the compressed kernel image. Defaults to pigz (a
+parallel implementation of gzip), run under scripts/jobserver-exec so that it
+uses the job slots make has free, if pigz is installed, otherwise to
+``KGZIP``. Set ``KPGZIP=`` on the make command line to use another program.
+
+KBZIP2, KLZOP, LZMA, LZ4, XZ, ZSTD
+----------------------------------
+The compressor programs for the other formats. Each defaults to the program
+of the same name.
+

 .. _userkbuildflags:

 USERCFLAGS

Documentation/process/changes.rst +0 -0
index 0aa232b117b5..28f2ca63318e 100644
@@ -55,6 +55,7 @@ nfs-utils              1.0.5            showmount --version

+ gzip

Quoted 23 lines

 openssl & libcrypto    1.0.0            openssl version pahole                 1.26             pahole --version pcmciautils            004              pccardctl -V +pigz (optional)        2.4              pigz --version PPP                    2.4.0            pppd --version procps                 3.2.0            ps --version Python                 3.9.x            python3 --version

Documentation/process/changes.rst +0 -0
@@ -206,6 +207,13 @@ GNU AWK

 GNU AWK is needed if you want kernel builds to generate address range data for builtin modules (CONFIG_BUILTIN_MODULE_RANGES).

Documentation/process/changes.rst +7 -0
+pigz (optional)
+---------------
+
+pigz is a parallel implementation of gzip. If it is installed the compressed
+kernel image is produced with it rather than with gzip, see ``KPGZIP`` in
+Documentation/kbuild/kbuild.rst.
+

 System utilities
 ****************

Makefile +0 -0
...
#71 lore raw

Re: [PATCH v3 20/20] kbuild: compress the kernel with pigz if available

Quoted 21 lines · Manuel Ebner

Hi Lorenzo,

Quoted 7 lines · Lorenzo Stoakes (ARM)

The gzip step of a kernel build is very lengthy, especially for larger builds such as allmodconfig.

...

Whole build, 128-thread Threadripper 9980X, best of N runs:

Quoted 10 lines

                                         before   after     delta
                                         -------------------------------
  x86 defconfig, touch mm/vma.c, gcc        7.7s     6.0s     -1.7s (-22%) x86 defconfig, touch mm/vma.c, clang      6.9s     5.4s     -1.5s (-21%) x86 defconfig, clean, gcc                28.2s    26.3s     -1.8s (-6%) x86 defconfig, clean, clang              28.7s    27.2s     -1.5s (-5%) x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.4s     -8.3s (-35%) x86 allmodconfig, touch mm/vma.c, clang  22.5s    15.6s     -7.0s (-31%) x86 allmodconfig, clean, gcc            294.1s   278.6s     -15.5s (-5%) x86 allmodconfig, clean, clang          283.9s   266.8s     -17.1s (-6%)

Quoted 1 line

That's good to hear.

:)

Quoted 13 lines
Quoted 6 lines
Quoted 6 lines

---
 Documentation/kbuild/kbuild.rst   | 17 +++++++++++++++++ Documentation/process/changes.rst |  8 ++++++++ Makefile                          |  5 ++++- kernel/Makefile                   |  6 +++++- scripts/Makefile.lib              |  4 ++--

Quoted 2 lines

Please add a line to
scripts/ver_linux

Ack, done for v4!

Quoted 13 lines
Quoted 13 lines

 scripts/jobserver-exec            |  3 ++- tools/lib/python/jobserver.py     | 13 +++++++++++++

 7 files changed, 51 insertions(+), 5 deletions(-)
Documentation/kbuild/kbuild.rst +0 -0
index 5a9013bacfb7..e71a692a559a 100644
@@ -110,6 +110,23 @@ HOSTLDLIBS

 ----------
 Additional libraries to link against when building host programs.

Quoted 6 lines

Documentation/kbuild/kbuild.rst HOSTLDLIBS · line 115

Quoted 3 lines
Documentation/kbuild/kbuild.rst +3 -0
+KGZIP
+-----
+The gzip program used for compressed modules, packaging and the embedded

Could you also add gzip to changes.rst and ver_linux while you are at it? Rest looks good to me.

I'd rather leave that out of this series tbh, if I listed it then I have to choose a minimum version that and feels out of scope.

One for a follow-up?

Quoted 1 line

Thanks!

Quoted 50 lines

Thanks
Manuel

Documentation/process/changes.rst nfs-utils              1.0.5            showmount --version

Quoted 22 lines
Documentation/kbuild/kbuild.rst +14 -0
+kernel configuration. Defaults to gzip.
+
+KPGZIP
+------
+The gzip program used for the compressed kernel image. Defaults to pigz (a
+parallel implementation of gzip), run under scripts/jobserver-exec so that it
+uses the job slots make has free, if pigz is installed, otherwise to
+``KGZIP``. Set ``KPGZIP=`` on the make command line to use another program.
+
+KBZIP2, KLZOP, LZMA, LZ4, XZ, ZSTD
+----------------------------------
+The compressor programs for the other formats. Each defaults to the program
+of the same name.
+

 .. _userkbuildflags:

 USERCFLAGS

Documentation/process/changes.rst +0 -0
index 0aa232b117b5..28f2ca63318e 100644
@@ -55,6 +55,7 @@ nfs-utils              1.0.5            showmount --version

+ gzip

Quoted 21 lines

 openssl & libcrypto    1.0.0            openssl version pahole                 1.26             pahole --version pcmciautils            004              pccardctl -V +pigz (optional)        2.4              pigz --version PPP                    2.4.0            pppd --version procps                 3.2.0            ps --version Python                 3.9.x            python3 --version

Documentation/process/changes.rst +0 -0
@@ -206,6 +207,13 @@ GNU AWK

 GNU AWK is needed if you want kernel builds to generate address range data for builtin modules (CONFIG_BUILTIN_MODULE_RANGES).

Documentation/process/changes.rst +7 -0
+pigz (optional)
+---------------
+
+pigz is a parallel implementation of gzip. If it is installed the compressed
+kernel image is produced with it rather than with gzip, see ``KPGZIP`` in
+Documentation/kbuild/kbuild.rst.
+

 System utilities
 ****************

Quoted 3 lines

Makefile

Quoted 2 lines
Makefile +0 -0
...

--
Cheers, Lorenzo

#72 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 11 lines · Lorenzo Stoakes (ARM)
                == defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        32.5s    26.3s     -6.1s (-19%)
Threadripper, clang      34.5s    27.2s     -7.3s (-21%)
EPYC, gcc                28.7s    20.6s     -8.1s (-28%)
EPYC, clang              39.8s    32.2s     -7.6s (-19%)
M2, gcc                 519.3s   512.4s     -6.9s (-1%)

M2, clang 634.5s 569.4s -65.1s (-10%)

There's something odd going on with that M2 gcc build. Why is it such an odd duck?

Linus

#73 lore raw
Quoted 13 lines · Linus Torvalds
Quoted 11 lines · Lorenzo Stoakes (ARM)
                == defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        32.5s    26.3s     -6.1s (-19%)
Threadripper, clang      34.5s    27.2s     -7.3s (-21%)
EPYC, gcc                28.7s    20.6s     -8.1s (-28%)
EPYC, clang              39.8s    32.2s     -7.6s (-19%)
M2, gcc                 519.3s   512.4s     -6.9s (-1%)

M2, clang 634.5s 569.4s -65.1s (-10%)

Quoted 2 lines

There's something odd going on with that M2 gcc build. Why is it such an odd duck?

Ugh dear lord I think the LLM somehow corrupted the numbers... Let me re-run those myself locally and come back with the actual times!

(I didn't do an allmodconfig out of pure impatience but might take the time to do that too)

Quoted 2 lines

Linus

--
Cheers, Lorenzo

#74 lore raw
Quoted 14 lines · Lorenzo Stoakes (ARM)
Quoted 13 lines · Linus Torvalds
Quoted 11 lines · Lorenzo Stoakes (ARM)
                == defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        32.5s    26.3s     -6.1s (-19%)
Threadripper, clang      34.5s    27.2s     -7.3s (-21%)
EPYC, gcc                28.7s    20.6s     -8.1s (-28%)
EPYC, clang              39.8s    32.2s     -7.6s (-19%)
M2, gcc                 519.3s   512.4s     -6.9s (-1%)

M2, clang 634.5s 569.4s -65.1s (-10%)

Quoted 5 lines
Quoted 2 lines

There's something odd going on with that M2 gcc build. Why is it such an odd duck?

Ugh dear lord I think the LLM somehow corrupted the numbers... Let me re-run those myself locally and come back with the actual times!

OK numbers are in:

M2, gcc 564.7s 512.1s -52.6s (-9%)
M2, clang 615.1s 564.1s -51.0s (-8%)

From the v1:

M2, gcc                 564.0s   512.4s    -51.6s (-9%)
M2, clang               616.1s   569.4s    -46.7s (-8%)

(Tested as per the cover letter pre-reqs, i.e. applying dependent series first etc.)

Not sure on the -5s delta on the clang build :) that might have been me being more disciplined this time to not use the laptop at the same time.

But broadly in line with the original numbers.

Quoted 6 lines
Quoted 3 lines

Linus

--
Cheers, Lorenzo

--
Cheers, Lorenzo

#75 lore raw
Quoted 29 lines · Lorenzo Stoakes (ARM)
Quoted 14 lines · Lorenzo Stoakes (ARM)
Quoted 13 lines · Linus Torvalds
Quoted 11 lines · Lorenzo Stoakes (ARM)
                == defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        32.5s    26.3s     -6.1s (-19%)
Threadripper, clang      34.5s    27.2s     -7.3s (-21%)
EPYC, gcc                28.7s    20.6s     -8.1s (-28%)
EPYC, clang              39.8s    32.2s     -7.6s (-19%)
M2, gcc                 519.3s   512.4s     -6.9s (-1%)

M2, clang 634.5s 569.4s -65.1s (-10%)

Quoted 5 lines
Quoted 2 lines

There's something odd going on with that M2 gcc build. Why is it such an odd duck?

Ugh dear lord I think the LLM somehow corrupted the numbers... Let me re-run those myself locally and come back with the actual times!

OK numbers are in:

M2, gcc                 564.7s   512.1s    -52.6s (-9%)
M2, clang               615.1s   564.1s    -51.0s (-8%)

From the v1:

Quoted 7 lines
M2, gcc                 564.0s   512.4s    -51.6s (-9%)
M2, clang               616.1s   569.4s    -46.7s (-8%)

(Tested as per the cover letter pre-reqs, i.e. applying dependent series first etc.)

Not sure on the -5s delta on the clang build :) that might have been me

Clang is faster on Thursdays.

Quoted 13 lines

being more disciplined this time to not use the laptop at the same time.

But broadly in line with the original numbers.

Quoted 6 lines
Quoted 3 lines

Linus

--
Cheers, Lorenzo

--
Cheers, Lorenzo

Signature · 2 lines
Thanks,
~Nick Desaulniers