Skip to contentSkip to conversation

kbuild: significantly speed up kernel builds

PATCH Superseded Lorenzo Stoakes (ARM) 15 participants 116 messages Sep 8 – Nov 8 9 messages not in the archive

Subsystems (10)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

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:

		== allmodconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       345.3s   275.2s    -70.1s (-20%)
Threadripper, clang     345.5s   265.7s    -79.8s (-23%)
EPYC, gcc               188.6s   121.1s    -67.5s (-36%)
EPYC, clang             261.7s   184.6s    -77.1s (-29%)
		== allmodconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        46.4s    15.3s    -31.1s (-67%)
Threadripper, clang      44.4s    15.2s    -29.1s (-66%)
EPYC, gcc                82.0s    24.3s    -57.7s (-70%)
EPYC, clang              77.6s    24.3s    -53.3s (-69%)
		== allmodconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       12.97s    1.18s   -11.79s (-91%)
Threadripper, clang     13.84s    1.64s   -12.20s (-88%)
EPYC, gcc               25.92s    1.52s   -24.40s (-94%)
EPYC, clang             27.58s    2.17s   -25.41s (-92%)
		== defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        35.3s    28.6s     -6.7s (-19%)
Threadripper, clang      33.5s    26.1s     -7.4s (-22%)
EPYC, gcc                31.2s    20.6s    -10.6s (-34%)
EPYC, clang              38.6s    32.2s     -6.4s (-17%)
M2, gcc                 564.0s   512.4s    -51.6s (-9%)
M2, clang               616.1s   569.4s    -46.7s (-8%)
		== defconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        11.6s     5.5s     -6.1s (-53%)
Threadripper, clang      11.6s     5.0s     -6.6s (-57%)
EPYC, gcc                19.3s     9.2s    -10.1s (-52%)
EPYC, clang              20.1s     8.6s    -11.5s (-57%)
M2, gcc                  18.6s     9.9s     -8.7s (-47%)
M2, clang                18.6s     8.2s    -10.4s (-56%)
		== defconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        0.96s    0.47s    -0.49s (-51%)
Threadripper, clang      1.21s    0.55s    -0.66s (-55%)
EPYC, gcc                1.47s    0.66s    -0.81s (-55%)
EPYC, clang              1.87s    0.80s    -1.07s (-57%)
M2, gcc                  5.59s    1.69s    -3.90s (-70%)
M2, clang                6.62s    1.74s    -4.88s (-74%)

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.x

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 ==

mksysmap (1, 2): A couple of bugfixes the rest of the series relies
upon.

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

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

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

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

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

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

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

modpost (13, 14): Hash module sources a file at a time not a byte at a
time, also improve performance through use of a cache.

modules (15, 16): 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.

modpost (17): Compute srcversions in parallel using a thread pool.

objtool (18, 19): Avoid polluting the reloc hash with millions of DWARF
relocations. Remember dead-ends and decode large objects over multiple threads. Size instruction hash to the code rather than hard-code it.

rust (20-22): Parallelise the frontend, set correct dependencies and
build crates in parallel with C code, retaining the requirement that rust/ crates are built first.

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

---
Lorenzo Stoakes (ARM) (23):
scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms scripts/mksysmap: fix escape of '$' in the __pi_ pattern
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: do not allocate .modinfo in vmlinux
kbuild: cache list, composite object state per object
kbuild: implement and use depcheck to check dependency timestamps
kbuild: avoid re-running compiler and linker probes
modpost: hash module source per-file, not per-byte
modpost: cache section relocation mismatch state
modpost: emit module descriptors as assembly
kbuild: batch module finalisation
modpost: perform srcversion hashing in parallel
objtool: cache relocations and function dead end state, do less work
objtool: decode instructions and resolve branch targets in parallel
kbuild: rust: parallelise rustc front end
rust: make exports.o depend on the headers generated for it
kbuild: build rust crates in parallel with the rest of the build
kbuild: use pigz for gzip compression if available

 .gitignore                                   |   1 +
 Documentation/kbuild/kbuild.rst              |  13 +
 Documentation/kbuild/reproducible-builds.rst |  16 +
 Kbuild                                       |   5 +
 Makefile                                     |  49 +-
 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                                 |  84 +++
 rust/Makefile                                |   5 +
 scripts/Makefile                             |   4 +-
 scripts/Makefile.build                       |  27 +-
 scripts/Makefile.lib                         |   7 +-
 scripts/Makefile.modfinal                    |  36 +-
 scripts/Makefile.modpost                     |   2 +-
 scripts/Makefile.vmlinux                     |  27 +-
 scripts/Makefile.warn                        |  28 +-
 scripts/basic/.gitignore                     |   1 +
 scripts/basic/Makefile                       |   2 +-
 scripts/basic/depcheck.c                     | 442 +++++++++++++++
 scripts/check-function-names.sh              |   3 +-
 scripts/elf-parse.c                          |  48 +-
 scripts/elf-parse.h                          |  19 +
 scripts/kallsyms-sysmap.c                    | 269 ++++++++++
 scripts/kallsyms.c                           | 387 ++++++++++----
 scripts/kallsyms.h                           |  44 ++
 scripts/link-vmlinux.sh                      |  25 +-
 scripts/mksysmap                             |  94 ----
 scripts/mod/.gitignore                       |   1 +
 scripts/mod/Makefile                         |   9 +
 scripts/mod/modpost.c                        | 757 ++++++++++++++++++++------
 scripts/mod/modpost.h                        |   2 +
 scripts/mod/module-offsets.c                 |  35 ++
 scripts/mod/sumversion.c                     |  57 +-
 scripts/tags.sh                              |   5 +-
 tools/objtool/Makefile                       |   2 +-
 tools/objtool/check.c                        | 767 ++++++++++++++++++++-------
 tools/objtool/elf.c                          | 242 ++++++++-
 tools/objtool/include/objtool/elf.h          |   4 +
 tools/objtool/include/objtool/objtool.h      |   3 +-
 tools/objtool/objtool.c                      |   1 -
 47 files changed, 2884 insertions(+), 682 deletions(-)

---
base-commit: 28924df2a08f440c73991b83028032c901de2ae4
change-id: 20260904-build-speedup-25e11a00b3d0

Best regards,

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

PATCH 1/23 scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

As a result this regexp has never matched and every kernel since v6.18 has carried one kallsyms entries for every MODULE_INFO() declaration in the kernel whether the modules are compiled or not.

That's 5,810 entries for an x86 defconfig build and 15,200 for arm64.

On x86 defconfig that is 113 KiB of kallsyms tables and 32 KiB of bzImage, and every lookup walks past them.

Fix the pattern.

Fixes 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped")

No measurable change in build time, the smaller tables are not on any path the build waits for.

Assisted-by LLM
---
 scripts/mksysmap | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/mksysmap +1 -1
index c4531eacde20..56a8b8bbdb37 100755
@@ -83,7 +83,7 @@
 / _SDA2_BASE_$/d
 
 # MODULE_INFO()
-/ __UNIQUE_ID_modinfo[0-9]*$/d
+/ __UNIQUE_ID_modinfo_[0-9]*$/d
 
 # ---------------------------------------------------------------------------
 # Ignored patterns
Signature · 1 line
2.55.0
maintainer Reviewed-by on v1 1/23
#2 lore raw

Re: [PATCH 01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

Quoted 16 lines

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

As a result this regexp has never matched and every kernel since v6.18 has carried one kallsyms entries for every MODULE_INFO() declaration in the kernel whether the modules are compiled or not.

That's 5,810 entries for an x86 defconfig build and 15,200 for arm64.

On x86 defconfig that is 113 KiB of kallsyms tables and 32 KiB of bzImage, and every lookup walks past them.

Quoted 7 lines

Fix the pattern.

Fixes 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped")

No measurable change in build time, the smaller tables are not on any path the build waits for.

For consistency, it would be nice to have the 'Fixes:' trailer at the beginning of the trailer block (that is: here.)

Quoted 8 lines
Assisted-by LLM
scripts/mksysmap +0 -0
index c4531eacde20..56a8b8bbdb37 100755

scripts/mksysmap line 89

Quoted 8 lines
scripts/mksysmap +1 -1
@@ -83,7 +83,7 @@
 / _SDA2_BASE_$/d
 
 # MODULE_INFO()
-/ __UNIQUE_ID_modinfo[0-9]*$/d
+/ __UNIQUE_ID_modinfo_[0-9]*$/d
 
 # ---------------------------------------------------------------------------
 # Ignored patterns

Thanks!

Signature · 1 line
Nicolas
#3 lore raw

Re: [PATCH 01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

Quoted 18 lines · Nicolas Schier
Quoted 18 lines

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

As a result this regexp has never matched and every kernel since v6.18 has carried one kallsyms entries for every MODULE_INFO() declaration in the kernel whether the modules are compiled or not.

That's 5,810 entries for an x86 defconfig build and 15,200 for arm64.

On x86 defconfig that is 113 KiB of kallsyms tables and 32 KiB of bzImage, and every lookup walks past them.

Fix the pattern.

Quoted 8 lines
Quoted 5 lines
Fixes 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped")

No measurable change in build time, the smaller tables are not on any path the build waits for.

For consistency, it would be nice to have the 'Fixes:' trailer at the beginning of the trailer block (that is: here.)

Yeah sorry my screw up when rejigging the commit message :)

Quoted 15 lines
Quoted 15 lines
Assisted-by LLM
scripts/mksysmap +1 -1
index c4531eacde20..56a8b8bbdb37 100755
@@ -83,7 +83,7 @@
 / _SDA2_BASE_$/d
 
 # MODULE_INFO()
-/ __UNIQUE_ID_modinfo[0-9]*$/d
+/ __UNIQUE_ID_modinfo_[0-9]*$/d
 
Quoted 6 lines

scripts/mksysmap line 89

Quoted 2 lines
scripts/mksysmap +0 -0
 # ---------------------------------------------------------------------------
 # Ignored patterns

Thanks!

Thanks!

Quoted 4 lines

--
Nicolas

--
Cheers, Lorenzo

maintainer Reviewed-by on v1 1/23
#4 lore raw

Re: [PATCH 01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

In reply to Lorenzo Stoakes (ARM)
Quoted 7 lines

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

Quoted 8 lines

As a result this regexp has never matched and every kernel since v6.18 has carried one kallsyms entries for every MODULE_INFO() declaration in the kernel whether the modules are compiled or not.

That's 5,810 entries for an x86 defconfig build and 15,200 for arm64.

On x86 defconfig that is 113 KiB of kallsyms tables and 32 KiB of bzImage, and every lookup walks past them.

Bummer :/

Quoted 6 lines

Fix the pattern.

Fixes 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped")

No measurable change in build time, the smaller tables are not on any path the build waits for.

I don't think this needs to be in the commit message, it could be below the fold, since it appears to be a valid fix on its own. Agree with Nicolas on adjusting the Fixes tag.

Is this worth Cc'ing stable for?

Quoted 2 lines
Assisted-by LLM
Signature · 2 lines
Cheers,
Nathan
#5 lore raw

Re: [PATCH 01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

Quoted 11 lines · Nathan Chancellor
Quoted 11 lines

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

As a result this regexp has never matched and every kernel since v6.18 has carried one kallsyms entries for every MODULE_INFO() declaration in the kernel whether the modules are compiled or not.

Quoted 6 lines
Quoted 4 lines

That's 5,810 entries for an x86 defconfig build and 15,200 for arm64.

On x86 defconfig that is 113 KiB of kallsyms tables and 32 KiB of bzImage, and every lookup walks past them.

Bummer :/

Yeah super easy to miss though I think!

Quoted 11 lines
Quoted 7 lines

Fix the pattern.

Fixes 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped")

No measurable change in build time, the smaller tables are not on any path the build waits for.

I don't think this needs to be in the commit message, it could be below the fold, since it appears to be a valid fix on its own. Agree with Nicolas on adjusting the Fixes tag.

Ack yeah I screwed this bit up sorry!

Quoted 2 lines

Is this worth Cc'ing stable for?

Yeah I wasn't sure, it's not like it breaks anything but you see stuff in kallsyms that you shouldn't.

So I'd say probably on balance yes we should actually?

Quoted 5 lines
Quoted 3 lines
Assisted-by LLM

Thanks!

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

maintainer
#6 lore raw

Re: [PATCH 01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

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

Commit 3e86e4d74c04 ("kbuild: keep .modinfo section in vmlinux.unstripped") keeps .modinfo symbols out of System.map and kallsyms, which assumes unique IDs have a format like '__UNIQUE_ID_modinfo123'.

However, commit afb026b6d35c ("compiler: Tweak __UNIQUE_ID() naming"), sent in the same cycle, changes this to '__UNIQUE_ID_modinfo_123'.

[...]

Applied to kbuild/linux.git (kbuild-fixes-unstable), thanks!

[01/23] scripts/mksysmap: drop the MODULE_INFO() symbols from kallsyms

        https://git.kernel.org/kbuild/c/3e2276de

Please look out for regression or issue reports or other follow up comments, as they may result in the patch/series getting dropped, reverted or modified (e.g. trailers).

The patch is applied to the kbuild-fixes-unstable branch and accepted pending wider testing in linux-next and any post-commit review; it will generally be moved to the kbuild-fixes branch within about a week if no issues are found.

Best regards,

Signature · 1 line
Nicolas
#7 lore raw

PATCH 2/23 scripts/mksysmap: fix escape of '$' in the __pi_ pattern

In reply to Lorenzo Stoakes (ARM)

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

$ grep __pi_\\$ /proc/kallsyms | sort -u
0000000000000000 d __pi_$d
0000000000000000 t __pi_$x

Fix the escaping properly.

Fixes b18b047002b7 ("kbuild: change scripts/mksysmap into sed script")

No measurable change in build time.

Assisted-by LLM
---
 scripts/mksysmap | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/mksysmap +1 -1
index 56a8b8bbdb37..856b26ba2ac0 100755
@@ -35,7 +35,7 @@
 / __efistub_/d
 
 # arm64 local symbols in PIE namespace
-/ __pi_\\$/d
+/ __pi_\$/d
 / __pi_\.L/d
 
 # arm64 local symbols in non-VHE KVM namespace
Signature · 1 line
2.55.0
maintainer Reviewed-by on v1 2/23
#8 lore raw

Re: [PATCH 02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

Quoted 28 lines

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

$ grep __pi_\\$ /proc/kallsyms | sort -u
0000000000000000 d __pi_$d
0000000000000000 t __pi_$x

Fix the escaping properly.

Fixes b18b047002b7 ("kbuild: change scripts/mksysmap into sed script")

No measurable change in build time.

Assisted-by LLM
scripts/mksysmap +0 -0
index 56a8b8bbdb37..856b26ba2ac0 100755

scripts/mksysmap line 41

Quoted 8 lines
scripts/mksysmap +1 -1
@@ -35,7 +35,7 @@
 / __efistub_/d
 
 # arm64 local symbols in PIE namespace
-/ __pi_\\$/d
+/ __pi_\$/d
 / __pi_\.L/d
 
 # arm64 local symbols in non-VHE KVM namespace

(Move 'Fixes:' to trailer block)

Signature · 1 line
Nicolas
#9 lore raw

Re: [PATCH 02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

Quoted 30 lines · Nicolas Schier
Quoted 30 lines

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

$ grep __pi_\\$ /proc/kallsyms | sort -u
0000000000000000 d __pi_$d
0000000000000000 t __pi_$x

Fix the escaping properly.

Fixes b18b047002b7 ("kbuild: change scripts/mksysmap into sed script")

No measurable change in build time.

Assisted-by LLM
scripts/mksysmap +0 -0
index 56a8b8bbdb37..856b26ba2ac0 100755
@@ -35,7 +35,7 @@
 / __efistub_/d
 
Quoted 8 lines

scripts/mksysmap line 41

Quoted 6 lines
scripts/mksysmap +1 -1
 # arm64 local symbols in PIE namespace
-/ __pi_\\$/d
+/ __pi_\$/d
 / __pi_\.L/d
 
 # arm64 local symbols in non-VHE KVM namespace

(Move 'Fixes:' to trailer block)

Yeah similar screw up. I think it was when perf times were appended per-patch but then then ended up on the fix patches + I yanked them bit didn't correct the tags, ugh!

Quoted 2 lines

Thanks! :)

Quoted 4 lines

--
Nicolas

--
Cheers, Lorenzo

#10 lore raw

Re: [PATCH 02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

In reply to Lorenzo Stoakes (ARM)
Quoted 14 lines

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

$ grep __pi_\\$ /proc/kallsyms | sort -u
0000000000000000 d __pi_$d
0000000000000000 t __pi_$x
Quoted 5 lines

Fix the escaping properly.

Fixes b18b047002b7 ("kbuild: change scripts/mksysmap into sed script")

No measurable change in build time.

Same comments as before.

Quoted 2 lines
Assisted-by LLM

Same thing, is this worth taking to stable? Truthfully, you could probably send these two changes separately from the series so that we could send them to Linus with the other pending Kbuild fixes, unless there are objections from Linus or Nicolas on taking that route? Shaving two patches off of an ~20 patch series is a 10% reduction so seems worth it?

I'll review some of the other low hanging fruit now so that we can start chunking this series out, since I too care deeply about build times.

Signature · 2 lines
Cheers,
Nathan
#11 lore raw

Re: [PATCH 02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

Quoted 14 lines · Nathan Chancellor
Quoted 14 lines

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

$ grep __pi_\\$ /proc/kallsyms | sort -u
0000000000000000 d __pi_$d
0000000000000000 t __pi_$x
Quoted 7 lines
Quoted 5 lines

Fix the escaping properly.

Fixes b18b047002b7 ("kbuild: change scripts/mksysmap into sed script")

No measurable change in build time.

Same comments as before.

Yeah sorry same screw up!

Quoted 5 lines
Quoted 3 lines
Assisted-by LLM

Same thing, is this worth taking to stable? Truthfully, you could

Ack I think it's probably worth it yes like patch 1.

Quoted 5 lines

probably send these two changes separately from the series so that we could send them to Linus with the other pending Kbuild fixes, unless there are objections from Linus or Nicolas on taking that route? Shaving two patches off of an ~20 patch series is a 10% reduction so seems worth it?

Patch 8 relies on 1 + 2, so as long as that ordering was enforced then that's OK.

I mean if these go as hotfixes then we naturally get that ordering of cousre!

Quoted 3 lines

I'll review some of the other low hanging fruit now so that we can start chunking this series out, since I too care deeply about build times.

Thanks!

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

maintainer
#12 lore raw

Re: [PATCH 02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

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

Commit b18b047002b7 ("kbuild: change scripts/mksysmap into sed script") converted scripts/mksysmap from a shell script to a sed script.

However an error was made - escaping of '$' required \\ escaping in shell but only \ in a sed script.

This was mostly corrected in commit 7a6c355b55c0 ("scripts/mksysmap: Fix escape chars '$'"), but this fix missed arm64 PIE namespace local symbols like __pi_$x and __pi_$d which appear in System.mapand /proc/kallsyms:

[...]

Applied to kbuild/linux.git (kbuild-fixes-unstable), thanks!

[02/23] scripts/mksysmap: fix escape of '$' in the __pi_ pattern

        https://git.kernel.org/kbuild/c/b99d1f50

Please look out for regression or issue reports or other follow up comments, as they may result in the patch/series getting dropped, reverted or modified (e.g. trailers).

The patch is applied to the kbuild-fixes-unstable branch and accepted pending wider testing in linux-next and any post-commit review; it will generally be moved to the kbuild-fixes branch within about a week if no issues are found.

Best regards,

Signature · 1 line
Nicolas
#13 lore raw

PATCH 3/23 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.4s    10.8s    -0.55s (-5%)
  x86 defconfig, touch mm/vma.c, clang     11.4s    10.7s    -0.66s (-6%)
  x86 defconfig, clean, gcc                30.3s    29.5s    -0.80s (-3%)
  x86 defconfig, clean, clang              30.3s    29.7s    -0.62s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    46.2s    45.3s    -0.91s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  44.2s    42.9s     -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
#14 lore raw

PATCH 4/23 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.8s     9.9s    -0.92s (-8%)
  x86 defconfig, touch mm/vma.c, clang     10.7s     9.5s     -1.2s (-11%)
  x86 defconfig, clean, gcc                29.5s    28.7s    -0.81s (-3%)
  x86 defconfig, clean, clang              29.7s    28.6s     -1.1s (-4%)
  x86 allmodconfig, touch mm/vma.c, gcc    45.3s    44.0s     -1.3s (-3%)
  x86 allmodconfig, touch mm/vma.c, clang  42.9s    40.2s     -2.7s (-6%)
Assisted-by LLM
---
 scripts/kallsyms.c      | 97 ++++++++++++++++++++++++++++++++++++++-----------
 scripts/link-vmlinux.sh |  2 +-
 2 files changed, 77 insertions(+), 22 deletions(-)
scripts/kallsyms.c +76 -21
index 350d118c3b9e..61c5eb537ed4 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,40 @@ static void output_label(const char *label)
 	printf("%s:\n", label);
 }
 
+static void write_bin(FILE *file, const void *data, size_t len)
+{
+	if (fwrite(data, 1, len, file) == len)
+		return;
+
+	perror("kallsyms: write");
+	exit(EXIT_FAILURE);
+}
+
+static void write_byte_bin(FILE *file, unsigned char byte)
+{
+	write_bin(file, &byte, 1);
+}
+
+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 +408,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 +428,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 +452,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);
+			write_byte_bin(out_bin_file, table[i]->len);
 			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);
+			write_byte_bin(out_bin_file, (table[i]->len & 0x7F) | 0x80);
+			write_byte_bin(out_bin_file, (table[i]->len >> 7) & 0x7F);
 			off += table[i]->len + 2;
 		}
-		for (k = 0; k < table[i]->len; k++)
-			printf(", 0x%02x", table[i]->sym[k]);
+		write_bin(out_bin_file, table[i]->sym, table[i]->len);
 
 		/*
 		 * 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 +482,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);
+		write_bin(out_bin_file, buf, strlen(buf) + 1);
 		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 +523,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++) {
+		write_byte_bin(out_bin_file, table[i]->seq >> 16);
+		write_byte_bin(out_bin_file, table[i]->seq >> 8);
+		write_byte_bin(out_bin_file, table[i]->seq >> 0);
+	}
+	write_incbin(out_bin_name, bin_start, bin_pos(out_bin_file));
 	printf("\n");
 }
 
@@ -798,6 +838,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 +856,26 @@ 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);
+
+	if (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

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

I'm finally going through this series, because I do care about build speed, so I love the concept.

However, I haven't actually applied it and tried it, I'm just reading the patches.

And this one triggered something:

Quoted 8 lines · 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.

It strikes me that this is clearly a bit faster, but it still seems to be not really fixing the underlying silliness of that code.

Wouldn't it be much better to actually create an object file directly? Afaik, the *only* think we ever do with that kallsyms-generated file is to immediately assemble it into an object file, because the actual asm file is useless to anybody.

And we already require libelf as part of the build, and we already kind of do things like that with gendwarfksyms.

Don't get my wrong: I think going through an asm file was very much the right thing originally: not every architecture used ELF in the first place, and when scripting things like this the current situation makes 100% sense.

And no sane human wants to deal with this kind of grotty detail and spend the effort on writing an ELF file writer.

But when there's a LLM that was used to find these things and help fix them up, and it's something this mechanical and the result really isn't ever human-readable and never has been, I feel like the obvious step would be to just ask the little helper bot to switch the whole kallsyms to using libelf-devel and writing an object file directly.

I don't think anybody has any deep emotional ties to the current kallsyms code and that horrific step of the kernel build, do they?

Linus

#16 lore raw

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

Quoted 37 lines · Linus Torvalds

I'm finally going through this series, because I do care about build speed, so I love the concept.

However, I haven't actually applied it and tried it, I'm just reading the patches.

And this one triggered something:

Quoted 8 lines · 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.

It strikes me that this is clearly a bit faster, but it still seems to be not really fixing the underlying silliness of that code.

Wouldn't it be much better to actually create an object file directly? Afaik, the *only* think we ever do with that kallsyms-generated file is to immediately assemble it into an object file, because the actual asm file is useless to anybody.

And we already require libelf as part of the build, and we already kind of do things like that with gendwarfksyms.

Don't get my wrong: I think going through an asm file was very much the right thing originally: not every architecture used ELF in the first place, and when scripting things like this the current situation makes 100% sense.

And no sane human wants to deal with this kind of grotty detail and spend the effort on writing an ELF file writer.

Quoted 8 lines

But when there's a LLM that was used to find these things and help fix them up, and it's something this mechanical and the result really isn't ever human-readable and never has been, I feel like the obvious step would be to just ask the little helper bot to switch the whole kallsyms to using libelf-devel and writing an object file directly.

I don't think anybody has any deep emotional ties to the current kallsyms code and that horrific step of the kernel build, do they?

No, but I wonder if it's really worth going all the way. And I did ask the LLM about this too (of course :)

The way it works now there's still a bunch of .long offset entries in the assembly which can actually be put into the binary file (the series generates a binary file for the byte tables and includes using .incbin).

So mostly it's binary already.

If we tried to generate an ELF file directly there'd be complications (LLM says e_flags and fun with arch-specific ABIs, plus arch's relocation type for _text-relative base).

I don't think there'd be much of a win for the added complexity (and I am nervous of fiddling with arch-specific stuff), BUT, can definitely put those remaining .long entries in the binary too so the assembly is absolutely minimal.

LLM says there's 200k of those, so does seem worthwhile, I'll do that for v2!

Quoted 2 lines

Linus

--
Cheers, Lorenzo

#17 lore raw

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

Quoted 6 lines · Lorenzo Stoakes (ARM)

...BUT, can definitely put
those remaining .long entries in the binary too so the assembly is absolutely minimal.

LLM says there's 200k of those, so does seem worthwhile, I'll do that for v2!

OK, correction, it turns out this isn't possible :) LLM found commit a081b5789255 ("kallsyms: Get rid of kallsyms relative base") which makes every offset a relocation against _text, which means these have to be kept in the assembly separately.

It takes .18s to parse those ~200k lines so it's not really a big deal :)

In any case it's not a huge time sink on build so it's no big deal to keep this as it is.

Quoted 6 lines
Quoted 3 lines

Linus

--
Cheers, Lorenzo

--
Cheers, Lorenzo

#18 lore raw

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

In reply to Lorenzo Stoakes (ARM)
Quoted 84 lines · On Tue, 08 Sep 2026 21:55:04 +0100 "Lorenzo Stoakes (ARM)" <[email protected]>…

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.8s     9.9s    -0.92s (-8%)
  x86 defconfig, touch mm/vma.c, clang     10.7s     9.5s     -1.2s (-11%)
  x86 defconfig, clean, gcc                29.5s    28.7s    -0.81s (-3%)
  x86 defconfig, clean, clang              29.7s    28.6s     -1.1s (-4%)
  x86 allmodconfig, touch mm/vma.c, gcc    45.3s    44.0s     -1.3s (-3%)
  x86 allmodconfig, touch mm/vma.c, clang  42.9s    40.2s     -2.7s (-6%)
Assisted-by LLM
---
 scripts/kallsyms.c      | 97 ++++++++++++++++++++++++++++++++++++++-----------
 scripts/link-vmlinux.sh |  2 +-
 2 files changed, 77 insertions(+), 22 deletions(-)
scripts/kallsyms.c +5 -2
index 350d118c3b9e..61c5eb537ed4 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,40 @@ static void output_label(const char *label)
 	printf("%s:\n", label);

scripts/kallsyms.c static void output_label(const char *label) · line 332

Quoted 10 lines
scripts/kallsyms.c +8 -0
 }
 
+static void write_bin(FILE *file, const void *data, size_t len)
+{
+	if (fwrite(data, 1, len, file) == len)
+		return;
+
+	perror("kallsyms: write");
+	exit(EXIT_FAILURE);
+}

It is pretty pointless checking the return value from fwrite(). Most of the time it is just doing a memcpy().
Instead call fflush() and the ferror() prior to the fclose(). (Or just rely on fclose() giving you that error status.)

David

#19 lore raw

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

Quoted 89 lines · David Laight
Quoted 86 lines · On Tue, 08 Sep 2026 21:55:04 +0100 "Lorenzo Stoakes (ARM)" <[email protected]>…

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.8s     9.9s    -0.92s (-8%)
  x86 defconfig, touch mm/vma.c, clang     10.7s     9.5s     -1.2s (-11%)
  x86 defconfig, clean, gcc                29.5s    28.7s    -0.81s (-3%)
  x86 defconfig, clean, clang              29.7s    28.6s     -1.1s (-4%)
  x86 allmodconfig, touch mm/vma.c, gcc    45.3s    44.0s     -1.3s (-3%)
  x86 allmodconfig, touch mm/vma.c, clang  42.9s    40.2s     -2.7s (-6%)
Assisted-by LLM
---
 scripts/kallsyms.c      | 97 ++++++++++++++++++++++++++++++++++++++-----------
 scripts/link-vmlinux.sh |  2 +-
 2 files changed, 77 insertions(+), 22 deletions(-)
scripts/kallsyms.c +5 -2
index 350d118c3b9e..61c5eb537ed4 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,40 @@ static void output_label(const char *label)
 	printf("%s:\n", label);
 }
 
Quoted 13 lines

scripts/kallsyms.c static void output_label(const char *label) · line 332

Quoted 8 lines
scripts/kallsyms.c +8 -0
+static void write_bin(FILE *file, const void *data, size_t len)
+{
+	if (fwrite(data, 1, len, file) == len)
+		return;
+
+	perror("kallsyms: write");
+	exit(EXIT_FAILURE);
+}

It is pretty pointless checking the return value from fwrite(). Most of the time it is just doing a memcpy().
Instead call fflush() and the ferror() prior to the fclose(). (Or just rely on fclose() giving you that error status.)

Ack, will fix up in v2.

Quoted 2 lines

David

--
Cheers, Lorenzo

#20 lore raw

Re: [4/23] kallsyms: output binary data to speed output and kallsyms assembly

In reply to David Laight

…

Quoted 1 line
Quoted 1 line

+++ b/scripts/kallsyms.c

…

Quoted 5 lines
Quoted 5 lines
scripts/kallsyms.c +5 -0
+static void write_bin(FILE *file, const void *data, size_t len)
+{
+	if (fwrite(data, 1, len, file) == len)
+		return;
+
Quoted 8 lines

scripts/kallsyms.c static void output_label(const char *label) · line 332

Quoted 3 lines
scripts/kallsyms.c +3 -0
+	perror("kallsyms: write");
+	exit(EXIT_FAILURE);
+}

It is pretty pointless checking the return value from fwrite(). Most of the time it is just doing a memcpy().
Instead call fflush() and the ferror() prior to the fclose(). (Or just rely on fclose() giving you that error status.)

How does such a development view fit to other known programming advices?
https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err33-c/
https://cwe.mitre.org/data/definitions/252.html

Regards,
Markus

A message that is not in the archive (sent off-list or not yet received): [email protected]

#22 lore raw

Re: [PATCH 04/23] kallsyms: output binary data to speed output and kallsyms assembly

Quoted 41 lines · On Tue, Sep 08, 2026 at 09:10:43PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Binary file out_bin_file is opened with "w" instead of "wb", which can corrupt output on host platforms that translate newlines. --

commit 8a28ee77f330c86631e4b29d33b55c73c4d0f181
Author: Lorenzo Stoakes (ARM) <[email protected]>

kallsyms: output binary data to speed output and kallsyms assembly

This commit modifies the kallsyms tool to output byte tables as binary data and import them into assembly using the .incbin directive. This is intended to significantly reduce the size of the generated assembly file and improve assembly times during the kernel build process.

Quoted 3 lines
scripts/kallsyms.c +0 -0

[ ... ]

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

Quoted 10 lines
scripts/kallsyms.c +3 -1
@@ -813,14 +856,26 @@ 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");

[Severity: Medium]
Will this cause the output to become corrupted on host platforms that translate newlines?

Since the file handles raw binary table data, opening it in text mode ("w") instead of binary mode ("wb") might cause newline bytes (0x0A) in the binary symbol tables to be transparently translated into carriage return and newline sequences (0x0D, 0x0A) on platforms that do not use POSIX standard text semantics, such as MSYS2 or MinGW.

Quoted 4 lines

Could this be changed to use "wb" to ensure portable byte-for-byte correctness on all build hosts and prevent corrupted vmlinux images or assembler errors?

Linux kernel requires a POSIX host where 'b' is a no-op so this is nonsense.

Quoted 10 lines

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

Quoted 7 lines
scripts/kallsyms.c +5 -0
+	if (!out_bin_file) {
+		perror(out_bin_name);
+		exit(EXIT_FAILURE);
+	}
+
 	read_map(argv[optind]);
 	shrink_table();

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4

--
Cheers, Lorenzo

#23 lore raw

PATCH 5/23 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, median of 3:

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

  x86 defconfig, touch mm/vma.c, gcc    10.02s     9.83s    -0.19s (-2%)
  x86 defconfig, touch mm/vma.c, clang   9.52s     9.24s    -0.28s (-3%)
  x86 defconfig, clean, gcc             28.71s    28.58s    -0.13s (-0.5%)
  x86 defconfig, clean, clang           28.69s    28.31s    -0.38s (-1%)
  x86 allmodconfig, touch mm/vma.c, cl  40.52s    39.83s    -0.69s (-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
#24 lore raw

Re: [PATCH 05/23] kbuild: do not sort nm output where the order is irrelevant

Quoted 43 lines

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, median of 3:

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

Quoted 8 lines
  x86 defconfig, touch mm/vma.c, gcc    10.02s     9.83s    -0.19s (-2%)
  x86 defconfig, touch mm/vma.c, clang   9.52s     9.24s    -0.28s (-3%)
  x86 defconfig, clean, gcc             28.71s    28.58s    -0.13s (-0.5%)
  x86 defconfig, clean, clang           28.69s    28.31s    -0.38s (-1%)
  x86 allmodconfig, touch mm/vma.c, cl  40.52s    39.83s    -0.69s (-2%)
Assisted-by LLM

This seems like it is worth taking now but I would appreciate an x86 maintainer ack.

Signature · 2 lines
Cheers,
Nathan
#25 lore raw

PATCH 6/23 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.8s 9.4s -0.43s (-4%)

  x86 defconfig, clean, gcc                28.6s    28.1s    -0.47s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    44.0s    42.7s     -1.3s (-3%)

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

Assisted-by LLM
---
 Makefile                 | 4 +++-
 scripts/Makefile.vmlinux | 3 ++-
 scripts/link-vmlinux.sh  | 6 ++++++
 3 files changed, 11 insertions(+), 2 deletions(-)
Makefile +3 -1
index 66654fa71655..85eb2fd026cb 100644
@@ -1263,8 +1263,10 @@ 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
+LDFLAGS_vmlinux_relocs := --emit-relocs
 endif
+export LDFLAGS_vmlinux_relocs
 
 # Align the architecture of userspace programs with the kernel
 USERFLAGS_FROM_KERNEL := --target=%
scripts/Makefile.vmlinux +2 -1
index fcae1e432d9a..4b54aaeca65d 100644
@@ -64,7 +64,8 @@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink)
 
 # Final link of vmlinux with optional arch pass after final link
 cmd_link_vmlinux =							\
-	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@";	\
+	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@"	\
+	   "$(LDFLAGS_vmlinux_relocs)";					\
 	$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true)
 
 targets += vmlinux.unstripped .vmlinux.export.o
scripts/link-vmlinux.sh +6 -0
index 970ca10f8fa9..09c5222ccb94 100755
@@ -32,6 +32,7 @@ LD="$1"
 KBUILD_LDFLAGS="$2"
 LDFLAGS_vmlinux="$3"
 VMLINUX="$4"
+LDFLAGS_vmlinux_relocs="$5"
 
 is_enabled() {
 	grep -q "^$1=y" include/config/auto.conf
@@ -96,6 +97,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && [ -n "${LDFLAGS_vmlinux_relocs}" ]; then
+		ldflags="${ldflags} ${wl}${LDFLAGS_vmlinux_relocs}"
+	fi
+
 	if [ -n "${generate_map}" ];  then
 		ldflags="${ldflags} ${wl}-Map=vmlinux.map"
 	fi
Signature · 1 line
2.55.0
#26 lore raw

Re: [PATCH 06/23] kbuild: only emit vmlinux relocations when required

Quoted 72 lines

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.8s 9.4s -0.43s (-4%)

  x86 defconfig, clean, gcc                28.6s    28.1s    -0.47s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    44.0s    42.7s     -1.3s (-3%)

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

Assisted-by LLM
Makefile +3 -1
index 9bd226726358..de095b11e20a 100644
@@ -1266,8 +1266,10 @@ 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
+LDFLAGS_vmlinux_relocs := --emit-relocs
 endif
+export LDFLAGS_vmlinux_relocs
 
 # Align the architecture of userspace programs with the kernel
 USERFLAGS_FROM_KERNEL := --target=%
scripts/Makefile.vmlinux +2 -1
index fcae1e432d9a..4b54aaeca65d 100644
@@ -64,7 +64,8 @@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink)
 
 # Final link of vmlinux with optional arch pass after final link
 cmd_link_vmlinux =							\
-	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@";	\
+	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@"	\
+	   "$(LDFLAGS_vmlinux_relocs)";					\
 	$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true)
 
 targets += vmlinux.unstripped .vmlinux.export.o
scripts/link-vmlinux.sh +1 -0
index 970ca10f8fa9..09c5222ccb94 100755
@@ -32,6 +32,7 @@ LD="$1"
 KBUILD_LDFLAGS="$2"
 LDFLAGS_vmlinux="$3"
 VMLINUX="$4"
+LDFLAGS_vmlinux_relocs="$5"
 
 is_enabled() {
 	grep -q "^$1=y" include/config/auto.conf

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

Quoted 8 lines
scripts/link-vmlinux.sh +5 -0
@@ -96,6 +97,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && [ -n "${LDFLAGS_vmlinux_relocs}" ]; then
+		ldflags="${ldflags} ${wl}${LDFLAGS_vmlinux_relocs}"
+	fi
+

We don't use LDFLAGS_vmlinux_relocs anywhere else, so do we even need this whole dance to just end up with the equivalent of

  if [ "${output}" = "${VMLINUX}" ] && is_enabled CONFIG_ARCH_VMLINUX_NEEDS_RELOCS; then
    ldflags="${ldflags} ${wl}--emit-relocs"
  fi

which would make this diff much simpler?

That being said, Sashiko makes a comment that may be relevant, have not verified though:

https://sashiko.dev/#/message/[email protected]

Signature · 2 lines
Cheers,
Nathan
#27 lore raw

Re: [PATCH 06/23] kbuild: only emit vmlinux relocations when required

Quoted 84 lines · Nathan Chancellor
Quoted 72 lines

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.8s 9.4s -0.43s (-4%)

  x86 defconfig, clean, gcc                28.6s    28.1s    -0.47s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    44.0s    42.7s     -1.3s (-3%)

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

Assisted-by LLM
Makefile +3 -1
index 9bd226726358..de095b11e20a 100644
@@ -1266,8 +1266,10 @@ 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
+LDFLAGS_vmlinux_relocs := --emit-relocs
 endif
+export LDFLAGS_vmlinux_relocs
 
 # Align the architecture of userspace programs with the kernel
 USERFLAGS_FROM_KERNEL := --target=%
scripts/Makefile.vmlinux +2 -1
index fcae1e432d9a..4b54aaeca65d 100644
@@ -64,7 +64,8 @@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink)
 
 # Final link of vmlinux with optional arch pass after final link
 cmd_link_vmlinux =							\
-	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@";	\
+	$< "$(LD)" "$(KBUILD_LDFLAGS)" "$(LDFLAGS_vmlinux)" "$@"	\
+	   "$(LDFLAGS_vmlinux_relocs)";					\
 	$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true)
 
 targets += vmlinux.unstripped .vmlinux.export.o
scripts/link-vmlinux.sh +1 -0
index 970ca10f8fa9..09c5222ccb94 100755
@@ -32,6 +32,7 @@ LD="$1"
 KBUILD_LDFLAGS="$2"
 LDFLAGS_vmlinux="$3"
 VMLINUX="$4"
+LDFLAGS_vmlinux_relocs="$5"
 
 is_enabled() {
 	grep -q "^$1=y" include/config/auto.conf

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

Quoted 8 lines
scripts/link-vmlinux.sh +5 -0
@@ -96,6 +97,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && [ -n "${LDFLAGS_vmlinux_relocs}" ]; then
+		ldflags="${ldflags} ${wl}${LDFLAGS_vmlinux_relocs}"
+	fi
+

We don't use LDFLAGS_vmlinux_relocs anywhere else, so do we even need this whole dance to just end up with the equivalent of

Quoted 5 lines
  if [ "${output}" = "${VMLINUX}" ] && is_enabled CONFIG_ARCH_VMLINUX_NEEDS_RELOCS; then
    ldflags="${ldflags} ${wl}--emit-relocs"
  fi

which would make this diff much simpler?

Nice, big simplification then :) fixed up for v2.

Quoted 5 lines

That being said, Sashiko makes a comment that may be relevant, have not verified though:

https://sashiko.dev/#/message/[email protected]

Yeah checked and not relevant :) I cc'd you on my mostly-for-my-own-record-keeping reply to sashiko on that one :)

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#29 lore raw

Re: [PATCH 06/23] kbuild: only emit vmlinux relocations when required

+cc Nathan as you flagged in reply (will reply there separately also! Doing a sashiko pass right now).

Quoted 37 lines · On Tue, Sep 08, 2026 at 09:12:04PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Inconsistent kallsyms data build failure on RISC-V due to missing --emit-relocs in temporary links. --

commit 4ec1c86acad0eaa0b52dbb5d1c138c6e094e48d0
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: only emit vmlinux relocations when required

This commit modifies the kernel build process to only append the --emit-relocs parameter during the final vmlinux link. Symbol tables of trial links preceding it no longer receive this parameter, which reduces build time since GNU ld is slow at emitting relocation tables.

Quoted 4 lines
scripts/link-vmlinux.sh +0 -0
index 970ca10f8fa90..09c5222ccb941 100755

[ ... ]

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

Quoted 9 lines
scripts/link-vmlinux.sh +5 -0
@@ -96,6 +97,11 @@ vmlinux_link()
 		ldflags="${ldflags} ${wl}--strip-debug"
 	fi
 
+	# Only the final link actually requires the relocations.
+	if [ "${output}" = "${VMLINUX}" ] && [ -n "${LDFLAGS_vmlinux_relocs}" ]; then
+		ldflags="${ldflags} ${wl}${LDFLAGS_vmlinux_relocs}"
+	fi
+

[Severity: Low]
Does omitting --emit-relocs from the temporary links cause an "Inconsistent kallsyms data" build failure on RISC-V?

On RISC-V, GNU ld disables linker relaxations when --emit-relocs is used.

Quoted 7 lines

If the temporary .tmp_vmlinux* links in vmlinux_link() are built without --emit-relocs, they will be built with relaxations enabled. Because the final vmlinux link uses --emit-relocs, it is built with relaxations disabled.

Can this difference alter instruction sizes and shift symbol addresses, causing the final System.map check against kallsyms symbols to fail?

This was checked empirically between --emit-relocs passed/not and confirmed there was no change whatsoever with identical size and sizes.

The code doesn't do anything differently. So this claim is false.

Quoted 7 lines

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

Quoted 4 lines
scripts/link-vmlinux.sh +0 -0
 	if [ -n "${generate_map}" ];  then
 		ldflags="${ldflags} ${wl}-Map=vmlinux.map"
 	fi

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6

--
Cheers, Lorenzo

#30 lore raw

PATCH 7/23 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 kallyms.

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
#31 lore raw

PATCH 8/23 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.4s     8.9s    -0.45s (-5%)
  x86 defconfig, touch mm/vma.c, clang      9.2s     8.1s     -1.1s (-12%)
  x86 defconfig, clean, gcc                28.1s    27.6s    -0.51s (-2%)
  x86 defconfig, clean, clang              28.2s    27.2s     -1.0s (-4%)
  x86 allmodconfig, touch mm/vma.c, gcc    42.7s    42.0s    -0.70s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  40.2s    38.1s     -2.1s (-5%)
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 09c5222ccb94..7e9d0676f59f 100755
@@ -124,11 +124,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
@@ -151,18 +155,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
#32 lore raw

Re: [PATCH 08/23] kallsyms: reimplement mksysmap in C

…

Quoted 2 lines

+++ b/scripts/kallsyms-sysmap.c

(quoted diff) +0 -0
@@ -0,0 +1,269 @@

…

scripts/kallsyms-sysmap.c line 262

Quoted 11 lines
scripts/kallsyms-sysmap.c new file +11 -0
+void sysmap_write(const struct sysmap *map, FILE *out)
+{
+	size_t i;
+
+	for (i = 0; i < map->nr_syms; i++) {
+		const struct sysmap_symbol *s = &map->syms[i];
+
+		fprintf(out, "%0*llx %c %s\n", map->addr_width, s->addr, s->type,
+			s->name);
+	}
+}

…

How do you think about to achieve more complete error detection?
https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err33-c/
https://cwe.mitre.org/data/definitions/252.html

Regards,
Markus

#33 lore raw

Re: [PATCH 08/23] kallsyms: reimplement mksysmap in C

In reply to Lorenzo Stoakes (ARM)

…

Quoted 1 line

+++ b/scripts/kallsyms.c

…

Quoted 1 line
(quoted diff) +0 -0
@@ -852,13 +848,33 @@ int main(int argc, char **argv)

…

Quoted 11 lines
scripts/kallsyms.c +11 -0
+	in = argv[optind];
+	if (sysmap) {
+		sysmap_out = fopen(sysmap, "w");
+		if (!sysmap_out) {
+			perror(sysmap);
+			exit(EXIT_FAILURE);
+		}
+	}
+
+	if (optind + 1 == argc) {
+		read_elf(in, sysmap_out);

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

Quoted 10 lines
scripts/kallsyms.c +7 -0
+		if (fclose(sysmap_out)) {
+			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) {

…

How do you think about to avoid a bit duplicate source code by using a goto chain?
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/process/coding-style.rst?h=v7.3-rc2#n572

Regards,
Markus

#34 lore raw

Re: [PATCH 08/23] kallsyms: reimplement mksysmap in C

In reply to Lorenzo Stoakes (ARM)
Quoted 4 lines

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.

…

Quoted 2 lines

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

…

Are there further opportunities for parallel data processing for an improved processing pipeline in this software area?

Regards,
Markus

#35 lore raw

PATCH 9/23 kbuild: do not allocate .modinfo in vmlinux

In reply to Lorenzo Stoakes (ARM)

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        8.9s     8.8s    -0.16s (-2%)
  x86 defconfig, touch mm/vma.c, clang      8.1s     7.9s    -0.20s (-2%)
  x86 defconfig, clean, gcc                27.6s    27.5s    -0.13s (0%)
  x86 defconfig, clean, clang              27.2s    27.0s    -0.18s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    42.0s    41.6s    -0.40s (-1%)
Assisted-by LLM
---
 include/asm-generic/vmlinux.lds.h |  2 +-
 scripts/Makefile.vmlinux          | 24 ++++++------------------
 2 files changed, 7 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 +6 -18
index 4b54aaeca65d..1fc7a0ca8eaf 100644
@@ -90,11 +90,9 @@ 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.
+# none of the removed sections is allocated, so no segment is left empty
 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,21 +101,11 @@ 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.
+# use --dump-section to include non-allocated sections
 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
#36 lore raw

Re: [PATCH 09/23] kbuild: do not allocate .modinfo in vmlinux

Quoted 55 lines

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        8.9s     8.8s    -0.16s (-2%)
  x86 defconfig, touch mm/vma.c, clang      8.1s     7.9s    -0.20s (-2%)
  x86 defconfig, clean, gcc                27.6s    27.5s    -0.13s (0%)
  x86 defconfig, clean, clang              27.2s    27.0s    -0.18s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    42.0s    41.6s    -0.40s (-1%)
Assisted-by LLM
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 +0 -0
index 4b54aaeca65d..1fc7a0ca8eaf 100644

scripts/Makefile.vmlinux remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' · line 93

Quoted 6 lines
scripts/Makefile.vmlinux +1 -2
@@ -90,11 +90,9 @@ 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.
+# none of the removed sections is allocated, so no segment is left empty

I think we could just drop this comment, I don't think it is particularly helpful

Quoted 11 lines
scripts/Makefile.vmlinux +1 -2
 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,21 +101,11 @@ vmlinux: vmlinux.unstripped FORCE
 # modules.builtin.modinfo
 # ---------------------------------------------------------------------------
 

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

Quoted 10 lines
scripts/Makefile.vmlinux +1 -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.
+# use --dump-section to include non-allocated sections

Same thing here, I am not sure anyone will question '--dump-section' here. Otherwise, this seems reasonable. I was curious about the [email protected] until I read the objcopy manual but that probably is not worth a comment.

I can probably take this one faster than the rest if you want to put it early in the stack since it is pretty low hanging fruit and earlier it gets exposure to -next, the better.

Signature · 2 lines
Cheers,
Nathan
#37 lore raw

Re: [PATCH 09/23] kbuild: do not allocate .modinfo in vmlinux

Quoted 56 lines · Nathan Chancellor
Quoted 56 lines

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        8.9s     8.8s    -0.16s (-2%)
  x86 defconfig, touch mm/vma.c, clang      8.1s     7.9s    -0.20s (-2%)
  x86 defconfig, clean, gcc                27.6s    27.5s    -0.13s (0%)
  x86 defconfig, clean, clang              27.2s    27.0s    -0.18s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    42.0s    41.6s    -0.40s (-1%)
Assisted-by LLM
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 +0 -0
index 4b54aaeca65d..1fc7a0ca8eaf 100644
@@ -90,11 +90,9 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*'
 
Quoted 8 lines

scripts/Makefile.vmlinux remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' · line 93

Quoted 5 lines
scripts/Makefile.vmlinux +1 -2
 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.
+# none of the removed sections is allocated, so no segment is left empty

I think we could just drop this comment, I don't think it is particularly helpful

Ack!

Quoted 12 lines
Quoted 12 lines
scripts/Makefile.vmlinux +1 -2
 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,21 +101,11 @@ vmlinux: vmlinux.unstripped FORCE
 # modules.builtin.modinfo
 # ---------------------------------------------------------------------------
 
Quoted 15 lines

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

Quoted 10 lines
scripts/Makefile.vmlinux +1 -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.
+# use --dump-section to include non-allocated sections

Same thing here, I am not sure anyone will question '--dump-section' here. Otherwise, this seems reasonable. I was curious about the [email protected] until I read the objcopy manual but that probably is not worth a comment.

Ack too.

Quoted 4 lines

I can probably take this one faster than the rest if you want to put it early in the stack since it is pretty low hanging fruit and earlier it gets exposure to -next, the better.

Sure sounds good, the sooner we get these in -next the better.

I was planning to go through feedback/sashiko (+ give a bit more time for people to respond) before doing a v2, but I guess you could put this to -next as-is, given v2 will just be stripping comments here (as it stands anyway!)

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#38 lore raw

PATCH 10/23 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           0.94s    0.92s    -0.02s (-2%)
  x86 defconfig, no-op make, clang          1.1s     1.1s    -0.01s (-1%)
  x86 allmodconfig, no-op make, gcc        13.0s    12.3s    -0.64s (-5%)
  x86 allmodconfig, no-op make, clang      13.8s    13.2s    -0.64s (-5%)
  x86 allmodconfig, touch mm/vma.c, gcc    41.6s    40.9s    -0.70s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  38.1s    37.6s    -0.52s (-1%)
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
#39 lore raw

PATCH 11/23 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           0.92s    0.62s    -0.29s (-32%)
  x86 defconfig, no-op make, clang          1.1s    0.78s    -0.31s (-29%)
  x86 allmodconfig, no-op make, gcc        12.3s    11.2s     -1.2s (-10%)
  x86 allmodconfig, no-op make, clang      13.2s    11.9s     -1.3s (-10%)
  x86 allmodconfig, touch mm/vma.c, gcc    40.9s    40.6s     -0.3s (-1%)
  x86 allmodconfig, touch mm/vma.c, clang  37.6s    36.5s     -1.0s (-3%)
Assisted-by LLM
---
 Makefile                 |   1 +
 scripts/Makefile.build   |  14 +-
 scripts/basic/.gitignore |   1 +
 scripts/basic/Makefile   |   2 +-
 scripts/basic/depcheck.c | 442 +++++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 458 insertions(+), 2 deletions(-)
Makefile +1 -0
index 85eb2fd026cb..56e56bea53c3 100644
@@ -2239,6 +2239,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 +442 -0

442 lines not on this page · raw message

Signature · 1 line
2.55.0
#40 lore raw

Re: [PATCH 11/23] kbuild: implement and use depcheck to check dependency timestamps

Quoted 7 lines · 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.

Side note: from some kernel build profiles I did long ago, I have this memory of it being made much worse by the fact that we use

    "$(wildcard xyzzy)"

for all our config header files in those .cmd.o files. That then causes extra work for 'make' for all of this.

And we do that 'wildcard' thing not because we want to actually match a pattern, but because that was the only way to have 'make' not complain about missing config headers.

I'm not even sure the original reason for it is relevant any more - this is all a very dim memory from years and years ago when I actually tried to look at profiles of 'make' itself (normally when I do kernel build profiles I only look at the what the kernel part of the build is, not user mode).

I just tried removing the 'wildcard' generation from scripts/basic/fixdep.c and the kernel build didn't care about it at all. The whole 'wildcard' trick goes all the way back to the original commit that added that whole 'fixdep.c' phase.

Maybe the whole thing is entirely stale now and should be removed. I probably just didn't trigger the situation where those extra 'wildcard' things matter. That whole thing is from a quarter century ago, and nobody has dared look at that code since..

Or maybe 'make' is better at those wildcards these days - or other things have shifted.

From those dim memories, make spent a lot of time doing filesystem lookups (directory reading and 'stat()' calls - the wildcard thing triggered more getdents calls), but even more time just in string handling.

Linus

#41 lore raw

Re: [PATCH 11/23] kbuild: implement and use depcheck to check dependency timestamps

Quoted 32 lines · Linus Torvalds
Quoted 7 lines · 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.

Side note: from some kernel build profiles I did long ago, I have this memory of it being made much worse by the fact that we use

    "$(wildcard xyzzy)"

for all our config header files in those .cmd.o files. That then causes extra work for 'make' for all of this.

And we do that 'wildcard' thing not because we want to actually match a pattern, but because that was the only way to have 'make' not complain about missing config headers.

I'm not even sure the original reason for it is relevant any more - this is all a very dim memory from years and years ago when I actually tried to look at profiles of 'make' itself (normally when I do kernel build profiles I only look at the what the kernel part of the build is, not user mode).

I just tried removing the 'wildcard' generation from scripts/basic/fixdep.c and the kernel build didn't care about it at all. The whole 'wildcard' trick goes all the way back to the original commit that added that whole 'fixdep.c' phase.

Quoted 4 lines

Maybe the whole thing is entirely stale now and should be removed. I probably just didn't trigger the situation where those extra 'wildcard' things matter. That whole thing is from a quarter century ago, and nobody has dared look at that code since..

Yeah, unfortunately it seems that it's still required - without it make seems to treat a missing target with an empty rule as if it were updated, so without the wildcard every object that references an unset option results in a rebuild.

Quoted 8 lines

Or maybe 'make' is better at those wildcards these days - or other things have shifted.

From those dim memories, make spent a lot of time doing filesystem lookups (directory reading and 'stat()' calls - the wildcard thing triggered more getdents calls), but even more time just in string handling.

The depcheck commit ("kbuild: implement and use depcheck to check dependency timestamps") actually fixes the overhead issue :) it stops make seeing those dependency lists at all for stuff that's up to date so the parse cost just goes away.

After that commit make only sees actually stale stuff.

The obvious question here is 'does depcheck make the wildcard stuff unnecessary then?' - and sadly no, because there's still places where make includes .cmd files directly without using depcheck.

But TL;DR is the overhead is gone.

Quoted 2 lines

Linus

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#43 lore raw

Re: [PATCH 11/23] kbuild: implement and use depcheck to check dependency timestamps

Quoted 24 lines · On Tue, Sep 08, 2026 at 09:10:37PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Missing return value check on fwrite() allows silent data corruption of the generated makefile fragment.
- [Medium] Use of st.st_mtim breaks host tool compilation on non-Linux platforms (e.g., macOS) where the member is named st_mtimespec. --

commit 6f34a9bb88096e341033a46a588226f8854a9a98
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: implement and use depcheck to check dependency timestamps

This commit implements scripts/basic/depcheck in C to speed up checking dependency timestamps for .cmd files. It reduces the work make has to do by generating fragments with only the saved command line for targets that are already up-to-date.

Quoted 5 lines
scripts/basic/depcheck.c new file +0 -0
new file mode 100644
index 0000000000000..5f9bbdff88032

[ ... ]

Quoted 2 lines
scripts/basic/depcheck.c new file +2 -0
+static const struct dep *lookup_dep(const char *path)
+{

[ ... ]

Quoted 9 lines

scripts/basic/depcheck.c line 162

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

[Severity: Medium]
Could accessing st.st_mtim directly break host tool compilation on non-Linux platforms? On systems like macOS, the member is typically named st_mtimespec instead of st_mtim, which might cause the build of depcheck to fail at the very beginning when cross-compiling the kernel.

Silly :)

It's a POSIX requirement.

Quoted 11 lines

[ ... ]

Quoted 3 lines
scripts/basic/depcheck.c new file +3 -0
+static bool target_is_fresh(const char *cmd_path, const char *buf, size_t len,
+			    size_t *deps_off)
+{

[ ... ]

scripts/basic/depcheck.c

Quoted 2 lines
scripts/basic/depcheck.c new file +2 -0
+	return deps_are_fresh(list, buf + len, &st.st_mtim);
+}

[Severity: Medium]
This shares the same st.st_mtim portability concern as lookup_dep() above.

Nothing compares at nanosecond ersolution.

Quoted 42 lines

[ ... ]

scripts/basic/depcheck.c line 386

Quoted 9 lines
scripts/basic/depcheck.c new file +9 -0
+static void write_without_deps(FILE *out, const char *buf, size_t len,
+			       size_t deps_off)
+{
+	const size_t tail_off = deps_block_end(buf, len, deps_off);
+
+	fwrite(buf, 1, deps_off, out);
+	fputc('\n', out);
+	fwrite(buf + tail_off, 1, len - tail_off, out);
+}

[Severity: High]
Are we missing a return value check for fwrite() here? If the tool runs out of disk space or hits a quota limit while writing the .depcheck.mk.tmp fragment, this could fail silently.

If the generated makefile fragment has silent data corruption, the build system might use incomplete dependency lists. Could this lead to the kernel being built from stale object files, potentially resulting in unpredictable runtime issues?

[ ... ]

Quoted 2 lines
scripts/basic/depcheck.c new file +2 -0
+int main(int argc, char **argv)
+{

[ ... ]

scripts/basic/depcheck.c line 442

Quoted 11 lines
scripts/basic/depcheck.c new file +11 -0
+	for (i = 2; i < argc; i++)
+		process(out, argv[i]);
+
+	if (fclose(out) || rename(tmp_path, argv[1])) {
+		perror(argv[1]);
+		unlink(tmp_path);
+		return 1;
+	}
+
+	return 0;
+}

[Severity: High]
Is relying on fclose() sufficient to catch the earlier fwrite() errors in write_without_deps()?

Quoted 4 lines

If a previous write failed (setting the stream's error indicator), fclose() does not necessarily return EOF if its final buffer flush succeeds or does no work. This could allow the program to exit successfully (0), masking the earlier write failures entirely.

There are valid, will fix to reflect the changes already in fixdep + kallsyms.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11

--
Cheers, Lorenzo

#44 lore raw

PATCH 12/23 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.

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.62s    0.46s    -0.17s (-27%)
  x86 defconfig, no-op make, clang         0.78s    0.53s    -0.25s (-32%)
  x86 defconfig, touch mm/vma.c, gcc        8.7s     8.5s    -0.17s (-2%)
  x86 defconfig, touch mm/vma.c, clang      7.9s     7.6s    -0.25s (-3%)
  x86 defconfig, clean, clang              27.0s    26.8s    -0.26s (-1%)
  x86 allmodconfig, no-op make, gcc        11.2s    11.0s    -0.18s (-2%)
  x86 allmodconfig, no-op make, clang      11.9s    11.6s    -0.28s (-2%)
  x86 allmodconfig, touch mm/vma.c, clang  36.5s    36.2s    -0.31s (-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                          | 77 +++++++++++++++++++++++++++++++++++
 scripts/Makefile.warn                 | 28 ++++++-------
 8 files changed, 128 insertions(+), 35 deletions(-)
Makefile +11 -12
index 56e56bea53c3..088e901f0a72 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,18 @@ 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.
-KBUILD_CFLAGS	+= $(call cc-option, -fno-stack-clash-protection)
+KBUILD_CFLAGS	+= $(if $(CONFIG_CC_HAS_NO_STACK_CLASH_PROTECTION),-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 +1033,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 +1051,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 +1159,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 +1239,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 +77 -0

89 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
#45 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 6 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 config CC_HAS_NO_PROFILE_FN_ATTR

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 10 lines
init/Kconfig +8 -0
 	def_bool $(success,echo '__attribute__((no_profile_instrument_function)) int x();' | $(CC) -x c - -c -o /dev/null -Werror)
 
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Signature · 2 lines
Cheers,
Nathan
#46 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 8 lines · Nathan Chancellor
Quoted 8 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 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)
 
Quoted 14 lines

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 8 lines
init/Kconfig +8 -0
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

Quoted 3 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Sounds good, yes.

Signature · 1 line
Nicolas
#47 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 9 lines · Nicolas Schier
Quoted 8 lines · Nathan Chancellor
Quoted 8 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 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)
 
Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
init/Kconfig +6 -0
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
Quoted 8 lines

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 2 lines
init/Kconfig +2 -0
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

(Sorry hadn't seen you'd replied also!)

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

I guess this bit can be a follow up potentially?

Quoted 6 lines
Quoted 4 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Sounds good, yes.

I can add a doc update as part of this series, unless you guys want to handle separately?

Quoted 3 lines

--
Nicolas

--
Cheers, Lorenzo

#48 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 26 lines · Lorenzo Stoakes (ARM)
Quoted 9 lines · Nicolas Schier
Quoted 8 lines · Nathan Chancellor
Quoted 8 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 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)
 
Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
init/Kconfig +6 -0
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
Quoted 8 lines

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 2 lines
init/Kconfig +2 -0
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

Quoted 8 lines

(Sorry hadn't seen you'd replied also!)

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

I guess this bit can be a follow up potentially?

yes, sure.

Quoted 9 lines
Quoted 6 lines
Quoted 4 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Sounds good, yes.

I can add a doc update as part of this series, unless you guys want to handle separately?

I don't think it has to be part of the series, it's long enough already. But if you want to prepare some docmentation about the preference of cc-option checks, feel free to go ahead or not.

Kind regards
Nicolas

#49 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 43 lines · Nicolas Schier
Quoted 26 lines · Lorenzo Stoakes (ARM)
Quoted 9 lines · Nicolas Schier
Quoted 8 lines · Nathan Chancellor
Quoted 8 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 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)
 
Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
init/Kconfig +6 -0
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
Quoted 8 lines

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 2 lines
init/Kconfig +2 -0
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

Quoted 8 lines

(Sorry hadn't seen you'd replied also!)

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

I guess this bit can be a follow up potentially?

yes, sure.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Sounds good, yes.

I can add a doc update as part of this series, unless you guys want to handle separately?

I don't think it has to be part of the series, it's long enough already. But if you want to prepare some docmentation about the preference of cc-option checks, feel free to go ahead or not.

Ack, thanks!

Quoted 3 lines

Kind regards
Nicolas

--
Cheers, Lorenzo

#50 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

In reply to Nicolas Schier

On Thu, 10 Sep 2026 17:42:35 +0200
Nicolas Schier <[email protected]> wrote:

...

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

One problem is that distributions have a nasty habit of shipping kernels that are compiled with a different compiler version to they actually ship as a compiler.
In some cases the versions are clearly the same - but the version strings differ.

David

#51 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 9 lines · David Laight

On Thu, 10 Sep 2026 17:42:35 +0200
Nicolas Schier <[email protected]> wrote:

...

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

Quoted 5 lines

One problem is that distributions have a nasty habit of shipping kernels that are compiled with a different compiler version to they actually ship as a compiler.
In some cases the versions are clearly the same - but the version strings differ.

yeah, I guess you hit the mark.

Signature · 1 line
Nicolas
#52 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 10 lines · Nicolas Schier
Quoted 9 lines · David Laight

On Thu, 10 Sep 2026 17:42:35 +0200
Nicolas Schier <[email protected]> wrote:

...

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

Quoted 7 lines
Quoted 5 lines

One problem is that distributions have a nasty habit of shipping kernels that are compiled with a different compiler version to they actually ship as a compiler.
In some cases the versions are clearly the same - but the version strings differ.

yeah, I guess you hit the mark.

I mean this is a problem that already exists for any flags already specified in Kconfig.

Out-of-tree modules are historically something that we don't go to great lengths to support and haven't historically worried about breaking, either.

I'm sure distros can find ways around this if a problem were to arise. But I don't think it's something to worry about all that much.

I expect a _lot_ of these, in any case, would only require the compilers to be within a fair few major versions of one another anyway.

Quoted 3 lines

--
Nicolas

--
Cheers, Lorenzo

#53 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 22 lines · Lorenzo Stoakes (ARM)
Quoted 10 lines · Nicolas Schier
Quoted 9 lines · David Laight

On Thu, 10 Sep 2026 17:42:35 +0200
Nicolas Schier <[email protected]> wrote:

...

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

Quoted 7 lines
Quoted 5 lines

One problem is that distributions have a nasty habit of shipping kernels that are compiled with a different compiler version to they actually ship as a compiler.
In some cases the versions are clearly the same - but the version strings differ.

yeah, I guess you hit the mark.

I mean this is a problem that already exists for any flags already specified in Kconfig.

Quoted 8 lines

Out-of-tree modules are historically something that we don't go to great lengths to support and haven't historically worried about breaking, either.

I'm sure distros can find ways around this if a problem were to arise. But I don't think it's something to worry about all that much.

I expect a _lot_ of these, in any case, would only require the compilers to be within a fair few major versions of one another anyway.

yes, I have similar thoughts about that. But I think it's good that it has been mentioned here in public.

Signature · 1 line
Nicolas
#54 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

In reply to Lorenzo Stoakes (ARM)
Quoted 22 lines · On Fri, 11 Sep 2026 19:24:50 +0100 "Lorenzo Stoakes (ARM)" <[email protected]>…
Quoted 10 lines · Nicolas Schier
Quoted 9 lines · David Laight

On Thu, 10 Sep 2026 17:42:35 +0200
Nicolas Schier <[email protected]> wrote:

...

Quoted 4 lines

Yes, skimming through the patch, I thought about that, too. Moving more cc option checks to Kconfig will make building out-of-tree kmods with a different compiler more dangerous. Maybe we will have to make the warning in Makefile's prepare (external kmods) target a bit louder.

Quoted 7 lines
Quoted 5 lines

One problem is that distributions have a nasty habit of shipping kernels that are compiled with a different compiler version to they actually ship as a compiler.
In some cases the versions are clearly the same - but the version strings differ.

yeah, I guess you hit the mark.

I mean this is a problem that already exists for any flags already specified in Kconfig.

Quoted 8 lines

Out-of-tree modules are historically something that we don't go to great lengths to support and haven't historically worried about breaking, either.

I'm sure distros can find ways around this if a problem were to arise. But I don't think it's something to worry about all that much.

I expect a _lot_ of these, in any case, would only require the compilers to be within a fair few major versions of one another anyway.

That is true at the moment when the version of the compiler being used is checked.
For instance it doesn't matter if modules are compiled without 'asm goto with output'.
But if you putting the options in Kconfig the compiler being used better not be older - or it might not support the options.
It isn't too bad if the compile fails, but some are silent.

IIRC it is Ubuntu that has different version strings for the same compiler version, and Oracle that ships kernels compiled with much newer compilers that they install by default.

David

Quoted 7 lines
Quoted 4 lines

--
Nicolas

--
Cheers, Lorenzo

#55 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

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

I mean this is a problem that already exists for any flags already specified in Kconfig.

Out-of-tree modules are historically something that we don't go to great lengths to support and haven't historically worried about breaking, either.

I'm sure distros can find ways around this if a problem were to arise. But I don't think it's something to worry about all that much.

I expect a _lot_ of these, in any case, would only require the compilers to be within a fair few major versions of one another anyway.

Yeah, while I know distributions will try to maintain a stable kernel ABI to allow updating modules without updating the main kernel, I would be very very surprised if they guaranteed compatability when building external modules with a compiler different from the main kernel. If so, I think they get to pick up the pieces :)

One issue that I found with my test matrix building with LLVM is that cc-option in Kconfig does not guarantee use of either '-m32' / '-m64' or '-mbig-endian' / '-mlittle-endian' to properly flip these options, which could result in a flag being set (or not set) when it should be. For example, building ARCH=powerpc pmac32_defconfig results in

clang: error: argument unused during compilation: '-fno-stack-clash-protection' [-Werror,-Wunused-command-line-argument] make[4]: *** [scripts/Makefile.build:193: kernel/bounds.s] Error 1

because the 64-bit PowerPC little endian target supports this flag in the PowerPC LLVM backend but the 32-bit big endian target does not.

I am not really sure what the best way to avoid this would be off the top of my head... it might be safer to start with moving only the warning flags to Kconfig since that is a truly frontend query.

Signature · 2 lines
Cheers,
Nathan
#56 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 25 lines · Nathan Chancellor
Quoted 11 lines · Lorenzo Stoakes (ARM)

I mean this is a problem that already exists for any flags already specified in Kconfig.

Out-of-tree modules are historically something that we don't go to great lengths to support and haven't historically worried about breaking, either.

I'm sure distros can find ways around this if a problem were to arise. But I don't think it's something to worry about all that much.

I expect a _lot_ of these, in any case, would only require the compilers to be within a fair few major versions of one another anyway.

Yeah, while I know distributions will try to maintain a stable kernel ABI to allow updating modules without updating the main kernel, I would be very very surprised if they guaranteed compatability when building external modules with a compiler different from the main kernel. If so, I think they get to pick up the pieces :)

One issue that I found with my test matrix building with LLVM is that cc-option in Kconfig does not guarantee use of either '-m32' / '-m64' or '-mbig-endian' / '-mlittle-endian' to properly flip these options, which could result in a flag being set (or not set) when it should be. For example, building ARCH=powerpc pmac32_defconfig results in

Quoted 5 lines

clang: error: argument unused during compilation: '-fno-stack-clash-protection' [-Werror,-Wunused-command-line-argument] make[4]: *** [scripts/Makefile.build:193: kernel/bounds.s] Error 1

because the 64-bit PowerPC little endian target supports this flag in the PowerPC LLVM backend but the 32-bit big endian target does not.

Ack, reproduced locally thanks!

I had the LLM probe every flag the patch moves in both directions with clang across ppc32/64 BE and LE, x86 -m32, mips 32/64, rv32, s390x, arm and arm64 BE and with gcc -m32.

(We really have to stop supporting some of this stuff...!)

It seems that only -fno-stack-clash-protection is problematic for ppc32/clang.

So in v2 I'll keep that probe in the Makefile and move the rest, have confirmed that fixes the problem.

Quoted 4 lines

I am not really sure what the best way to avoid this would be off the top of my head... it might be safer to start with moving only the warning flags to Kconfig since that is a truly frontend query.

Given the testing above I think we _should_ be OK :)

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#57 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

In reply to Nathan Chancellor
Quoted 8 lines · Nathan Chancellor
Quoted 8 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 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)
 
Quoted 14 lines

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 8 lines
init/Kconfig +8 -0
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

Yeah makes sense to separate them out so they're not all clumped with unrelated stuff.

It feels like init is the right place, having actual substantive Kconfig entries in scripts/ feels a bit weird.

I can add an extra patch to move existing entries over before adding these in in the next patch?

Quoted 4 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Yeah makes sense. I can add a patch to update the docs too?

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#58 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

Quoted 2 lines · Lorenzo Stoakes (ARM)

It feels like init is the right place, having actual substantive Kconfig entries in scripts/ feels a bit weird.

Yeah, that is valid.

Quoted 2 lines

I can add an extra patch to move existing entries over before adding these in in the next patch?

Yes, sounds perfect.

Quoted 5 lines
Quoted 3 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Yeah makes sense. I can add a patch to update the docs too?

Yeah, sounds good to me!

Signature · 2 lines
Cheers,
Nathan
#59 lore raw

Re: [PATCH 12/23] kbuild: avoid re-running compiler and linker probes

In reply to Nathan Chancellor
Quoted 23 lines · On Wed, 09 Sep 2026 21:19:12 -0700 Nathan Chancellor <[email protected]> wrote:
Quoted 6 lines
init/Kconfig +0 -0
index 8583d9f06c52..3c92c87254a3 100644
@@ -144,6 +144,44 @@ config CC_HAS_ASSUME
 config CC_HAS_NO_PROFILE_FN_ATTR

init/Kconfig config CC_HAS_ASSUME · line 154

Quoted 10 lines
init/Kconfig +8 -0
 	def_bool $(success,echo '__attribute__((no_profile_instrument_function)) int x();' | $(CC) -x c - -c -o /dev/null -Werror)
 
+config CC_HAS_ZERO_INIT_PADDING_BITS
+	def_bool $(cc-option,-fzero-init-padding-bits=all)
+
+config CC_HAS_NO_STACK_CLASH_PROTECTION
+	def_bool $(cc-option,-fno-stack-clash-protection)
+
+config CC_HAS_NO_ADDRSIG
+	def_bool $(cc-option,-fno-addrsig)  

I am generally in favor of this proposal since I think these checks should be cached by Kconfig where possible to clear up running them twice. That said, I wonder if we should pick a better dumping ground for these checks other than init/Kconfig. Maybe init/Kconfig.tools or scripts/Kconfig.tools or something?

Quoted 4 lines

I also worry about backsliding and growing cc-option checks. Should we update the documentation to state that it is preferrable for these checks to live in Kconfig so that they can be properly cached?

Thought...
Can some/all of the checks be done by running 'cc --help=xxx' once and parsing the result?

Although I'm not really sure that shaving off 0.2 seconds really matters. (I know the little bits add up, but there are much bigger delays.)

One thing that does annoy me is the delay before the first compile when you do a -j1 build. I've not looked at what is being run. This is all made worse because gmake doesn't stop on errors very well. I fixed that in NetBSD's make about 25 years ago.
(IIRC it mostly required always getting a new token from the pipe.)

David

#60 lore raw

PATCH 13/23 modpost: hash module source per-file, not per-byte

In reply to Lorenzo Stoakes (ARM)

modpost spends a long time md4 hashing module source at a per-byte granularity.

Fix this by doing this hashing per-file instead by accumulating a per-file buffer in parse_file().

All 11,189 .mod.c files and Module.symvers were confirmed to be identical with this change applied.

This is especially impactful for allmodconfig incremental builds (where CONFIG_MODULE_SRCVERSION_ALL is set).

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    40.6s    38.2s     -2.4s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  36.2s    35.0s     -1.2s (-3%)
Assisted-by LLM
---
 scripts/mod/sumversion.c | 56 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 44 insertions(+), 12 deletions(-)
scripts/mod/sumversion.c +44 -12
index 3dd28b4d0099..2cbadd3cd97d 100644
@@ -224,19 +224,11 @@ static void md4_final_ascii(struct md4_ctx *mctx, char *out, unsigned int len)
 		 mctx->hash[0], mctx->hash[1], mctx->hash[2], mctx->hash[3]);
 }
 
-static inline void add_char(unsigned char c, struct md4_ctx *md)
-{
-	md4_update(md, &c, 1);
-}
-
-static int parse_string(const char *file, unsigned long len,
-			struct md4_ctx *md)
+static int parse_string(const char *file, unsigned long len)
 {
 	unsigned long i;
 
-	add_char(file[0], md);
 	for (i = 1; i < len; i++) {
-		add_char(file[i], md);
 		if (file[i] == '"' && file[i-1] != '\\')
 			break;
 	}
@@ -255,15 +247,44 @@ static int parse_comment(const char *file, unsigned long len)
 }
 
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
+static bool stop_char[256];
+
+static void init_stop_chars(void)
+{
+	static bool done;
+	int chr;
+
+	if (done)
+		return;
+
+	for (chr = 0; chr < 256; chr++)
+		if (chr == '\\' || chr == '"' || chr == '/' || isspace(chr))
+			stop_char[chr] = true;
+
+	done = true;
+}
+
 static int parse_file(const char *fname, struct md4_ctx *md)
 {
+	unsigned long i, len, n = 0;
+	unsigned char *buf;
 	char *file;
-	unsigned long i, len;
 
 	file = read_text_file(fname);
 	len = strlen(file);
+	if (!len)
+		goto out_file;
+	init_stop_chars();
+	buf = xmalloc(len); /* File output buffer. */
 
 	for (i = 0; i < len; i++) {
+		const unsigned char chr = file[i];
+
+		if (!stop_char[chr]) {
+			buf[n++] = file[i];
+			continue;
+		}
+
 		/* Collapse and ignore \ and CR. */
 		if (file[i] == '\\' && (i+1 < len) && file[i+1] == '\n') {
 			i++;
@@ -276,7 +297,14 @@ static int parse_file(const char *fname, struct md4_ctx *md)
 
 		/* Handle strings as whole units */
 		if (file[i] == '"') {
-			i += parse_string(file+i, len - i, md);
+			unsigned long slen = parse_string(file+i, len - i);
+
+			/* Closing quote is included if there is one. */
+			if (slen < len - i)
+				slen++;
+			memcpy(buf + n, file + i, slen);
+			n += slen;
+			i += slen - 1;
 			continue;
 		}
 
@@ -286,11 +314,15 @@ static int parse_file(const char *fname, struct md4_ctx *md)
 			continue;
 		}
 
-		add_char(file[i], md);
+		buf[n++] = file[i];
 	}
+	md4_update(md, buf, n);
+	free(buf);
+out_file:
 	free(file);
 	return 1;
 }
+
 /* Check whether the file is a static library or not */
 static bool is_static_library(const char *objfile)
 {
Signature · 1 line
2.55.0
#61 lore raw

Re: [PATCH 13/23] modpost: hash module source per-file, not per-byte

Quoted 16 lines · Lorenzo Stoakes (ARM)

modpost spends a long time md4 hashing module source at a per-byte granularity.

Fix this by doing this hashing per-file instead by accumulating a per-file buffer in parse_file().

All 11,189 .mod.c files and Module.symvers were confirmed to be identical with this change applied.

This is especially impactful for allmodconfig incremental builds (where CONFIG_MODULE_SRCVERSION_ALL is set).

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

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

Quoted 8 lines
  x86 allmodconfig, touch mm/vma.c, gcc    40.6s    38.2s     -2.4s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  36.2s    35.0s     -1.2s (-3%)
Assisted-by LLM
---
 scripts/mod/sumversion.c | 56 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 44 insertions(+), 12 deletions(-)

Support for the module srcversion is being removed in "module: remove MODULE_VERSION() and srcversion" [1] and scripts/mod/sumversion.c should be gone completely.

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

Signature · 2 lines
Thanks,
Petr
#62 lore raw

Re: [PATCH 13/23] modpost: hash module source per-file, not per-byte

Quoted 26 lines · Petr Pavlu
Quoted 16 lines · Lorenzo Stoakes (ARM)

modpost spends a long time md4 hashing module source at a per-byte granularity.

Fix this by doing this hashing per-file instead by accumulating a per-file buffer in parse_file().

All 11,189 .mod.c files and Module.symvers were confirmed to be identical with this change applied.

This is especially impactful for allmodconfig incremental builds (where CONFIG_MODULE_SRCVERSION_ALL is set).

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

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

Quoted 8 lines
  x86 allmodconfig, touch mm/vma.c, gcc    40.6s    38.2s     -2.4s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  36.2s    35.0s     -1.2s (-3%)
Assisted-by LLM
---
 scripts/mod/sumversion.c | 56 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 44 insertions(+), 12 deletions(-)
Quoted 3 lines

Support for the module srcversion is being removed in "module: remove MODULE_VERSION() and srcversion" [1] and scripts/mod/sumversion.c should be gone completely.

Hmm, that series doesn't remove the script though, is that planned as a follow up?

I guess I can drop this patch from the series then :) Also patch 17 I think?

Quoted 6 lines

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

--
Thanks,
Petr

--
Cheers, Lorenzo

#63 lore raw

Re: [PATCH 13/23] modpost: hash module source per-file, not per-byte

Quoted 27 lines · Lorenzo Stoakes (ARM)
Quoted 26 lines · Petr Pavlu
Quoted 24 lines · Lorenzo Stoakes (ARM)

modpost spends a long time md4 hashing module source at a per-byte granularity.

Fix this by doing this hashing per-file instead by accumulating a per-file buffer in parse_file().

All 11,189 .mod.c files and Module.symvers were confirmed to be identical with this change applied.

This is especially impactful for allmodconfig incremental builds (where CONFIG_MODULE_SRCVERSION_ALL is set).

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    40.6s    38.2s     -2.4s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  36.2s    35.0s     -1.2s (-3%)
Assisted-by LLM
---
 scripts/mod/sumversion.c | 56 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 44 insertions(+), 12 deletions(-)
Quoted 5 lines
Quoted 3 lines

Support for the module srcversion is being removed in "module: remove MODULE_VERSION() and srcversion" [1] and scripts/mod/sumversion.c should be gone completely.

Hmm, that series doesn't remove the script though, is that planned as a follow up?

My reply to that series [1] notes that it should also remove scripts/mod/sumversion.c. It should be done in the next version.

Quoted 2 lines

I guess I can drop this patch from the series then :) Also patch 17 I think?

I agree. The module srcversion is no longer needed since build IDs are nowadays the standard mechanism for providing effectively the same functionality. While I'm not sure when the mentioned removal will land, reviewing and polishing this patch and patch 17 would IMO be wasteful at this point.

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

Signature · 2 lines
Thanks,
Petr
#64 lore raw

Re: [PATCH 13/23] modpost: hash module source per-file, not per-byte

Quoted 28 lines · Petr Pavlu
Quoted 27 lines · Lorenzo Stoakes (ARM)
Quoted 26 lines · Petr Pavlu
Quoted 24 lines · Lorenzo Stoakes (ARM)

modpost spends a long time md4 hashing module source at a per-byte granularity.

Fix this by doing this hashing per-file instead by accumulating a per-file buffer in parse_file().

All 11,189 .mod.c files and Module.symvers were confirmed to be identical with this change applied.

This is especially impactful for allmodconfig incremental builds (where CONFIG_MODULE_SRCVERSION_ALL is set).

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    40.6s    38.2s     -2.4s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  36.2s    35.0s     -1.2s (-3%)
Assisted-by LLM
---
 scripts/mod/sumversion.c | 56 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 44 insertions(+), 12 deletions(-)
Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

Support for the module srcversion is being removed in "module: remove MODULE_VERSION() and srcversion" [1] and scripts/mod/sumversion.c should be gone completely.

Hmm, that series doesn't remove the script though, is that planned as a follow up?

My reply to that series [1] notes that it should also remove scripts/mod/sumversion.c. It should be done in the next version.

Ack!

Quoted 9 lines
Quoted 3 lines

I guess I can drop this patch from the series then :) Also patch 17 I think?

I agree. The module srcversion is no longer needed since build IDs are nowadays the standard mechanism for providing effectively the same functionality. While I'm not sure when the mentioned removal will land, reviewing and polishing this patch and patch 17 would IMO be wasteful at this point.

Ack, will drop them for v2 then and add a note to the cover clearly stating the dependency!

Quoted 6 lines

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

--
Thanks,
Petr

--
Cheers, Lorenzo

#65 lore raw

PATCH 14/23 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.6s     8.4s    -0.16s (-2%)
  x86 defconfig, touch mm/vma.c, clang      7.7s     7.5s    -0.15s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    38.2s    33.5s     -4.6s (-12%)
  x86 allmodconfig, touch mm/vma.c, clang  35.0s    31.1s     -4.0s (-11%)
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
#66 lore raw

PATCH 15/23 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.

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.

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        11.0s     1.9s     -9.1s (-82%)
  x86 allmodconfig, no-op make, clang      11.6s     2.4s     -9.2s (-79%)
  x86 allmodconfig, clean, gcc            342.1s   304.5s    -37.6s (-11%)
  x86 allmodconfig, clean, clang          338.5s   301.7s    -36.8s (-11%)
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        | 619 +++++++++++++++++++++++++++++++------------
 scripts/mod/module-offsets.c |  35 +++
 scripts/tags.sh              |   5 +-
 10 files changed, 512 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 088e901f0a72..997fc7ebe096 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 +453 -166

664 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
#67 lore raw

Re: [PATCH 15/23] modpost: emit module descriptors as assembly

Quoted 10 lines · 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.

This kind of triggers the same reaction as the kallsyms code: I think not including <linux/module.h> is probably the biggest win in this all, and precomputing the offsets of the (few) structures that modpost uses then makes the whole end result fairly trivial in raw asm.

Fine.

BUT.

You end up with things like this instead:

scripts/mod/module-offsets.c

Quoted 1 line
scripts/mod/module-offsets.c +0 -0

where it generates a header file for those asm scripts so that the asm generation can do things like

        buf_printf(buf, "\t.size __this_module, %d\n",

MOD_SIZEOF_struct_module);

etc.

But I - again - get the feeling that this is all going through AS as a silly way to generate an object file, and that there really isn't any obvious advantage to that side quest.

Becuase no human ever wants to see that asm file, and it's no more legible than generating the object file directly would have been.

So I get the feeling that it would again be more natural to just generate the object file directly when all those files really end up being are a few symbol definitions and a couple of fixed structures (is there anything but the magic "__this_module" thing and the modinfo unique ID thing?)

And again - I feel like nobody sane would want to write that code. I certainly don't. But if this was at least partly automated anyway, going that extra step might not be all that horrific.

I'll also be honest: part of why I do these suggestions is that I do think it would be faster to skip the intermediate assembler step, but a big part of it is that I don't love the random turds our build creates. Getting rid of the *.mod.c files would be a cleanup of our strange build.

Linus

#68 lore raw

Re: [PATCH 15/23] modpost: emit module descriptors as assembly

Quoted 12 lines · Linus Torvalds
Quoted 10 lines · 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.

Quoted 4 lines

This kind of triggers the same reaction as the kallsyms code: I think not including <linux/module.h> is probably the biggest win in this all, and precomputing the offsets of the (few) structures that modpost uses then makes the whole end result fairly trivial in raw asm.

Right indeed :)

Quoted 12 lines

Fine.

BUT.

You end up with things like this instead:

scripts/mod/module-offsets.c

Quoted 1 line
scripts/mod/module-offsets.c +0 -0

where it generates a header file for those asm scripts so that the asm generation can do things like

Quoted 8 lines
        buf_printf(buf, "\t.size __this_module, %d\n",

MOD_SIZEOF_struct_module);

etc.

But I - again - get the feeling that this is all going through AS as a silly way to generate an object file, and that there really isn't any obvious advantage to that side quest.

Well it seems the biggest advantage in doing assembly over directly manipulating an object file is that you avoid any arch-specific nonsense, as with kallsyms.

Quoted 14 lines

Becuase no human ever wants to see that asm file, and it's no more legible than generating the object file directly would have been.

So I get the feeling that it would again be more natural to just generate the object file directly when all those files really end up being are a few symbol definitions and a couple of fixed structures (is there anything but the magic "__this_module" thing and the modinfo unique ID thing?)

And again - I feel like nobody sane would want to write that code. I certainly don't. But if this was at least partly automated anyway, going that extra step might not be all that horrific.

Quoted 5 lines

I'll also be honest: part of why I do these suggestions is that I do think it would be faster to skip the intermediate assembler step, but a big part of it is that I don't love the random turds our build creates. Getting rid of the *.mod.c files would be a cleanup of our strange build.

Well the *.mod.c turds are flushed already, but replaced with smaller *.mod.S ones instead :)

The LLM says the time taken per assembler step is ~7.5ms per .mod.S which is .65s of wall time on the threadripper so it terms of a build it's into the noise territory at least for a bigger box (plus obviously you won't go to _zero_ cost by writing the object file directly).

Overall I think it's not _currently_ worth it as part of this work, but it's something I can set the LLM on as a follow-up maybe? Could do a 'eliminate build artifacts' pass in general.

Quoted 2 lines

Linus

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#70 lore raw

Re: [PATCH 15/23] modpost: emit module descriptors as assembly

Quoted 54 lines · On Tue, Sep 08, 2026 at 09:18:28PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] The hardcoded emission order of __this_module fields in assembly breaks when CONFIG_RANDSTRUCT is enabled, silently corrupting the struct module layout. --

commit 36c35576d2135acc7ba00c67d37c3dbf0e909c0c
Author: Lorenzo Stoakes (ARM) <[email protected]>

modpost: emit module descriptors as assembly

This commit modifies modpost to emit module descriptors as assembly instead of C to improve build times.

Quoted 4 lines
scripts/mod/modpost.c +0 -0
index 0fd43c8a89ea0..550ccd753ed88 100644

[ ... ]

Quoted 16 lines
scripts/mod/modpost.c +16 -0
+static void add_asm_this_module(struct buffer *buf, const struct module *mod,
+				const char *modname)
+{
+	struct this_module_field fields[THIS_MODULE_MAX_FIELDS];
+	const unsigned int nr_fields = get_this_module_fields(mod, fields);
+	unsigned int pos = 0, i;
+
+	buf_printf(buf, "\n\t.section .gnu.linkonce.this_module,\"aw\",%%progbits\n");
+	buf_printf(buf, "\t.balign %d\n", MOD_ALIGNOF_struct_module);
+	buf_printf(buf, "\t.globl __this_module\n");
+	buf_printf(buf, "\t.type __this_module, %%object\n");
+	buf_printf(buf, "\t.size __this_module, %d\n", MOD_SIZEOF_struct_module);
+	buf_printf(buf, "__this_module:\n");
+
+	asm_skip_to(buf, &pos, MOD_OFF_module_name);
+	buf_printf(buf, "\t.ascii \"%s\"\n", modname);

scripts/mod/modpost.c static void write_vmlinux_export_c_file(struct module *mod) · line 2278

Quoted 10 lines
scripts/mod/modpost.c +10 -0
+	pos += strlen(modname);
+
+	for (i = 0; i < nr_fields; i++) {
+		asm_skip_to(buf, &pos, fields[i].offset);
+		buf_printf(buf, "\t" MOD_PTR_DIRECTIVE " %s\n", fields[i].value);
+		pos += MOD_SIZEOF_LONG;
+	}
+
+	asm_skip_to(buf, &pos, MOD_SIZEOF_struct_module);
+}

[Severity: Critical]
Will this hardcoded emission order of __this_module fields break when CONFIG_RANDSTRUCT is enabled?

The logic in add_asm_this_module() assumes that the name field is located at a lower offset than any of the function pointers in the fields array. Under CONFIG_RANDSTRUCT, struct module is marked with __randomize_layout, which means the name field might be placed at a higher offset than the init or exit fields.

Quoted 4 lines

Since the assembler cannot skip backwards, could this sequential assumption fail the offset-based .skip logic, placing the function pointers at incorrect offsets immediately following the name string, rather than at their proper offsets within the struct?

Yeah this was valid, updated to fix this by ordering by offset explicitly for v2.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15

--
Cheers, Lorenzo

#71 lore raw

PATCH 16/23 kbuild: batch module finalisation

In reply to Lorenzo Stoakes (ARM)

Module finalisation on allmodconfig builds consists of a large number of very short-lived jobs, and the make job dispatcher cannot possibly dispatch jobs fast enough.

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

However per-job cost grows with the variables the instance holds, here the savedcmd_* of every .mod.o and .ko read back from the .cmd files, since it walks them all to build each child's environment.

This makes module finalisation very inefficient when large numbers of modules are being built.

Fix this by splitting modules.order into chunks of 128 at a time, run in parallel.

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>.

"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         1.9s     1.2s    -0.74s (-39%)
  x86 allmodconfig, no-op make, clang       2.4s     1.6s    -0.77s (-32%)
  x86 allmodconfig, clean, gcc            304.5s   291.4s     -13.1s (-4%)
  x86 allmodconfig, clean, clang          301.7s   297.0s     -4.7s (-2%)
Assisted-by LLM
---
 scripts/Makefile.modfinal | 26 +++++++++++++++++++++++++-
 scripts/mod/sumversion.c  |  4 ++--
 2 files changed, 27 insertions(+), 3 deletions(-)
scripts/Makefile.modfinal +25 -1
index 75e9effdf02c..858fa798090b 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
@@ -58,7 +79,10 @@ ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 endif
 	+$(call cmd,check_tracepoint)
 
-targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
+targets += .module-common.o
+ifdef modfinal-first
+targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o)
+endif
 
 # Add FORCE to the prerequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
scripts/mod/sumversion.c +2 -2
index 2cbadd3cd97d..5501d6aa0bea 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void init_stop_chars(void)
+static void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -274,7 +274,7 @@ static int parse_file(const char *fname, struct md4_ctx *md)
 	len = strlen(file);
 	if (!len)
 		goto out_file;
-	init_stop_chars();
+	sumversion_init();
 	buf = xmalloc(len); /* File output buffer. */
 
 	for (i = 0; i < len; i++) {
Signature · 1 line
2.55.0
#72 lore raw

Re: [PATCH 16/23] kbuild: batch module finalisation

Quoted 45 lines · Lorenzo Stoakes (ARM)

Module finalisation on allmodconfig builds consists of a large number of very short-lived jobs, and the make job dispatcher cannot possibly dispatch jobs fast enough.

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

However per-job cost grows with the variables the instance holds, here the savedcmd_* of every .mod.o and .ko read back from the .cmd files, since it walks them all to build each child's environment.

This makes module finalisation very inefficient when large numbers of modules are being built.

Fix this by splitting modules.order into chunks of 128 at a time, run in parallel.

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>.

"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         1.9s     1.2s    -0.74s (-39%)
  x86 allmodconfig, no-op make, clang       2.4s     1.6s    -0.77s (-32%)
  x86 allmodconfig, clean, gcc            304.5s   291.4s     -13.1s (-4%)
  x86 allmodconfig, clean, clang          301.7s   297.0s     -4.7s (-2%)
Assisted-by LLM
---
 scripts/Makefile.modfinal | 26 +++++++++++++++++++++++++-
 scripts/mod/sumversion.c  |  4 ++--
 2 files changed, 27 insertions(+), 3 deletions(-)
scripts/Makefile.modfinal +0 -0
index 75e9effdf02c..858fa798090b 100644

[...]

Quoted 26 lines
scripts/mod/sumversion.c +2 -2
index 2cbadd3cd97d..5501d6aa0bea 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void init_stop_chars(void)
+static void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -274,7 +274,7 @@ static int parse_file(const char *fname, struct md4_ctx *md)
 	len = strlen(file);
 	if (!len)
 		goto out_file;
-	init_stop_chars();
+	sumversion_init();
 	buf = xmalloc(len); /* File output buffer. */
 
 	for (i = 0; i < len; i++) {
Signature · 2 lines
-- 
2.55.0

(I have only skimmed through, not yet reviewed this patch.)

The change in sumversion.c seems to be wrong here.

Signature · 1 line
Nicolas
#73 lore raw

Re: [PATCH 16/23] kbuild: batch module finalisation

Quoted 71 lines · Nicolas Schier
Quoted 45 lines · Lorenzo Stoakes (ARM)

Module finalisation on allmodconfig builds consists of a large number of very short-lived jobs, and the make job dispatcher cannot possibly dispatch jobs fast enough.

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

However per-job cost grows with the variables the instance holds, here the savedcmd_* of every .mod.o and .ko read back from the .cmd files, since it walks them all to build each child's environment.

This makes module finalisation very inefficient when large numbers of modules are being built.

Fix this by splitting modules.order into chunks of 128 at a time, run in parallel.

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>.

"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         1.9s     1.2s    -0.74s (-39%)
  x86 allmodconfig, no-op make, clang       2.4s     1.6s    -0.77s (-32%)
  x86 allmodconfig, clean, gcc            304.5s   291.4s     -13.1s (-4%)
  x86 allmodconfig, clean, clang          301.7s   297.0s     -4.7s (-2%)
Assisted-by LLM
---
 scripts/Makefile.modfinal | 26 +++++++++++++++++++++++++-
 scripts/mod/sumversion.c  |  4 ++--
 2 files changed, 27 insertions(+), 3 deletions(-)
scripts/Makefile.modfinal +0 -0
index 75e9effdf02c..858fa798090b 100644

[...]

Quoted 23 lines
scripts/mod/sumversion.c +2 -2
index 2cbadd3cd97d..5501d6aa0bea 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void init_stop_chars(void)
+static void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -274,7 +274,7 @@ static int parse_file(const char *fname, struct md4_ctx *md)
 	len = strlen(file);
 	if (!len)
 		goto out_file;
-	init_stop_chars();
+	sumversion_init();
 	buf = xmalloc(len); /* File output buffer. */
 
 	for (i = 0; i < len; i++) {
Quoted 7 lines
Quoted 3 lines

--
2.55.0

(I have only skimmed through, not yet reviewed this patch.)

The change in sumversion.c seems to be wrong here.

Ugh yeah this is a merge conflict artifact that I thought I had fixed but clearly not :) Will fix up on respin.

Quoted 3 lines

--
Nicolas

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#75 lore raw

Re: [PATCH 16/23] kbuild: batch module finalisation

Quoted 35 lines · On Tue, Sep 08, 2026 at 09:18:22PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Unlisted and non-POSIX dependency on the seq command causes a fatal Make syntax error if missing.
- [High] Fatal Make syntax error when no modules are selected for the build.
--

commit 6c6d5fda60bd6b0c0a86fda35f3eac7d4488623e
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: batch module finalisation

This commit splits modules.order into chunks of 128 at a time for module finalisation to speed up allmodconfig builds. It parallelises the finalisation workload by having a parent make process dispatch chunk instances.

Quoted 10 lines
scripts/Makefile.modfinal +2 -0
index 75e9effdf02ce..858fa798090be 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
+

[ ... ]

scripts/Makefile.modfinal include $(srctree)/scripts/Makefile.lib · line 29

Quoted 3 lines
scripts/Makefile.modfinal +3 -0
+else
+
+modfinal-chunks := $(addprefix chunk-, $(shell seq 1 $(modfinal-chunk-size) $(words $(modules))))

[Severity: High]
The seq command is not mandated by POSIX and is not listed as a required tool in Documentation/process/changes.rst. On minimal environments or certain BSDs where seq might be missing, the shell command fails silently and returns an empty string.

Quoted 2 lines

Will this result in modfinal-chunks being empty, leading to a fatal Make syntax error on the rule below?

This is very silly, it's shipped everywhere that can possibly build a kernel. Build would fail loudly if missing.

Quoted 11 lines

scripts/Makefile.modfinal include $(srctree)/scripts/Makefile.lib · line 33

Quoted 5 lines
scripts/Makefile.modfinal +4 -0
+
+PHONY += $(modfinal-chunks)
+$(modfinal-chunks): .module-common.o
+	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modfinal modfinal-first=$(@:chunk-%=%)

[Severity: High]
If the kernel configuration enables modules (CONFIG_MODULES=y) but no actual modules are selected, modules.order is generated but empty. Consequently, $(words $(modules)) evaluates to 0, and $(shell seq 1 128 0) outputs nothing.

Quoted 3 lines

Does this leave modfinal-chunks completely empty, evaluating to an invalid target-less rule (: .module-common.o) and causing a fatal Make syntax error (*** missing target pattern. Stop.)?

Bogus. Tested and works fine, GNU make accepts ar ule with an empty target list.

SO 100% hallucination here.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16

--
Cheers, Lorenzo

#76 lore raw

PATCH 17/23 modpost: perform srcversion hashing in parallel

In reply to Lorenzo Stoakes (ARM)

modpost does a lot of single-threaded work hashing files from each object's .cmd file.

This makes the build slower than it needs to be, so do this work in parallel.

This is egregious for allmodconfig builds - for instance x86-64 can end up opening 200,000 files individually and hashing them all serially.

Parallelise this operation by maintaining a thread pool for the hashing work.

Combined with the per-file hashing commit this cuts modpost's run time nearly in half for an allmodconfig build.

Module.symvers and every *.mod.S are byte for byte the same.

modpost is on the serial tail of every allmodconfig build, however defconfig does not set CONFIG_MODULE_SRCVERSION_ALL and is unchanged.

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    33.4s    30.2s     -3.2s (-10%)
  x86 allmodconfig, touch mm/vma.c, clang  31.1s    28.1s     -3.0s (-10%)
Assisted-by LLM
---
 scripts/mod/Makefile     |  1 +
 scripts/mod/modpost.c    | 72 ++++++++++++++++++++++++++++++++++++++++++++++--
 scripts/mod/modpost.h    |  2 ++
 scripts/mod/sumversion.c |  3 +-
 4 files changed, 74 insertions(+), 4 deletions(-)
scripts/mod/Makefile +1 -0
index fbd5099e0441..fdd486184f9c 100644
@@ -5,6 +5,7 @@ hostprogs-always-y	+= modpost mk_elfconfig
 always-y		+= empty.o
 
 modpost-objs	:= modpost.o file2alias.o sumversion.o symsearch.o
+HOSTLDLIBS_modpost := -lpthread
 
 devicetable-offsets-file := devicetable-offsets.h
 
scripts/mod/modpost.c +70 -2

96 lines not on this page · raw message

scripts/mod/modpost.h +2 -0
index d5f6d82837d5..10d5f8f2f293 100644
@@ -127,6 +127,7 @@ struct module {
 	bool has_init;
 	bool has_cleanup;
 	char	     srcversion[25];
+	bool need_srcversion;
 	// Missing namespace dependencies
 	struct list_head missing_namespaces;
 	// Actual imported namespaces
@@ -213,6 +214,7 @@ void handle_moddevtable(struct module *mod, struct elf_info *info,
 			Elf_Sym *sym, const char *symname);
 
 /* sumversion.c */
+void sumversion_init(void);
 void get_src_version(const char *modname, char sum[], unsigned sumlen);
 
 /* from modpost.c */
scripts/mod/sumversion.c +1 -2
index 5501d6aa0bea..4521b92ef868 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void sumversion_init(void)
+void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -402,7 +402,6 @@ static int parse_source_files(const char *objfile, struct md4_ctx *md)
 				     line, strerror(errno));
 				goto out_file;
 			}
-
 		}
 
 	}
Signature · 1 line
2.55.0
#77 lore raw

Re: [PATCH 17/23] modpost: perform srcversion hashing in parallel

Quoted 73 lines · On Tue, 08 Sep 2026 21:55:17 +0100 "Lorenzo Stoakes (ARM)" <[email protected]>…

modpost does a lot of single-threaded work hashing files from each object's .cmd file.

This makes the build slower than it needs to be, so do this work in parallel.

This is egregious for allmodconfig builds - for instance x86-64 can end up opening 200,000 files individually and hashing them all serially.

Parallelise this operation by maintaining a thread pool for the hashing work.

Combined with the per-file hashing commit this cuts modpost's run time nearly in half for an allmodconfig build.

Module.symvers and every *.mod.S are byte for byte the same.

modpost is on the serial tail of every allmodconfig build, however defconfig does not set CONFIG_MODULE_SRCVERSION_ALL and is unchanged.

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    33.4s    30.2s     -3.2s (-10%)
  x86 allmodconfig, touch mm/vma.c, clang  31.1s    28.1s     -3.0s (-10%)
Assisted-by LLM
---
 scripts/mod/Makefile     |  1 +
 scripts/mod/modpost.c    | 72 ++++++++++++++++++++++++++++++++++++++++++++++--
 scripts/mod/modpost.h    |  2 ++
 scripts/mod/sumversion.c |  3 +-
 4 files changed, 74 insertions(+), 4 deletions(-)
scripts/mod/Makefile +1 -0
index fbd5099e0441..fdd486184f9c 100644
@@ -5,6 +5,7 @@ hostprogs-always-y	+= modpost mk_elfconfig
 always-y		+= empty.o
 
 modpost-objs	:= modpost.o file2alias.o sumversion.o symsearch.o
+HOSTLDLIBS_modpost := -lpthread
 
 devicetable-offsets-file := devicetable-offsets.h
 
scripts/mod/modpost.c +2 -2
index 550ccd753ed8..882169e51851 100644
@@ -16,6 +16,7 @@
 #include <fnmatch.h>
 #include <stdio.h>
 #include <ctype.h>
+#include <pthread.h>
 #include <string.h>
 #include <limits.h>
 #include <stdbool.h>
@@ -1717,8 +1718,7 @@ static void read_symbols(const char *modname)
 	if (!mod->is_vmlinux) {
 		version = get_modinfo(&info, "version");
 		if (version || all_versions)
-			get_src_version(mod->name, mod->srcversion,
-					sizeof(mod->srcversion) - 1);
+			mod->need_srcversion = true;
 	}
 
 	parse_elf_finish(&info);
@@ -1736,6 +1736,72 @@ static void read_symbols(const char *modname)
 	}
 }

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1747

Quoted 10 lines
scripts/mod/modpost.c +9 -0
 
+static struct module **srcversion_mods;
+static unsigned int nr_srcversion_mods, next_srcversion_mod;
+
+static bool get_next_src_version(void)
+{
+	struct module *mod;
+	unsigned int idx;
+
+	idx = __sync_fetch_and_add(&next_srcversion_mod, 1);

When I've done this is the past, adding 'a few' items was faster because it reduced the contention on the counter. (Although there were probably some very cheap 'actions'.)

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1760

Quoted 13 lines
scripts/mod/modpost.c +13 -0
+	if (idx >= nr_srcversion_mods)
+		return false;
+	mod = srcversion_mods[idx];
+
+	get_src_version(mod->name, mod->srcversion,
+			sizeof(mod->srcversion) - 1);
+	return true;
+}
+
+static void *srcversion_worker(void *arg)
+{
+	while (get_next_src_version())
+		;

I don't think the extra function call helps.

Quoted 15 lines
scripts/mod/modpost.c +15 -0
+
+	return NULL;
+}
+
+static void hash_srcversions(void)
+{
+	unsigned int i = 0;
+	struct module *mod;
+	pthread_t *threads;
+	long nr_threads;
+
+	list_for_each_entry(mod, &modules, list)
+		if (mod->need_srcversion)
+			nr_srcversion_mods++;
+

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1785

Quoted 10 lines
scripts/mod/modpost.c +10 -0
+	if (!nr_srcversion_mods)
+		return;
+
+	srcversion_mods = xmalloc(nr_srcversion_mods * sizeof(*srcversion_mods));
+
+	list_for_each_entry(mod, &modules, list)
+		if (mod->need_srcversion)
+			srcversion_mods[i++] = mod;
+
+	nr_threads = sysconf(_SC_NPROCESSORS_ONLN);

One thread per cpu is probably a few to many.
It might be worth adding a command line parameter for the 'max threads'. Possibly with -n meaning 'all but n'.

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1797

Quoted 12 lines
scripts/mod/modpost.c +12 -0
+	nr_threads = nr_threads < 1 ? 1 : nr_threads; /* On error assume 1. */
+	if (nr_threads > nr_srcversion_mods)
+		nr_threads = nr_srcversion_mods;
+
+	sumversion_init();
+	threads = xmalloc(nr_threads * sizeof(*threads));
+	for (i = 0; i < nr_threads; i++) {
+		if (pthread_create(&threads[i], NULL, srcversion_worker, NULL)) {
+			perror("pthread_create");
+			exit(1);
+		}
+	}

The main code can call srcversion_worker() here.

David

Quoted 61 lines
scripts/mod/modpost.c +9 -0
+	for (i = 0; i < nr_threads; i++)
+		pthread_join(threads[i], NULL);
+
+	free(threads);
+	free(srcversion_mods);
+}
+
 static void read_symbols_from_files(const char *filename)
 {
 	FILE *in = stdin;
@@ -2729,6 +2795,8 @@ int main(int argc, char **argv)
 	if (files_source)
 		read_symbols_from_files(files_source);
 
+	hash_srcversions();
+
 	list_for_each_entry(mod, &modules, list) {
 		keep_no_trim_symbols(mod);
 
scripts/mod/modpost.h +2 -0
index d5f6d82837d5..10d5f8f2f293 100644
@@ -127,6 +127,7 @@ struct module {
 	bool has_init;
 	bool has_cleanup;
 	char	     srcversion[25];
+	bool need_srcversion;
 	// Missing namespace dependencies
 	struct list_head missing_namespaces;
 	// Actual imported namespaces
@@ -213,6 +214,7 @@ void handle_moddevtable(struct module *mod, struct elf_info *info,
 			Elf_Sym *sym, const char *symname);
 
 /* sumversion.c */
+void sumversion_init(void);
 void get_src_version(const char *modname, char sum[], unsigned sumlen);
 
 /* from modpost.c */
scripts/mod/sumversion.c +1 -2
index 5501d6aa0bea..4521b92ef868 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void sumversion_init(void)
+void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -402,7 +402,6 @@ static int parse_source_files(const char *objfile, struct md4_ctx *md)
 				     line, strerror(errno));
 				goto out_file;
 			}
-
 		}
 
 	}
#78 lore raw

Re: [PATCH 17/23] modpost: perform srcversion hashing in parallel

I'm likely going to be dropping this patch from the series:

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

I don't really agree with the points below but not really worth getting into if the patch is going away :)

Quoted 213 lines · David Laight
Quoted 73 lines · On Tue, 08 Sep 2026 21:55:17 +0100 "Lorenzo Stoakes (ARM)" <[email protected]>…

modpost does a lot of single-threaded work hashing files from each object's .cmd file.

This makes the build slower than it needs to be, so do this work in parallel.

This is egregious for allmodconfig builds - for instance x86-64 can end up opening 200,000 files individually and hashing them all serially.

Parallelise this operation by maintaining a thread pool for the hashing work.

Combined with the per-file hashing commit this cuts modpost's run time nearly in half for an allmodconfig build.

Module.symvers and every *.mod.S are byte for byte the same.

modpost is on the serial tail of every allmodconfig build, however defconfig does not set CONFIG_MODULE_SRCVERSION_ALL and is unchanged.

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

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

  x86 allmodconfig, touch mm/vma.c, gcc    33.4s    30.2s     -3.2s (-10%)
  x86 allmodconfig, touch mm/vma.c, clang  31.1s    28.1s     -3.0s (-10%)
Assisted-by LLM
---
 scripts/mod/Makefile     |  1 +
 scripts/mod/modpost.c    | 72 ++++++++++++++++++++++++++++++++++++++++++++++--
 scripts/mod/modpost.h    |  2 ++
 scripts/mod/sumversion.c |  3 +-
 4 files changed, 74 insertions(+), 4 deletions(-)
scripts/mod/Makefile +1 -0
index fbd5099e0441..fdd486184f9c 100644
@@ -5,6 +5,7 @@ hostprogs-always-y	+= modpost mk_elfconfig
 always-y		+= empty.o
 
 modpost-objs	:= modpost.o file2alias.o sumversion.o symsearch.o
+HOSTLDLIBS_modpost := -lpthread
 
 devicetable-offsets-file := devicetable-offsets.h
 
scripts/mod/modpost.c +2 -2
index 550ccd753ed8..882169e51851 100644
@@ -16,6 +16,7 @@
 #include <fnmatch.h>
 #include <stdio.h>
 #include <ctype.h>
+#include <pthread.h>
 #include <string.h>
 #include <limits.h>
 #include <stdbool.h>
@@ -1717,8 +1718,7 @@ static void read_symbols(const char *modname)
 	if (!mod->is_vmlinux) {
 		version = get_modinfo(&info, "version");
 		if (version || all_versions)
-			get_src_version(mod->name, mod->srcversion,
-					sizeof(mod->srcversion) - 1);
+			mod->need_srcversion = true;
 	}
 
 	parse_elf_finish(&info);
@@ -1736,6 +1736,72 @@ static void read_symbols(const char *modname)
 	}
 }

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1747

Quoted 10 lines
scripts/mod/modpost.c +9 -0
 
+static struct module **srcversion_mods;
+static unsigned int nr_srcversion_mods, next_srcversion_mod;
+
+static bool get_next_src_version(void)
+{
+	struct module *mod;
+	unsigned int idx;
+
+	idx = __sync_fetch_and_add(&next_srcversion_mod, 1);

When I've done this is the past, adding 'a few' items was faster because it reduced the contention on the counter. (Although there were probably some very cheap 'actions'.)

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1760

Quoted 13 lines
scripts/mod/modpost.c +13 -0
+	if (idx >= nr_srcversion_mods)
+		return false;
+	mod = srcversion_mods[idx];
+
+	get_src_version(mod->name, mod->srcversion,
+			sizeof(mod->srcversion) - 1);
+	return true;
+}
+
+static void *srcversion_worker(void *arg)
+{
+	while (get_next_src_version())
+		;

I don't think the extra function call helps.

Quoted 15 lines
scripts/mod/modpost.c +15 -0
+
+	return NULL;
+}
+
+static void hash_srcversions(void)
+{
+	unsigned int i = 0;
+	struct module *mod;
+	pthread_t *threads;
+	long nr_threads;
+
+	list_for_each_entry(mod, &modules, list)
+		if (mod->need_srcversion)
+			nr_srcversion_mods++;
+

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1785

Quoted 10 lines
scripts/mod/modpost.c +10 -0
+	if (!nr_srcversion_mods)
+		return;
+
+	srcversion_mods = xmalloc(nr_srcversion_mods * sizeof(*srcversion_mods));
+
+	list_for_each_entry(mod, &modules, list)
+		if (mod->need_srcversion)
+			srcversion_mods[i++] = mod;
+
+	nr_threads = sysconf(_SC_NPROCESSORS_ONLN);

One thread per cpu is probably a few to many.
It might be worth adding a command line parameter for the 'max threads'. Possibly with -n meaning 'all but n'.

scripts/mod/modpost.c static void read_symbols(const char *modname) · line 1797

Quoted 12 lines
scripts/mod/modpost.c +12 -0
+	nr_threads = nr_threads < 1 ? 1 : nr_threads; /* On error assume 1. */
+	if (nr_threads > nr_srcversion_mods)
+		nr_threads = nr_srcversion_mods;
+
+	sumversion_init();
+	threads = xmalloc(nr_threads * sizeof(*threads));
+	for (i = 0; i < nr_threads; i++) {
+		if (pthread_create(&threads[i], NULL, srcversion_worker, NULL)) {
+			perror("pthread_create");
+			exit(1);
+		}
+	}

The main code can call srcversion_worker() here.

David

Quoted 59 lines
scripts/mod/modpost.c +9 -0
+	for (i = 0; i < nr_threads; i++)
+		pthread_join(threads[i], NULL);
+
+	free(threads);
+	free(srcversion_mods);
+}
+
 static void read_symbols_from_files(const char *filename)
 {
 	FILE *in = stdin;
@@ -2729,6 +2795,8 @@ int main(int argc, char **argv)
 	if (files_source)
 		read_symbols_from_files(files_source);
 
+	hash_srcversions();
+
 	list_for_each_entry(mod, &modules, list) {
 		keep_no_trim_symbols(mod);
 
scripts/mod/modpost.h +2 -0
index d5f6d82837d5..10d5f8f2f293 100644
@@ -127,6 +127,7 @@ struct module {
 	bool has_init;
 	bool has_cleanup;
 	char	     srcversion[25];
+	bool need_srcversion;
 	// Missing namespace dependencies
 	struct list_head missing_namespaces;
 	// Actual imported namespaces
@@ -213,6 +214,7 @@ void handle_moddevtable(struct module *mod, struct elf_info *info,
 			Elf_Sym *sym, const char *symname);
 
 /* sumversion.c */
+void sumversion_init(void);
 void get_src_version(const char *modname, char sum[], unsigned sumlen);
 
 /* from modpost.c */
scripts/mod/sumversion.c +1 -2
index 5501d6aa0bea..4521b92ef868 100644
@@ -249,7 +249,7 @@ static int parse_comment(const char *file, unsigned long len)
 /* FIXME: Handle .s files differently (eg. # starts comments) --RR */
 static bool stop_char[256];
 
-static void sumversion_init(void)
+void sumversion_init(void)
 {
 	static bool done;
 	int chr;
@@ -402,7 +402,6 @@ static int parse_source_files(const char *objfile, struct md4_ctx *md)
 				     line, strerror(errno));
 				goto out_file;
 			}
-
 		}
 
Quoted 3 lines

scripts/mod/sumversion.c static int parse_source_files(const char *objfile, struct md4_ctx *md) · line 407

Quoted 2 lines
scripts/mod/sumversion.c +0 -0
 	}

--
Cheers, Lorenzo

#79 lore raw

Re: [PATCH 17/23] modpost: perform srcversion hashing in parallel

In reply to Lorenzo Stoakes (ARM)

Hi,

Le 08/09/2026 à 22:55, Lorenzo Stoakes (ARM) a écrit :

Quoted 5 lines

modpost does a lot of single-threaded work hashing files from each object's .cmd file.

This makes the build slower than it needs to be, so do this work in parallel.

If you're going parallel, it would be nicer to do it under make's jobserver supervision.

Quoted 21 lines

This is egregious for allmodconfig builds - for instance x86-64 can end up opening 200,000 files individually and hashing them all serially.

Parallelise this operation by maintaining a thread pool for the hashing work.

Combined with the per-file hashing commit this cuts modpost's run time nearly in half for an allmodconfig build.

Module.symvers and every *.mod.S are byte for byte the same.

modpost is on the serial tail of every allmodconfig build, however defconfig does not set CONFIG_MODULE_SRCVERSION_ALL and is unchanged.

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

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

   x86 allmodconfig, touch mm/vma.c, gcc    33.4s    30.2s     -3.2s (-10%)
   x86 allmodconfig, touch mm/vma.c, clang  31.1s    28.1s     -3.0s (-10%)
Quoted 9 lines
Assisted-by LLM
---
  scripts/mod/Makefile     |  1 +
  scripts/mod/modpost.c    | 72 ++++++++++++++++++++++++++++++++++++++++++++++--
  scripts/mod/modpost.h    |  2 ++
  scripts/mod/sumversion.c |  3 +-
  4 files changed, 74 insertions(+), 4 deletions(-)

Regards.

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

#80 lore raw

Re: [PATCH 17/23] modpost: perform srcversion hashing in parallel

Quoted 6 lines · Yann Droneaud

Hi,

Le 08/09/2026 à 22:55, Lorenzo Stoakes (ARM) a écrit :

Quoted 3 lines

modpost does a lot of single-threaded work hashing files from each object's .cmd file.

Quoted 6 lines
Quoted 2 lines

This makes the build slower than it needs to be, so do this work in parallel.

If you're going parallel, it would be nicer to do it under make's jobserver supervision.

Ack, though this patch is going to be dropped due to mod versions being removed upstream.

Quoted 33 lines
Quoted 23 lines

This is egregious for allmodconfig builds - for instance x86-64 can end up opening 200,000 files individually and hashing them all serially.

Parallelise this operation by maintaining a thread pool for the hashing work.

Combined with the per-file hashing commit this cuts modpost's run time nearly in half for an allmodconfig build.

Module.symvers and every *.mod.S are byte for byte the same.

modpost is on the serial tail of every allmodconfig build, however defconfig does not set CONFIG_MODULE_SRCVERSION_ALL and is unchanged.

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

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

   x86 allmodconfig, touch mm/vma.c, gcc    33.4s    30.2s     -3.2s (-10%)
   x86 allmodconfig, touch mm/vma.c, clang  31.1s    28.1s     -3.0s (-10%)
Quoted 9 lines
Assisted-by LLM
---
  scripts/mod/Makefile     |  1 +
  scripts/mod/modpost.c    | 72 ++++++++++++++++++++++++++++++++++++++++++++++--
  scripts/mod/modpost.h    |  2 ++
  scripts/mod/sumversion.c |  3 +-
  4 files changed, 74 insertions(+), 4 deletions(-)
Quoted 3 lines

Regards.

--
Cheers, Lorenzo

#81 lore raw

PATCH 18/23 objtool: cache relocations and function dead end state, do less work

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.

For cases where sections are supplied out of order or grown one relocation at a time (e.g. livepatch), fall back to using the existing hash mechanism.

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().

So do not index or hash DWARF relocations at all - however add a mechanism such that if one were ever looked up, a linear scan will be used.

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 hash, when used, is read-mostly (every jump, call and memory operand) and several relocations share a key due to the 16-byte stride, so keep the hash sparse by scaling the hash by the number of objects to be hashed.

Another hotspot in objtool processing is determining 'dead end' functions, i.e. functions which never return.

Implement a simple boolean per-function cache for this to avoid determining this more than once per function.

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 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.4s     8.1s    -0.28s (-3%)
  x86 defconfig, touch mm/vma.c, clang      7.5s     7.1s    -0.41s (-5%)
  x86 defconfig, clean, gcc                27.1s    26.8s    -0.34s (-1%)
  x86 defconfig, clean, clang              26.6s    26.2s    -0.40s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    30.2s    28.4s     -1.8s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  28.1s    26.0s     -2.1s (-7%)
Assisted-by LLM
---
 tools/objtool/check.c               |  10 +-
 tools/objtool/elf.c                 | 242 +++++++++++++++++++++++++++++++++---
 tools/objtool/include/objtool/elf.h |   4 +
 3 files changed, 238 insertions(+), 18 deletions(-)
tools/objtool/check.c +9 -1
index 464f6c9d9ff0..2abd41cc3aaf 100644
@@ -305,7 +305,15 @@ static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
 
 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
 {
-	return __dead_end_function(file, func, 0);
+	if (!func)
+		return false;
+
+	if (!func->dead_end_known) {
+		func->dead_end = __dead_end_function(file, func, 0);
+		func->dead_end_known = 1;
+	}
+
+	return func->dead_end;
 }
 
 static void init_cfi_state(struct cfi_state *cfi)
tools/objtool/elf.c +225 -17

318 lines not on this page · raw message

tools/objtool/include/objtool/elf.h +4 -0
index a82517a76a0f..0d61ddfec05f 100644
@@ -59,6 +59,8 @@ struct section {
 	const char *name;
 	int idx;
 	bool _changed, text, rodata, noinstr, init, truncate;
+	bool hashed, sorted;
+	unsigned int *reloc_cache;
 	struct reloc *relocs;
 	unsigned long nr_alloc_relocs;
 	struct section *twin;
@@ -98,6 +100,8 @@ struct symbol {
 	u8 klp		     : 1;
 	u8 dont_correlate    : 1;
 	u8 fake		     : 1;
+	u8 dead_end_known    : 1;
+	u8 dead_end	     : 1;
 	struct list_head pv_target;
 	struct reloc *relocs;
 	struct section *group_sec;
Signature · 1 line
2.55.0
maintainer
#82 lore raw

Re: [PATCH 18/23] objtool: cache relocations and function dead end state, do less work

Quoted 10 lines · Lorenzo Stoakes (ARM)

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

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

  x86 defconfig, touch mm/vma.c, gcc        8.4s     8.1s    -0.28s (-3%)
  x86 defconfig, touch mm/vma.c, clang      7.5s     7.1s    -0.41s (-5%)
  x86 defconfig, clean, gcc                27.1s    26.8s    -0.34s (-1%)
  x86 defconfig, clean, clang              26.6s    26.2s    -0.40s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    30.2s    28.4s     -1.8s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  28.1s    26.0s     -2.1s (-7%)

Nice!

Quoted 5 lines
tools/objtool/check.c +0 -1
@@ -305,7 +305,15 @@ static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
 
 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
 {
-	return __dead_end_function(file, func, 0);

tools/objtool/check.c static bool __dead_end_function(struct objtool_file *file, struct symbol *func, · line 317

Quoted 10 lines
tools/objtool/check.c +9 -0
+	if (!func)
+		return false;
+
+	if (!func->dead_end_known) {
+		func->dead_end = __dead_end_function(file, func, 0);
+		func->dead_end_known = 1;
+	}
+
+	return func->dead_end;
 }

This bit seems like it should be a separate patch. Though actually, it can just be dropped as I have something similar brewing:

https://lore.kernel.org/9d4b8ccfed745ac47a954aa2e1de62a85197122d.1788899473.git.jpoimboe@kernel.org

tools/objtool/elf.c struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *se · line 456

Quoted 10 lines
tools/objtool/elf.c +7 -2
-struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
+/* Should never be invoked, provided as a backstop. */
+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;
+
+	WARN("%s: linear scan for sec %s with %u relocs at offset %lu len %u",
+	     __func__, rsec->name, sec_num_entries(rsec), offset, len);

Won't this be triggered for sections created with elf_create_rela_section()? I don't see where they set rsec->hashed.

Quoted 5 lines
tools/objtool/elf.c +1 -0
@@ -1147,6 +1307,28 @@ static int read_relocs(struct elf *elf)
 
 		rsec->base->rsec = rsec;
 
+		/* DWARF relocs are never looked up. */

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

Quoted 10 lines
tools/objtool/elf.c +10 -0
+		if (is_dwarf_section(rsec->base))
+			continue;
+		if (reloc_sec_in_order(rsec)) {
+			rsec->sorted = true;
+			continue;
+		}
+
+		rsec->hashed = true;
+		nr_hashed += sec_num_entries(rsec);
+	}

Hm, I'm not sure whether hashing is even still needed, as compilers generally emit sorted relocs.

tools/objtool/elf.c static int elf_alloc_reloc(struct elf *elf, struct section *rsec) · line 1802

Quoted 5 lines
tools/objtool/elf.c +1 -0
@@ -1592,6 +1799,7 @@ static int elf_alloc_reloc(struct elf *elf, struct section *rsec)
 	}
 
 	rsec->nr_alloc_relocs = nr_alloc;
+	copy_reloc_cache_to_hash(elf, rsec, nr_relocs_old);

Not all relocation appends go through this allocation code path. It can return earlier in this function if the space has already been allocated previously. So this call probably belongs in elf_create_reloc().

Signature · 1 line
Josh
#83 lore raw

Re: [PATCH 18/23] objtool: cache relocations and function dead end state, do less work

Quoted 33 lines · Josh Poimboeuf
Quoted 10 lines · Lorenzo Stoakes (ARM)

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

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

  x86 defconfig, touch mm/vma.c, gcc        8.4s     8.1s    -0.28s (-3%)
  x86 defconfig, touch mm/vma.c, clang      7.5s     7.1s    -0.41s (-5%)
  x86 defconfig, clean, gcc                27.1s    26.8s    -0.34s (-1%)
  x86 defconfig, clean, clang              26.6s    26.2s    -0.40s (-1%)
  x86 allmodconfig, touch mm/vma.c, gcc    30.2s    28.4s     -1.8s (-6%)
  x86 allmodconfig, touch mm/vma.c, clang  28.1s    26.0s     -2.1s (-7%)

Nice!

Quoted 5 lines
tools/objtool/check.c +0 -1
@@ -305,7 +305,15 @@ static bool __dead_end_function(struct objtool_file *file, struct symbol *func,
 
 static bool dead_end_function(struct objtool_file *file, struct symbol *func)
 {
-	return __dead_end_function(file, func, 0);

tools/objtool/check.c static bool __dead_end_function(struct objtool_file *file, struct symbol *func, · line 317

Quoted 10 lines
tools/objtool/check.c +9 -0
+	if (!func)
+		return false;
+
+	if (!func->dead_end_known) {
+		func->dead_end = __dead_end_function(file, func, 0);
+		func->dead_end_known = 1;
+	}
+
+	return func->dead_end;
 }

This bit seems like it should be a separate patch. Though actually, it can just be dropped as I have something similar brewing:

Quoted 2 lines

https://lore.kernel.org/9d4b8ccfed745ac47a954aa2e1de62a85197122d.1788899473.git.jpoimboe@kernel.org

Ack, dropped for v2, will reference that seris in the cover.

Quoted 5 lines
Quoted 5 lines
tools/objtool/elf.c +3 -1
-struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
+/* Should never be invoked, provided as a backstop. */
+static struct reloc *find_reloc_linear(struct section *rsec,
+				       unsigned long offset, unsigned int len)
 {
Quoted 8 lines

tools/objtool/elf.c struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *se · line 456

Quoted 5 lines
tools/objtool/elf.c +4 -1
-	return find_reloc_by_dest_range(elf, sec, offset, 1);
+	struct reloc *reloc, *first = NULL;
+
+	WARN("%s: linear scan for sec %s with %u relocs at offset %lu len %u",
+	     __func__, rsec->name, sec_num_entries(rsec), offset, len);

Won't this be triggered for sections created with elf_create_rela_section()? I don't see where they set rsec->hashed.

Good catch thanks, it was triggering for those, e.g. CONFIG_LIVEPATCH, repro'd locally.

Updated the code to hash these too correctly for v3.

Quoted 5 lines
Quoted 5 lines
tools/objtool/elf.c +0 -0
@@ -1147,6 +1307,28 @@ static int read_relocs(struct elf *elf)
 
 		rsec->base->rsec = rsec;
 
Quoted 14 lines

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

Quoted 11 lines
tools/objtool/elf.c +11 -0
+		/* DWARF relocs are never looked up. */
+		if (is_dwarf_section(rsec->base))
+			continue;
+		if (reloc_sec_in_order(rsec)) {
+			rsec->sorted = true;
+			continue;
+		}
+
+		rsec->hashed = true;
+		nr_hashed += sec_num_entries(rsec);
+	}

Hm, I'm not sure whether hashing is even still needed, as compilers generally emit sorted relocs.

They do, and anything read from the file in the build does, but this is a fallback for sections that objtool grows or creates itself which needs the duplicate check + can be appended out of order.

Quoted 11 lines

tools/objtool/elf.c static int elf_alloc_reloc(struct elf *elf, struct section *rsec) · line 1802

Quoted 6 lines
tools/objtool/elf.c +1 -0
@@ -1592,6 +1799,7 @@ static int elf_alloc_reloc(struct elf *elf, struct section *rsec)
 	}
 
 	rsec->nr_alloc_relocs = nr_alloc;
+	copy_reloc_cache_to_hash(elf, rsec, nr_relocs_old);

Not all relocation appends go through this allocation code path. It can return earlier in this function if the space has already been allocated previously. So this call probably belongs in elf_create_reloc().

Ack thanks, fixed for v2.

Quoted 3 lines

--
Josh

--
Cheers, Lorenzo

#84 lore raw

PATCH 19/23 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.

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.

Also update the instruction hash to be more efficient - it was previously hardcoded to a size of 2^20 buckets.

This is insufficient for an x86-64 allmodconfig kernel where an x86-64 build decodes ~16 million instructions and in practice find_insn() was observed working chains of four or more entries on lookup.

Instead size it based on the amount of text to be decoded at roughly one bucket per instruction, identical to the relocation hash (set to OFFSET_STRIDE).

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

Threads are only created for objects with 8 MiB or more of text, meaning that runs involving smaller objects remain unaffected.

Only decoding and the branch passes are threaded, so the gain flattens out at 16 threads and more only add overhead - on the clang allmodconfig vmlinux.o objtool takes 5.58s on 1 thread, 3.96s on 8, 3.91s on 16 and 4.03s on 128. Cap the thread count at 16, or the number of CPUs if fewer.

The passes which resolve jump and call destinations and annotate call sites all run over the same regions.

They only write to lists in struct objtool_file, so have each range work with their own copy of this data structure, which are then joined, in range order afterwards in a map-reduce fashion.

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.9s to 3.7s (6.5s to 3.7s together with the previous patch), and on defconfig from 1.87s to 1.26s.

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.1s     7.5s    -0.65s (-8%)
  x86 defconfig, touch mm/vma.c, clang      7.1s     6.6s    -0.51s (-7%)
  x86 defconfig, clean, gcc                26.8s    26.3s    -0.46s (-2%)
  x86 defconfig, clean, clang              26.2s    25.8s    -0.45s (-2%)
  x86 allmodconfig, touch mm/vma.c, gcc    28.4s    23.7s     -4.7s (-17%)
  x86 allmodconfig, touch mm/vma.c, clang  26.0s    22.1s     -3.9s (-15%)
Assisted-by LLM
---
 tools/objtool/Makefile                  |   2 +-
 tools/objtool/check.c                   | 757 ++++++++++++++++++++++++--------
 tools/objtool/include/objtool/objtool.h |   3 +-
 tools/objtool/objtool.c                 |   1 -
 4 files changed, 578 insertions(+), 185 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 +575 -182

878 lines not on this page · raw message

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
maintainer
#85 lore raw

Re: [PATCH 19/23] objtool: decode instructions and resolve branch targets in parallel

Quoted 33 lines · Lorenzo Stoakes (ARM)
tools/objtool/check.c +33 -0
+/* Only an object this large, e.g. vmlinux.o, is decoded on several threads. */
+#define DECODE_THREADED_MIN_TEXT	SZ_8M
+/* Only decoding and the branch passes are threaded, so more gains nothing. */
+#define DECODE_MAX_THREADS		16
+#define DECODE_RANGES_PER_THREAD	4
+
+/*
+ * 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));

tools/objtool/check.c static void *cfi_hash_alloc(unsigned long size) · line 469

Quoted 10 lines
tools/objtool/check.c +10 -0
+	if (!file->insn_hash) {
+		ERROR_GLIBC("calloc");
+		return -1;
+	}
+
+	if (opts.stats)
+		printf("insn_hash_bits: %d\n", file->insn_hash_bits);
+
+	return 0;
+}

The dynamic insn hash sizing should probably be its own patch. It's a standalone improvement, and much more obviously correct compared to the rest of patch. I suspect it will make a big difference on allyesconfig.

The rest of the patch looks ok to me, though it needs to be reviewed very carefully (which I haven't done yet). I'd like to see a Sashiko review (I wasn't able to find these patches on sashiko.dev for some reason).

Signature · 1 line
Josh
#86 lore raw

Re: [PATCH 19/23] objtool: decode instructions and resolve branch targets in parallel

Quoted 40 lines · Josh Poimboeuf
Quoted 39 lines · Lorenzo Stoakes (ARM)
tools/objtool/check.c +39 -0
+/* Only an object this large, e.g. vmlinux.o, is decoded on several threads. */
+#define DECODE_THREADED_MIN_TEXT	SZ_8M
+/* Only decoding and the branch passes are threaded, so more gains nothing. */
+#define DECODE_MAX_THREADS		16
+#define DECODE_RANGES_PER_THREAD	4
+
+/*
+ * 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)
Quoted 8 lines

tools/objtool/check.c static void *cfi_hash_alloc(unsigned long size) · line 469

Quoted 4 lines
tools/objtool/check.c +4 -0
+		printf("insn_hash_bits: %d\n", file->insn_hash_bits);
+
+	return 0;
+}

The dynamic insn hash sizing should probably be its own patch. It's a standalone improvement, and much more obviously correct compared to the rest of patch. I suspect it will make a big difference on allyesconfig.

Thanks, will split out!

Quoted 5 lines

The rest of the patch looks ok to me, though it needs to be reviewed very carefully (which I haven't done yet). I'd like to see a Sashiko review (I wasn't able to find these patches on sashiko.dev for some reason).

https://sashiko.dev/#/patchset/20260908-build-speedup-v1-0-5dc1ac01672d%40kernel.org
seems to be it?

I will work through the reports for v2!

Quoted 3 lines

--
Josh

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#88 lore raw

Re: [PATCH 19/23] objtool: decode instructions and resolve branch targets in parallel

Quoted 26 lines · On Tue, Sep 08, 2026 at 09:25:32PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] Concurrent list_add() on shared pv_ops list heads and symbol nodes corrupts doubly-linked lists.
- [Medium] Concurrent unsynchronized writes and read-modify-writes to elf->changed and sec->_changed boolean flags during threaded passes.
- [Medium] Dynamically allocated insn_hash is not freed, leaking up to 32 MiB.
- [Low] Memory leak of decode_ranges array on realloc failure and early error returns.
--

commit 979675b19c505e12e7330b836dbf233b74331260
Author: Lorenzo Stoakes (ARM) <[email protected]>

objtool: decode instructions and resolve branch targets in parallel

This commit introduces multi-threading to objtool for decoding instructions and resolving branch targets to speed up the kernel build. It sizes the instruction hash based on the text size and limits thread creation to objects with 8 MiB or more of text. The decoding and branch passes are threaded using a map-reduce fashion over split ranges of the objtool file.

Quoted 4 lines
tools/objtool/check.c +0 -0
index 2abd41cc3aaf7..b092cf8d582f7 100644

[ ... ]

Quoted 14 lines

tools/objtool/check.c static void *cfi_hash_alloc(unsigned long size) · line 459

Quoted 8 lines
tools/objtool/check.c +8 -0
+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));

[Severity: Medium]
Since the statically allocated hash table is replaced with a dynamically allocated array here, does this memory need to be freed? It looks like free_insns() was not updated to free file->insn_hash, which might leak up to 32 MiB of memory during objtool execution.

Yup fixed for v2.

Quoted 25 lines

[ ... ]

Quoted 11 lines
tools/objtool/check.c +11 -0
+static int decode_range(struct objtool_file *file, struct insn_range *range)
+{
+	struct instruction *insn = NULL;
+	struct section *sec = range->sec;
+	unsigned long offset;
+	u8 prev_len = 0;
+
+	for (offset = range->start; offset < range->end; offset += insn->len) {
+		const unsigned long remaining = sec_size(sec) - offset;
+
+		insn = next_insn_slot(insn);

tools/objtool/check.c static void *cfi_hash_alloc(unsigned long size) · line 563

Quoted 10 lines
tools/objtool/check.c +10 -0
+		if (!insn)
+			return -1;
+
+		INIT_LIST_HEAD(&insn->call_node);
+		insn->sec = sec;
+		insn->offset = offset;
+		insn->prev_len = prev_len;
+
+		if (arch_decode_instruction(file, sec, offset, remaining, insn))
+			return -1;
Quoted 7 lines

[Severity: High]
Can this concurrent decoding corrupt doubly-linked lists? During the threaded pass on x86_64, arch_decode_instruction() calls objtool_pv_add(). Because range->shadow shallow-copies the file structure, all threads share the identical f->pv_ops array and func symbols. The concurrent calls to list_add(&func->pv_target, &f->pv_ops[idx].targets) appear to have no locking.

Yes, valid, and ThreadSanitizer found more. Fixed in v2.

Quoted 19 lines

[ ... ]

tools/objtool/check.c static void *cfi_hash_alloc(unsigned long size) · line 710

Quoted 11 lines
tools/objtool/check.c +11 -0
+static int add_decode_range(struct section *sec, unsigned long start,
+			    unsigned long end)
+{
+	const size_t size = (nr_decode_ranges + 1) * sizeof(*decode_ranges);
+	struct insn_range *range;
+
+	decode_ranges = realloc(decode_ranges, size);
+	if (!decode_ranges) {
+		ERROR_GLIBC("realloc");
+		return -1;
+	}

[Severity: Low]
If realloc() fails here, it returns NULL and overwrites the decode_ranges pointer. Does this permanently leak the previously allocated memory for the array?

Nope, that failure results in objtool exiting so nothing leaks.

Quoted 22 lines

[ ... ]

tools/objtool/check.c static struct symbol *find_call_destination(struct section *sec, unsigned long o · line 2113

Quoted 12 lines
tools/objtool/check.c +12 -0
+static int add_call_destinations_range(struct objtool_file *file,
+				       struct insn_range *range)
+{
+	struct instruction *insn;
+
+	range_for_each_insn(file, range, insn) {
+		if (add_call_destination(file, insn))
+			return -1;
+	}
+
+	return 0;
+}

[Severity: Medium]
Does this threaded pass risk a data race on boolean flags? If a thread needs to patch an instruction (like removing KCOV from noinstr), add_call_destination() eventually calls set_reloc_type() and mark_sec_changed(). This executes:

Quoted 6 lines

elf->changed |= changed;
sec->_changed = changed;

Since elf and sec pointers are shared across all shadow copies, multiple threads might perform these bitwise operations and assignments concurrently without atomics, potentially losing flag updates.

It's not something that would have any impact.

Quoted 7 lines

[ ... ]

Quoted 4 lines
tools/objtool/check.c +0 -0
@@ -2689,6 +3080,8 @@ int decode_file(struct objtool_file *file)
 	if (read_annotate(file, __annotate_late))
 		return -1;
 
Quoted 9 lines

tools/objtool/check.c int decode_file(struct objtool_file *file) · line 3086

Quoted 4 lines
tools/objtool/check.c +2 -0
+	free_decode_ranges();
+
 	return 0;
 }

[Severity: Low]
If any analysis pass in decode_file() fails and returns early before reaching this point, does it bypass the call to free_decode_ranges(), leaking the decode_ranges array?

Nope, every early return is an error path that exits objtool so nonsense.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19

--
Cheers, Lorenzo

#89 lore raw

PATCH 20/23 kbuild: rust: parallelise rustc front end

In reply to Lorenzo Stoakes (ARM)

Rust crates are compiled in a serial chain on the critical path - core, bindings, kernel crates and then the drivers - each a rustc invocation.

With CONFIG_RUST set and every rust driver enabled, the entire chain takes around 25 seconds on a 128-thread machine, with the associated C code taking 24 seconds.

Each time a change is made to any of the bindings, it triggers a rebuild.

Use the -Zthreads option to have rustc perform builds in parallel. This has been available since rust 1.84 (rust-lang/rust#132282), and the kernel requires rust 1.85 or above.

A future -j/--jobs option is planned for rustc:(rust-lang/compiler-team#1005), so check to see if this available and if so use it.

If the user's rustc supports neither, then it falls back gracefully and neither are used.

The threads are taken from make's jobserver, so a parallel build is not oversubscribed. It was found that benefits level off at 8 threads (16 was found to be around the same, and 32 slower).

Generated output was confirmed byte-for-byte identical.

Observed build time changes (using rustc 1.98, clang):

before after

  core.o                                   7.7s	    4.9s
  bindings.o                               4.3s     3.1s
  kernel.o                                 2.0s     1.4s
  clean build                             39.3s    34.6s
  touch rust/kernel/lib.rs                12.9s    12.1s
  touch rust/bindings/bindings_helper.h   19.5s    17.5s

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

before after delta
-------------------------------
x86 defconfig+RUST, clean 41.0s 36.4s -4.6s (-11%)
x86 defconfig+RUST, touch lib.rs 8.3s 7.7s -0.56s (-7%)

Assisted-by LLM
---
 Makefile     | 4 ++++
 init/Kconfig | 7 +++++++
 2 files changed, 11 insertions(+)
Makefile +4 -0
index 997fc7ebe096..7d23d7b64be3 100644
@@ -1204,6 +1204,10 @@ KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro
 endif
 endif
 
+ifdef CONFIG_RUST
+KBUILD_RUSTFLAGS += $(if $(CONFIG_RUSTC_HAS_JOBS),-j8,$(if $(CONFIG_RUSTC_HAS_ZTHREADS),-Zthreads=8))
+endif
+
 # include additional Makefiles when needed
 include-y			:= scripts/Makefile.warn
 include-$(CONFIG_DEBUG_INFO)	+= scripts/Makefile.debug
init/Kconfig +7 -0
index 3c92c87254a3..4096a306e2ab 100644
@@ -231,6 +231,13 @@ config RUSTC_HAS_FILE_AS_C_STR
 config RUSTC_HAS_SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS
 	def_bool RUSTC_VERSION >= 109800
 
+# rustc's parallel front end: -j is the coming spelling, -Zthreads the current one
+config RUSTC_HAS_JOBS
+	def_bool $(rustc-option,-j8)
+
+config RUSTC_HAS_ZTHREADS
+	def_bool $(rustc-option,-Zthreads=8)
+
 config PAHOLE_VERSION
 	int
 	default "$(PAHOLE_VERSION)"
Signature · 1 line
2.55.0
#90 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 4 lines · Lorenzo Stoakes (ARM)

A future -j/--jobs option is planned for rustc:(rust-lang/compiler-team#1005), so check to see if this available and if so use it.

This is already implemented in nightly as far as I can tell. If it weren't, we shouldn't add it, even if planned.

(By the way, could you please add Link tags for those URLs?)

init/Kconfig config RUSTC_HAS_FILE_AS_C_STR · line 239

Quoted 5 lines
init/Kconfig +5 -0
+config RUSTC_HAS_JOBS
+       def_bool $(rustc-option,-j8)
+
+config RUSTC_HAS_ZTHREADS
+       def_bool $(rustc-option,-Zthreads=8)

We can simplify using RUSTC_VERSION for these like we do elsewhere.

Cheers,
Miguel

#91 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 10 lines · Miguel Ojeda
Quoted 4 lines · Lorenzo Stoakes (ARM)

A future -j/--jobs option is planned for rustc:(rust-lang/compiler-team#1005), so check to see if this available and if so use it.

This is already implemented in nightly as far as I can tell. If it weren't, we shouldn't add it, even if planned.

(By the way, could you please add Link tags for those URLs?)

Ack, will do.

Quoted 8 lines

init/Kconfig config RUSTC_HAS_FILE_AS_C_STR · line 239

Quoted 6 lines
init/Kconfig +5 -0
+config RUSTC_HAS_JOBS
+       def_bool $(rustc-option,-j8)
+
+config RUSTC_HAS_ZTHREADS
+       def_bool $(rustc-option,-Zthreads=8)

We can simplify using RUSTC_VERSION for these like we do elsewhere.

Ack also!

Quoted 3 lines

Cheers,
Miguel

--
Cheers, Lorenzo

reviewer
#92 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

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

Use the -Zthreads option to have rustc perform builds in parallel. This has been available since rust 1.84 (rust-lang/rust#132282), and the kernel requires rust 1.85 or above.

[..]

Generated output was confirmed byte-for-byte identical.

There are still several known reproducibility issues for the parallel frontend[1] and at least until fairly recently there were also deadlock issues and incorrect errors[2], so I would not recommend enabling it without an explicit request from the user. Perhaps even only allow it on nightly rustc for now, then you don't need to check which of the two spellings of the flag is supported.

By the way, currently backend parallelism is entirely disabled due to the usage of --emit obj (which forces -Ccodegen-units=1). For -O2/3 builds enabling backend parallelism may have a bigger impact than frontend parallelism. And it would make incremental compilation for rustc a lot more effective as editing a single function would no longer need to codegen all functions in a crate again, only those inside the same codegen unit. Getting it working would require using --emit link to produce rlibs and then linking those rlibs in the place of the raw object files. Rlibs are just static libraries containing some extra rustc specific info that will be ignored by the linker (no guarantees about this, but there are no guarantees --emit obj can be linked without missing symbols either and I don't know of any reason why we would change it right now. It would hurt compile times due to needing to repackage all rlibs before rustc runs linking.). I tried implementing this a couple of years ago, but back then if I recall correctly either binutils ar or llvm-ar was unable to produce a thin archive referencing members of another archive like Kbuild expects to do. I'm not familiar enough with Kbuild to know how to skip the thin archive production.

#93 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 7 lines · Björn Baron

There are still several known reproducibility issues for the parallel frontend[1] and at least until fairly recently there were also deadlock issues and incorrect errors[2], so I would not recommend enabling it without an explicit request from the user. Perhaps even only allow it on nightly rustc for now, then you don't need to check which of the two spellings of the flag is supported.

Thanks a lot for taking a look Björn.

If there are still major issues even in nightly, then I would say let's not add it yet -- some users/CIs are testing with nightly routinely, so it is probably best to avoid surprises for them. (If someone wants to test the flag, they can still pass it manually.)

On the other hand, if there are no major issues left and it is just reproducibility issues, then I guess we could add it to help figure those issues out and avoid surprises later on.

Quoted 2 lines

By the way, currently backend parallelism is entirely disabled due to the usage of --emit obj (which forces -Ccodegen-units=1). For -O2/3 builds

Yeah, we even set -Ccodegen-units=1 explicitly at the moment, so we would need to change that too (and likely make it an option, because normally end users will want the best results, while developers may want speed of iteration).

Cheers,
Miguel

#94 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 11 lines · Miguel Ojeda
Quoted 7 lines · Björn Baron

There are still several known reproducibility issues for the parallel frontend[1] and at least until fairly recently there were also deadlock issues and incorrect errors[2], so I would not recommend enabling it without an explicit request from the user. Perhaps even only allow it on nightly rustc for now, then you don't need to check which of the two spellings of the flag is supported.

Thanks a lot for taking a look Björn.

Quoted 8 lines

If there are still major issues even in nightly, then I would say let's not add it yet -- some users/CIs are testing with nightly routinely, so it is probably best to avoid surprises for them. (If someone wants to test the flag, they can still pass it manually.)

On the other hand, if there are no major issues left and it is just reproducibility issues, then I guess we could add it to help figure those issues out and avoid surprises later on.

Yup, I am encouraged by 'until fairly recently' on that ;) so maybe just bump version requirement to whatever this recently was?

Quoted 11 lines
Quoted 3 lines

By the way, currently backend parallelism is entirely disabled due to the usage of --emit obj (which forces -Ccodegen-units=1). For -O2/3 builds

Yeah, we even set -Ccodegen-units=1 explicitly at the moment, so we would need to change that too (and likely make it an option, because normally end users will want the best results, while developers may want speed of iteration).

Cheers,
Miguel

--
Cheers, Lorenzo

#95 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

In reply to Björn Baron

On Wed, Sep 09, 2026 at 10:22:33AM +0000, Björn Baron wrote:
[...]

Quoted 5 lines

I tried implementing this a couple of years ago, but back then if I recall correctly either binutils ar or llvm-ar was unable to produce a thin archive referencing members of another archive like Kbuild expects to do. I'm not familiar enough with Kbuild to know how to skip the thin archive production.

You might be referencing to llvm-ar <= 14, cp.
https://git.kernel.org/stable/c/a48bd961fb20
https://github.com/llvm/llvm-project/commit/d17c54d17de22d2961a04163f3dbc8e973de89b8

Signature · 1 line
Nicolas
#96 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

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

Rust crates are compiled in a serial chain on the critical path - core, bindings, kernel crates and then the drivers - each a rustc invocation.

With CONFIG_RUST set and every rust driver enabled, the entire chain takes around 25 seconds on a 128-thread machine, with the associated C code taking 24 seconds.

Each time a change is made to any of the bindings, it triggers a rebuild.

Use the -Zthreads option to have rustc perform builds in parallel. This has been available since rust 1.84 (rust-lang/rust#132282), and the kernel requires rust 1.85 or above.

A future -j/--jobs option is planned for rustc:(rust-lang/compiler-team#1005), so check to see if this available and if so use it.

If the user's rustc supports neither, then it falls back gracefully and neither are used.

The threads are taken from make's jobserver, so a parallel build is not oversubscribed. It was found that benefits level off at 8 threads (16 was found to be around the same, and 32 slower).

[...]

Makefile KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro · line 1209

Quoted 11 lines
Makefile +3 -0
index 997fc7ebe096..7d23d7b64be3 100644
@@ -1204,6 +1204,10 @@ KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro
 endif
 endif
 
+ifdef CONFIG_RUST
+KBUILD_RUSTFLAGS += $(if $(CONFIG_RUSTC_HAS_JOBS),-j8,$(if $(CONFIG_RUSTC_HAS_ZTHREADS),-Zthreads=8))
+endif

Is there a reason for the 'ifdef CONFIG_RUST'?

Hard-coding '8' feels a bit odd. If some kind of KBUILD_RUST_JOBS would be used, it could allow users to disable or override the parallelism for rust. Does it make sense to have rust parallelism configurable?

Signature · 1 line
Nicolas
#97 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 40 lines · Nicolas Schier
Quoted 23 lines · Lorenzo Stoakes (ARM)

Rust crates are compiled in a serial chain on the critical path - core, bindings, kernel crates and then the drivers - each a rustc invocation.

With CONFIG_RUST set and every rust driver enabled, the entire chain takes around 25 seconds on a 128-thread machine, with the associated C code taking 24 seconds.

Each time a change is made to any of the bindings, it triggers a rebuild.

Use the -Zthreads option to have rustc perform builds in parallel. This has been available since rust 1.84 (rust-lang/rust#132282), and the kernel requires rust 1.85 or above.

A future -j/--jobs option is planned for rustc:(rust-lang/compiler-team#1005), so check to see if this available and if so use it.

If the user's rustc supports neither, then it falls back gracefully and neither are used.

The threads are taken from make's jobserver, so a parallel build is not oversubscribed. It was found that benefits level off at 8 threads (16 was found to be around the same, and 32 slower).

[...]

Makefile KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro · line 1209

Quoted 11 lines
Makefile +3 -0
index 997fc7ebe096..7d23d7b64be3 100644
@@ -1204,6 +1204,10 @@ KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro
 endif
 endif
 
+ifdef CONFIG_RUST
+KBUILD_RUSTFLAGS += $(if $(CONFIG_RUSTC_HAS_JOBS),-j8,$(if $(CONFIG_RUSTC_HAS_ZTHREADS),-Zthreads=8))
+endif

Is there a reason for the 'ifdef CONFIG_RUST'?

Quoted 3 lines

Hard-coding '8' feels a bit odd. If some kind of KBUILD_RUST_JOBS would be used, it could allow users to disable or override the parallelism for rust. Does it make sense to have rust parallelism configurable?

Have decided to go with a build var for v2 - KBUILD_RUST_THREADS=n - which solves the default thread count, the instability issues and the confiigurability all at once! :)

Quoted 3 lines

--
Nicolas

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#99 lore raw

Re: [PATCH 20/23] kbuild: rust: parallelise rustc front end

Quoted 29 lines · On Tue, Sep 08, 2026 at 09:20:34PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Unconditionally passing -j8 or -Zthreads=8 to rustc breaks single-threaded Make invocations (e.g., make -j1 or simply make), forcing an 8-thread pool and creating an OOM risk. --

commit 31e6e028120fc1bff9382e6014058f3d1bbcb274
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: rust: parallelise rustc front end

This commit adds parallelization flags (-j or -Zthreads) to the rustc invocation for Rust kernel code. It uses Kconfig checks to detect compiler support and applies an 8-thread default to speed up the Rust frontend build process.

Makefile KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro · line 1208

Quoted 10 lines
Makefile +2 -0
index 997fc7ebe0965..7d23d7b64be33 100644
@@ -1204,6 +1204,10 @@ KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro
 endif
 endif
 
+ifdef CONFIG_RUST
+KBUILD_RUSTFLAGS += $(if $(CONFIG_RUSTC_HAS_JOBS),-j8,$(if $(CONFIG_RUSTC_HAS_ZTHREADS),-Zthreads=8))

[Severity: Medium]
Does unconditionally passing -j8 or -Zthreads=8 to rustc break single-threaded Make invocations (e.g. "make -j1" or just "make")?

Quoted 5 lines

It appears this might override Make's job controls and force an 8-thread pool even when no jobserver is present. On resource-constrained systems where users intentionally use "make -j1" to limit the RAM footprint, could this significantly increase memory consumption per rustc invocation and cause an out-of-memory error during the build?

No, when a jobserver is present it doesn't override that.

When -j1 yes it will, but the memory delta is small, a few hundred megabytes (~1.1 GiB vs. 1.4 GiB).

So it doesn't seem to be real world issue.

Quoted 8 lines

Makefile KBUILD_RUSTFLAGS += --remap-path-prefix=$(srcroot)/= --remap-path-scope=macro · line 1212

Quoted 5 lines
Makefile +2 -0
+endif
+
 # include additional Makefiles when needed
 include-y			:= scripts/Makefile.warn

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20

--
Cheers, Lorenzo

#100 lore raw

PATCH 21/23 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
#101 lore raw

PATCH 22/23 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.

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               | 11 ++++++++++-
 scripts/Makefile.build |  5 ++++-
 3 files changed, 19 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 +10 -1
index 7d23d7b64be3..3805f72428cb 100644
@@ -1429,11 +1429,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
@@ -1760,6 +1763,12 @@ modules: modules_prepare
 # Target to prepare building external modules
 modules_prepare: prepare
 	$(Q)$(MAKE) $(build)=scripts scripts/module.lds
+ifdef CONFIG_RUST
+# Ensure rust/ is build before any external rust module which will rely upon it.
+ifeq ($(MAKECMDGOALS),modules_prepare)
+	$(Q)$(MAKE) $(build)=rust
+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

A message that is not in the archive (sent off-list or not yet received): [email protected]

#103 lore raw

Re: [PATCH 22/23] kbuild: build rust crates in parallel with the rest of the build

Quoted 37 lines · On Tue, Sep 08, 2026 at 09:43:34PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The modules_prepare target fails to build the rust/ directory when multiple targets are specified on the command line. --

commit b7cbb20d375e296dcfc9da28b89bbc6beb01af39
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: build rust crates in parallel with the rest of the build

This commit allows Rust crates to be built in parallel with C code by removing the Rust build from the make prepare step and establishing a top-level list of directories containing Rust code. It also attempts to ensure that the rust/ dependency is established for out-of-tree module builds.

Quoted 4 lines
Makefile +0 -0
index 7d23d7b64be33..3805f72428cb2 100644

[ ... ]

Makefile modules: modules_prepare · line 1768

Quoted 7 lines
Makefile +3 -0
@@ -1760,6 +1763,12 @@ modules: modules_prepare
 # Target to prepare building external modules
 modules_prepare: prepare
 	$(Q)$(MAKE) $(build)=scripts scripts/module.lds
+ifdef CONFIG_RUST
+# Ensure rust/ is build before any external rust module which will rely upon it.
+ifeq ($(MAKECMDGOALS),modules_prepare)

[Severity: Medium]
Will this exact string comparison fail if multiple make targets are provided?

If a user or distribution build script runs a command with multiple targets, such as make modules_prepare scripts, MAKECMDGOALS will contain multiple words. The exact string match check here will fail, causing the compilation of the rust directory to be silently skipped.

Quoted 7 lines

This would result in the prepared kernel headers being incomplete and lacking necessary Rust artifacts like kernel.rmeta, preventing subsequent attempts to build out-of-tree Rust modules.

Could this check be modified to use the filter function to see if modules_prepare is present in MAKECMDGOALS instead of requiring an exact match?

Yeah this is valid, will fix in v2.

Quoted 10 lines

Makefile modules: modules_prepare · line 1774

Quoted 7 lines
Makefile +3 -0
+	$(Q)$(MAKE) $(build)=rust
+endif
+endif
 
 endif # CONFIG_MODULES
 

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22

--
Cheers, Lorenzo

#104 lore raw

PATCH 23/23 kbuild: use pigz for gzip compression if available

In reply to Lorenzo Stoakes (ARM)

The gzip step of a kernel build is very lengthily, 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.

It is already possible to specify the KGZIP environmental variable to make use of pigz, however it seems sensible to make use of pigz if it is available.

Therefore default to using pigz if it is available on the system upon which the kernel is being built, otherwise fall back to gzip.

The output is byte-for-byte identical between pigz/gzip invocations, but gzip and pigz do not produce the same stream as one another.

Therefore, for reproducible builds, the same set of tools should be used.

This seems to already be an implicit requirement in any case, but update the reproducible build documentation to make this clear.

Also update the kbuild documentation to reflect the change.

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.4s     5.4s     -2.0s (-27%)
  x86 defconfig, touch mm/vma.c, clang      6.6s     4.9s     -1.7s (-26%)
  x86 defconfig, clean, gcc                26.2s    24.4s     -1.8s (-7%)
  x86 defconfig, clean, clang              25.8s    24.3s     -1.5s (-6%)
  x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.3s     -8.4s (-35%)
  x86 allmodconfig, touch mm/vma.c, clang  22.1s    15.2s     -6.9s (-31%)
  x86 allmodconfig, clean, gcc            291.4s   275.2s     -16.2s (-6%)
  x86 allmodconfig, clean, clang          278.3s   265.7s     -12.6s (-5%)
---
 Documentation/kbuild/kbuild.rst              | 13 +++++++++++++
 Documentation/kbuild/reproducible-builds.rst | 16 ++++++++++++++++
 Makefile                                     |  2 +-
 3 files changed, 30 insertions(+), 1 deletion(-)
Documentation/kbuild/kbuild.rst +13 -0
index 5a9013bacfb7..ebfc2319d6da 100644
@@ -110,6 +110,19 @@ HOSTLDLIBS
 ----------
 Additional libraries to link against when building host programs.
 
+KGZIP
+-----
+The gzip compressor used for the compressed kernel image, compressed
+modules and packaging.
+
+If unset, it defaults to pigz (a parallel implementation of gzip) if available,
+otherwise gzip.
+
+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/kbuild/reproducible-builds.rst +16 -0
index bc1eb82211df..b95586df2cb5 100644
@@ -76,6 +76,22 @@ include generated files.  You should ensure the source tree is
 pristine by running ``make mrproper`` or ``git clean -d -f -x`` before
 building a source package.
 
+Compression tools
+-----------------
+
+The compressed kernel image, compressed modules and packages are produced
+using the binary specified by the environment variable ``KGZIP`` (described
+in Documentation/kbuild/kbuild.rst).
+
+This variable defaults to ``pigz`` if installed (a parallel implementation
+of gzip), or ``gzip`` otherwise.
+
+The generated output between two invocations of identical builds with
+either of the default tools will be byte-for-byte equivalent.
+
+However, for reproducible builds, ensure the same tool is used on all build
+hosts, as different tools may generate different output from one another.
+
 Module signing
 --------------
 
Makefile +1 -1
index 3805f72428cb..5cb819034372 100644
@@ -561,7 +561,7 @@ PERL		= perl
 PYTHON3		= python3
 CHECK		= sparse
 BASH		= bash
-KGZIP		= gzip
+KGZIP		:= $(if $(shell command -v pigz 2>/dev/null),pigz,gzip)
 KBZIP2		= bzip2
 KLZOP		= lzop
 LZMA		= lzma
Signature · 1 line
2.55.0
#105 lore raw

Re: [PATCH 23/23] kbuild: use pigz for gzip compression if available

Quoted 47 lines

The gzip step of a kernel build is very lengthily, 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.

It is already possible to specify the KGZIP environmental variable to make use of pigz, however it seems sensible to make use of pigz if it is available.

Therefore default to using pigz if it is available on the system upon which the kernel is being built, otherwise fall back to gzip.

The output is byte-for-byte identical between pigz/gzip invocations, but gzip and pigz do not produce the same stream as one another.

Therefore, for reproducible builds, the same set of tools should be used.

This seems to already be an implicit requirement in any case, but update the reproducible build documentation to make this clear.

Also update the kbuild documentation to reflect the change.

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.4s     5.4s     -2.0s (-27%)
  x86 defconfig, touch mm/vma.c, clang      6.6s     4.9s     -1.7s (-26%)
  x86 defconfig, clean, gcc                26.2s    24.4s     -1.8s (-7%)
  x86 defconfig, clean, clang              25.8s    24.3s     -1.5s (-6%)
  x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.3s     -8.4s (-35%)
  x86 allmodconfig, touch mm/vma.c, clang  22.1s    15.2s     -6.9s (-31%)
  x86 allmodconfig, clean, gcc            291.4s   275.2s     -16.2s (-6%)
  x86 allmodconfig, clean, clang          278.3s   265.7s     -12.6s (-5%)

...

Makefile PERL = perl · line 564

Quoted 10 lines
Makefile +1 -1
index a0d29dee81d7..efa6a2d77e6b 100644
@@ -561,7 +561,7 @@ PERL		= perl
 PYTHON3		= python3
 CHECK		= sparse
 BASH		= bash
-KGZIP		= gzip
+KGZIP		:= $(if $(shell command -v pigz 2>/dev/null),pigz,gzip)

This should be '?=', right? Sashiko also notes a concern around parallel module installation with gzip module compression since there is no thread limitation, which could bring a little risk to doing this by default? Might not be that big of a deal though?

Signature · 2 lines
Cheers,
Nathan
#106 lore raw

Re: [PATCH 23/23] kbuild: use pigz for gzip compression if available

Quoted 48 lines · Nathan Chancellor
Quoted 47 lines

The gzip step of a kernel build is very lengthily, 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.

It is already possible to specify the KGZIP environmental variable to make use of pigz, however it seems sensible to make use of pigz if it is available.

Therefore default to using pigz if it is available on the system upon which the kernel is being built, otherwise fall back to gzip.

The output is byte-for-byte identical between pigz/gzip invocations, but gzip and pigz do not produce the same stream as one another.

Therefore, for reproducible builds, the same set of tools should be used.

This seems to already be an implicit requirement in any case, but update the reproducible build documentation to make this clear.

Also update the kbuild documentation to reflect the change.

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.4s     5.4s     -2.0s (-27%)
  x86 defconfig, touch mm/vma.c, clang      6.6s     4.9s     -1.7s (-26%)
  x86 defconfig, clean, gcc                26.2s    24.4s     -1.8s (-7%)
  x86 defconfig, clean, clang              25.8s    24.3s     -1.5s (-6%)
  x86 allmodconfig, touch mm/vma.c, gcc    23.7s    15.3s     -8.4s (-35%)
  x86 allmodconfig, touch mm/vma.c, clang  22.1s    15.2s     -6.9s (-31%)
  x86 allmodconfig, clean, gcc            291.4s   275.2s     -16.2s (-6%)
  x86 allmodconfig, clean, clang          278.3s   265.7s     -12.6s (-5%)

...

Quoted 12 lines

Makefile PERL = perl · line 564

Quoted 10 lines
Makefile +1 -1
index a0d29dee81d7..efa6a2d77e6b 100644
@@ -561,7 +561,7 @@ PERL		= perl
 PYTHON3		= python3
 CHECK		= sparse
 BASH		= bash
-KGZIP		= gzip
+KGZIP		:= $(if $(shell command -v pigz 2>/dev/null),pigz,gzip)

This should be '?=', right? Sashiko also notes a concern around parallel

Actually make KGZIP=foo will override this still. But it doesn't take an environment variable for make -e.

However, that's consistent with other variables there like KBZIP2 etc.

Probably the wording in the docs should be tweaked!

Quoted 3 lines

module installation with gzip module compression since there is no thread limitation, which could bring a little risk to doing this by default? Might not be that big of a deal though?

Yeah, will modify so it single threads for things that aren't vmlinux on respin!

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#107 lore raw

Re: [PATCH 23/23] kbuild: use pigz for gzip compression if available

Quoted 6 lines · Lorenzo Stoakes (ARM)

Actually make KGZIP=foo will override this still. But it doesn't take an environment variable for make -e.

However, that's consistent with other variables there like KBZIP2 etc.

Probably the wording in the docs should be tweaked!

Hmmm, TIL, I thought := always overrode a value specified on the command line but I guess not! I don't think there is anything that needs to be clarified.

Signature · 2 lines
Cheers,
Nathan
#108 lore raw

Re: [PATCH 23/23] kbuild: use pigz for gzip compression if available

Quoted 11 lines · Nathan Chancellor
Quoted 6 lines · Lorenzo Stoakes (ARM)

Actually make KGZIP=foo will override this still. But it doesn't take an environment variable for make -e.

However, that's consistent with other variables there like KBZIP2 etc.

Probably the wording in the docs should be tweaked!

Hmmm, TIL, I thought := always overrode a value specified on the command line but I guess not! I don't think there is anything that needs to be clarified.

Yeah, news to me too :))

I did slightly tweak the doc so I didn't make a claim that wasn't valid on KGZIP re: env vars :)

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

A message that is not in the archive (sent off-list or not yet received): [email protected]

#110 lore raw

Re: [PATCH 23/23] kbuild: use pigz for gzip compression if available

Quoted 66 lines · On Tue, Sep 08, 2026 at 09:20:45PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Implicitly replacing gzip with pigz causes massive nested parallelism (N^2 thread explosion) and resource exhaustion during parallel make modules_install.
- [Medium] The KGZIP variable is unconditionally assigned using := in the Makefile, ignoring user-supplied environment variables and breaking the documented reproducible build instructions. --

commit 705f9cac49412988e279fbfecc9fcd8e34672bd2
Author: Lorenzo Stoakes (ARM) <[email protected]>

kbuild: use pigz for gzip compression if available

The gzip step of a kernel build is very lengthily, 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.
Therefore default to using pigz if it is available on the system upon which the kernel is being built, otherwise fall back to gzip.

Quoted 4 lines
Documentation/kbuild/kbuild.rst +0 -0
index 5a9013bacfb75..ebfc2319d6dac 100644

[ ... ]

Documentation/kbuild/kbuild.rst HOSTLDLIBS · line 119

Quoted 11 lines
Documentation/kbuild/kbuild.rst +7 -0
@@ -110,6 +110,19 @@ HOSTLDLIBS
 ----------
 Additional libraries to link against when building host programs.
 
+KGZIP
+-----
+The gzip compressor used for the compressed kernel image, compressed
+modules and packaging.
+
+If unset, it defaults to pigz (a parallel implementation of gzip) if available,
+otherwise gzip.

[Severity: Medium]
Will this fallback behavior actually work as documented?

Looking at the assignment in the Makefile, KGZIP is unconditionally assigned using the := operator, which overrides any user-supplied environment variables.

If a user sets export KGZIP=gzip as instructed to ensure reproducible builds, but runs make without command-line variable overrides, wouldn't the Makefile unconditionally overwrite their environment variable?

[ ... ]

Makefile PERL = perl · line 564

Quoted 10 lines
Makefile +1 -1
index 3805f72428cb2..5cb8190343729 100644
@@ -561,7 +561,7 @@ PERL		= perl
 PYTHON3		= python3
 CHECK		= sparse
 BASH		= bash
-KGZIP		= gzip
+KGZIP		:= $(if $(shell command -v pigz 2>/dev/null),pigz,gzip)

[Severity: High]
Could this implicit replacement of gzip with pigz cause massive thread explosion and resource exhaustion during parallel module installations?

When running make modules_install -jN on a multi-core system with pigz installed and CONFIG_MODULE_COMPRESS_GZIP enabled, make spawns N concurrent instances of cmd_gzip.

Quoted 8 lines

Looking at scripts/Makefile.modinst, it invokes the compressor without restricting its thread count:

    cmd_gzip = $(KGZIP) -n -f $<

Since pigz defaults to using all available CPU cores, wouldn't this result in N*C active threads during parallel module installs, leading to CPU thrashing and potential out-of-memory errors?

These have already been addressed for v2 as were raised by Nathan.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23

--
Cheers, Lorenzo

#111 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 11 lines · Lorenzo Stoakes (ARM)

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.

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.

Cool! I have not reviewed this patch series, but am supportive of solving the problem, since I do recall this being an issue;

i.e. it always annoyed me that despite have a 128 core machine, much of the build is sequential! Having all those cores and not saturating them during a build was always something I noticed (usually have system monitor always showing system load, always) but never had time to look into.

It would be cool if your LLM could generate any visualizations of what's going on during a build? Seeing what's serial vs parallelized in perhaps useful. Particularly when you can compare the before vs after.

Signature · 2 lines
Thanks,
~Nick Desaulniers
#112 lore raw
Quoted 9 lines · Nick Desaulniers
Quoted 6 lines · Lorenzo Stoakes (ARM)

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.

Quoted 6 lines
Quoted 3 lines

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.

Cool! I have not reviewed this patch series, but am supportive of solving the problem, since I do recall this being an issue;

Thanks :)

Quoted 6 lines

i.e. it always annoyed me that despite have a 128 core machine, much of the build is sequential! Having all those cores and not saturating them during a build was always something I noticed (usually have system monitor always showing system load, always) but never had time to look into.

Yeah this was exactly the motivation.

I've seen single-threaded stalls endlessly in kernel builds, even on smaller boxes, and thought that there must be a lot of low-hanging fruit there.

Obviously I have not enough time to do anything extra (TM) so never dug into it.

Which made it a great candidate for LLM usage (though with a LOT of taming, reviewing, auditing, rewriting of code because I _still_ have to be able to maintain my changes and there's still a bar there :)

Quoted 5 lines

It would be cool if your LLM could generate any visualizations of what's going on during a build? Seeing what's serial vs parallelized in perhaps useful. Particularly when you can compare the before vs after.

Great idea!

I asked it to do exactly that, attached. Came out quite nice and sums it up nicely :)

It also provided an ASCII version:

x86 allmodconfig, clang, 128 threads. One character per interval: height = CPU utilisation, letter beneath = what was running (C compile, L link, O objtool, P modpost, K kallsyms, Z compress, m make, . idle)

== clean build (4s per character) ==
before ▁▁▁▁▁▂█████████████████████████████████████████████████████████▃▁▁▁▁▁▁▁███████████▇▅▁▁ 343.6s
mCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCOOOOPPPCCCCCCCCCCCCCLL
after ▁▆████████████████████████████████████████████████████████▇▁▁▁▄██▆▁ 265.6s
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCOOCCCCC

== touch mm/vma.c (0.5s per character) ==
before ▁▁▁█▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ 45.7s
mCmCCmmmCLOOOOOOOOOOOOOOOOOOOOmPPPPPPPPPPPPPPPPPPPCLmKKKCCCmmKKKCCCLmmmmmmCCZZZZZZZZZZZZZZC
after ▁▁▅▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▁▁▁▁▁▁▁▁▁▁▁▁▂▁ 15.7s
mmCCCLOOOOOOOOOPPPPLKCKCLmmmmmCC

== no-op make (0.2s per character) ==
before ▁▁▁▁▁▁▁███▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ 14.4s
CCCCmmmCCCmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
after ▁▁▁▁▄▆▄▁ 2.0s
CCmmmCmm

Quoted 3 lines

--
Thanks,
~Nick Desaulniers

--
Cheers, Lorenzo

#113 lore raw
Quoted 7 lines · Lorenzo Stoakes (ARM)
Quoted 4 lines · Nick Desaulniers

It would be cool if your LLM could generate any visualizations of what's going on during a build? Seeing what's serial vs parallelized in perhaps useful. Particularly when you can compare the before vs after.

Quoted 6 lines

Great idea!

I asked it to do exactly that, attached. Came out quite nice and sums it up nicely :)

It also provided an ASCII version:

unreadable, but the pictures you attached are worth a thousand words. Particularly exciting are the speed ups to the usual edit+compile+run loop.

For the blue graph (the top one, first), any idea what that dip in the middle is? That's always what annoyed me.

Signature · 2 lines
Thanks,
~Nick Desaulniers
#114 lore raw
Quoted 8 lines · Nick Desaulniers
Quoted 7 lines · Lorenzo Stoakes (ARM)
Quoted 4 lines · Nick Desaulniers

It would be cool if your LLM could generate any visualizations of what's going on during a build? Seeing what's serial vs parallelized in perhaps useful. Particularly when you can compare the before vs after.

Quoted 8 lines
Quoted 6 lines

Great idea!

I asked it to do exactly that, attached. Came out quite nice and sums it up nicely :)

It also provided an ASCII version:

unreadable, but the pictures you attached are worth a thousand words.

:) Yeah I didn't think the ASCII was amazing either but fun that it tried ;) and yeah I was surprised at how nice the graphic came out...!

Quoted 2 lines

Particularly exciting are the speed ups to the usual edit+compile+run loop.

Yes! I never really expected that out of this!

I mean I didn't think there'd be such a big speed up in general, though I expected at least to shave off a big chunk of the delta between compile + full build on a defconfig clean build.

But the incremental/noop build improvements are really important to day-to-day use.

Quoted 3 lines

For the blue graph (the top one, first), any idea what that dip in the middle is? That's always what annoyed me.

That's ld -r of vmlinux.o, then modpost and objtool which are critical path blockers on the rest of the build.

Before the series that was 23 seconds for allmodconfig on the threadripper, now 7s :)

There's still more objtool stuff that could be done that I opted not to do yet, it takes 6s to run so dominating.

Quoted 3 lines

--
Thanks,
~Nick Desaulniers

--
Cheers, Lorenzo

#115 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 2 lines · Lorenzo Stoakes (ARM)

A typical kernel build consists of a frustratingly large amount of time

.. you're preaching to the choir.

Quoted 5 lines
                == allmodconfig FULL build ==

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

Threadripper, gcc 345.3s 275.2s -70.1s (-20%)

Well, that's certainly very encouraging. We should do this. I sent out some emails as just reactions to individual patches, but I have no numbers to back any of those emails up, and I never actually applied this series to my tree - they were all based on reading the patches themselves.

Quoted 4 lines · That

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.

This made me scared to look at the patches originally, and I held off in fear that the patches would be horrible and this build time improvement would be hugely controversial garbage code.

But:

Quoted 2 lines

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

None of the patches look at all horrible to me. You clearly excised the hideous parts. All of my reactions were of the type "this could probably be taken _further_" rather than me throwing my hands up in disgust.

So the Rust parallelism thing clearly isn't ready based on feedback from that quarter, but the rest looked safe and innocuous. I'm all for merging this, although it should obviously go in through the right channels. Mostly the kbuild tree, although some of it clearly would be other cases - the objtool change in particular is fairly substantial and needsobjtool people to approve. It didn't look all that contentious, but still..

Anyway, I'd love for this all to go in. Build times are a pet peeve of mine.

Linus

#116 lore raw
Quoted 5 lines · Linus Torvalds
Quoted 2 lines · Lorenzo Stoakes (ARM)

A typical kernel build consists of a frustratingly large amount of time

.. you're preaching to the choir.

:) Yeah, it's something that's annoyed me for a long time too.

Quoted 7 lines
Quoted 6 lines
                == allmodconfig FULL build ==

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

Threadripper, gcc 345.3s 275.2s -70.1s (-20%)

Quoted 5 lines

Well, that's certainly very encouraging. We should do this. I sent out some emails as just reactions to individual patches, but I have no numbers to back any of those emails up, and I never actually applied this series to my tree - they were all based on reading the patches themselves.

Thanks, will have a read through those!

I do recommend trying them locally ;)

It makes a surprising difference to defconfig even. (Though you need pigz installed for the full effect)

Quoted 14 lines
Quoted 4 lines · That

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.

This made me scared to look at the patches originally, and I held off in fear that the patches would be horrible and this build time improvement would be hugely controversial garbage code.

But:

Quoted 7 lines
Quoted 2 lines

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

None of the patches look at all horrible to me. You clearly excised the hideous parts. All of my reactions were of the type "this could probably be taken _further_" rather than me throwing my hands up in disgust.

Thanks! :)

I made sure to audit everything it came up with patch-by-patch, got it to rework the horrors then rewrote large chunks of what it came up with.

Quoted 3 lines

So the Rust parallelism thing clearly isn't ready based on feedback from that quarter, but the rest looked safe and innocuous. I'm all for

Sure, happy to drop anything like that.

Though based on what Miguel said it _might_ be ok perhaps with a nightly gate on it? Will see what he/Bjorn say.

Quoted 5 lines

merging this, although it should obviously go in through the right channels. Mostly the kbuild tree, although some of it clearly would be other cases - the objtool change in particular is fairly substantial and needsobjtool people to approve. It didn't look all that contentious, but still..

Agreed, it definitely needs some eyes on it, especially the trickier bits.

Quoted 2 lines

Anyway, I'd love for this all to go in. Build times are a pet peeve of mine.

Yeah, it'd be nice to see this benefit everyone!

Am happy to iterate on it as needed to get it upstream.

Quoted 2 lines

Linus

--
Cheers, Lorenzo

#117 lore raw
In reply to Linus Torvalds

Hi Lorenzo, Linus,

I maintain Sparky Stereo OS and have preliminary measurements of preparing reduced compiler inputs ahead of consumption.
Our Lean Code pipeline retains the complete authored source and generates a representation with removable comments eliminated, preserving required directives and source locations. The aim is fewer bytes for repeated consumers to read and scan.

On an AMD A10-9600P laptop with 12 GB RAM and SATA SSD storage, our 17 October header experiment changed 6,290 files out of 10,352 examined. The changed subset went from 61,154,706 to 44,167,571 bytes: 16,987,135 fewer bytes (27.8%).
Preparing it with two workers took 258.94 seconds.
These are file-size figures, not measured disk reads.

Using the prepared headers, the elapsed-time medians were:

                             pairs   authored     lean
Qt umbrella, syntax only       20    9,284.25 ms  9,259.50 ms
Qt umbrella, -O2 -g            20   10,970.60 ms 11,046.45 ms
Qt umbrella, preprocessing     20      882.45 ms    890.25 ms
acpi_call module, -j1          10    4,672.95 ms  4,677.45 ms
v4l2loopback module, -j1       10    6,572.40 ms  6,541.05 ms

All builds exited successfully, but these measurements do not establish a compilation speedup.
The experiment used engine 0.1.2, always ran authored before lean within each pair, and used different header paths; it does not establish binary equivalence either. We have not measured full-kernel builds.
Any benefit from reuse must also repay the preparation and verification cost.

Separately, with engine 0.1.3 on the same laptop, eight paired application-start rounds with variant order reversed each round gave these median paired window-time changes:

cold warm cold pairs faster

plasmashell        -159.9 ms   +43.8 ms       7/8
Dolphin             -66.7 ms    -6.9 ms       5/8
Discover            -70.6 ms    -1.4 ms       6/8
System Settings     -38.1 ms   -41.9 ms       4/8

Those used 95 selected runtime text files in a nested headless environment.
CPU temperatures ranged from 63 to 91 degrees C, so these are preliminary observations, not evidence of a general speedup or a kernel-build result.

The policy and implementation are public:
Policy: https://github.com/danielcamposramos/driver_stereodisplay/blob/main/sparky-os/LEAN-CODE-POLICY.md
Implementation: https://github.com/danielcamposramos/driver_stereodisplay/tree/main/sparky-os/lean

Would a controlled kernel-build comparison, including preparation cost and repeated-use break-even, be useful to this discussion? I can provide the raw records behind these preliminary numbers.

I develop this with Claude and Codex as AI partners and take responsibility for this report.

Daniel Campos Ramos

#118 lore raw

Hi Lorenzo, Linus,

A follow-up to my 20 October note, with controlled numbers.

The principle is the compiler's, applied to comments: prepare once what the machine reads, and keep what people read beside it. The web already does this: minifiers remove 48 to 70% of JavaScript bytes in one study, and source maps lead back to the original. Debian does it for binaries: stripped in the package, debug symbols in -dbgsym.
Lean Code does it for the text a system reads: headers, scripts, settings.

Every changed file has three forms:
1. The authored source, unchanged, in the source package.
2. The machine form, installed: comment-only lines removed; blank lines, directives and code untouched.
3. The human form, the complete authored text, in a <package>-lc-hr companion at the same version.
The human form costs nothing at build or run time, so documentation can grow there, better grounded, paid for once by the person who reads it. Line numbers shift on purpose; a tool finds a machine-form line by its content in the authored source (dpkg-stereo --resolve PATH:LINE). An earlier form inserted #line directives: it cost about 21% more preprocessing and silently disabled -Wmisleading-indentation. It is gone.

Measured, per file type (instructions with perf):
- Kernel headers, linux-headers 7.3.1, 50.7 to 46.9 MB (-7.5%): preprocessing -0.78%, compiling -0.52%.
- libstdc++, 864 headers (-23.6% bytes): preprocessing -2.7 to -3.0% instructions and -3.9 to -4.3% cycles; -O2 objects byte-identical; one compile of bits/stdc++.h reads 1.9 MB less.

Measured, the whole system: a 2016 AMD A10 laptop, 28,500 installed files lean, then restored to the originals, then lean again:
- DKMS module builds against the kernel headers: 6 to 9% faster warm, 1 to 6% cold. That is more than the instruction counts, which points at reading and caching; the two are not separated yet.
- Programs use 3 to 6% less memory; boot time is unchanged; installed package files take 140 MB less disk.
- The cost: 0.4 to 0.8 s more per dpkg run for the integrity check (about 64 ms in the current version), and a full verification takes 22 s instead of 11.
- Modules built lean are identical to each other; against the original headers, modules whose macros carry header line numbers differ in those numbers only.

Scaled, as estimates rather than measurements; I found no reliable count of Linux machines, so per million, to multiply by any fleet:
- A developer building 1 hour a day against kernel headers saves 15 to 22 hours a year; per million such machines, 15 to 22 million hours.
- Per million machines: 140 TB less disk, and 3.8 TB less page cache where the kernel headers are kept.
- A desktop user who never compiles comes out about even.

For scale: GCC 16 builds the kernel about 2.6% slower than GCC 15 in one report; Ingo Molnar's first header attempts gave barely 4% before Fast Kernel Headers reached 50 to 80% with over 2,000 commits; your series reports allmodconfig up to 36% faster. This stacks with all of them, with no source change.

I am not proposing anything for the kernel tree.
If a defconfig or allmodconfig comparison on the kernel's own include/, with the objects checked, would be useful, I can run it. Methods and raw data:
https://github.com/Sparky-OS/sparky-stereo-os/blob/main/docs/proofs/lean-code-a10-aba.md
https://github.com/Sparky-OS/sparky-stereo-os/blob/main/docs/proofs/lean-code-compile-cycles.md

Daniel Campos Ramos

#119 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 9 lines · Lorenzo Stoakes (ARM)

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.

Quoted 8 lines

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)

My AMD EPYC 9454P server shows an improvement in the order of 13% using the arm64's defconfig and make -j97. Thanks for doing this!

Signature · 1 line
Florian
#120 lore raw
Quoted 14 lines · Florian Fainelli
Quoted 13 lines · Lorenzo Stoakes (ARM)

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:

Quoted 7 lines
Quoted 4 lines

* 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)

My AMD EPYC 9454P server shows an improvement in the order of 13% using the arm64's defconfig and make -j97. Thanks for doing this!

Nice thanks! Good to confirm others are seeing the benefits :)

Quoted 3 lines

--
Florian

--
Cheers, Lorenzo

#121 lore raw
Quoted 20 lines · Lorenzo Stoakes (ARM)
Quoted 19 lines · Florian Fainelli
Quoted 17 lines · Lorenzo Stoakes (ARM)

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)

Quoted 4 lines
Quoted 2 lines

My AMD EPYC 9454P server shows an improvement in the order of 13% using the arm64's defconfig and make -j97. Thanks for doing this!

Nice thanks! Good to confirm others are seeing the benefits :)

I see similar gains on an 80-core Ampere Altra system

6h 21m 42s -> 5h 31m 15s (-13.22%)

and a 32-core AMD system.

3h 38m 55s -> 3h 13m 18s (-11.7%)

The build matrices were different between machines but it is good to see similar numbers across different environments.

Signature · 2 lines
Cheers,
Nathan
#122 lore raw
Quoted 28 lines · Nathan Chancellor
Quoted 20 lines · Lorenzo Stoakes (ARM)
Quoted 19 lines · Florian Fainelli
Quoted 17 lines · Lorenzo Stoakes (ARM)

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)

Quoted 4 lines
Quoted 2 lines

My AMD EPYC 9454P server shows an improvement in the order of 13% using the arm64's defconfig and make -j97. Thanks for doing this!

Nice thanks! Good to confirm others are seeing the benefits :)

I see similar gains on an 80-core Ampere Altra system

Quoted 8 lines

6h 21m 42s -> 5h 31m 15s (-13.22%)

and a 32-core AMD system.

3h 38m 55s -> 3h 13m 18s (-11.7%)

The build matrices were different between machines but it is good to see similar numbers across different environments.

Nice, yes for sure!

Quoted 4 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo

#123 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 104 lines

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:

		== allmodconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       345.3s   275.2s    -70.1s (-20%)
Threadripper, clang     345.5s   265.7s    -79.8s (-23%)
EPYC, gcc               188.6s   121.1s    -67.5s (-36%)
EPYC, clang             261.7s   184.6s    -77.1s (-29%)
		== allmodconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        46.4s    15.3s    -31.1s (-67%)
Threadripper, clang      44.4s    15.2s    -29.1s (-66%)
EPYC, gcc                82.0s    24.3s    -57.7s (-70%)
EPYC, clang              77.6s    24.3s    -53.3s (-69%)
		== allmodconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       12.97s    1.18s   -11.79s (-91%)
Threadripper, clang     13.84s    1.64s   -12.20s (-88%)
EPYC, gcc               25.92s    1.52s   -24.40s (-94%)
EPYC, clang             27.58s    2.17s   -25.41s (-92%)
		== defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        35.3s    28.6s     -6.7s (-19%)
Threadripper, clang      33.5s    26.1s     -7.4s (-22%)
EPYC, gcc                31.2s    20.6s    -10.6s (-34%)
EPYC, clang              38.6s    32.2s     -6.4s (-17%)
M2, gcc                 564.0s   512.4s    -51.6s (-9%)
M2, clang               616.1s   569.4s    -46.7s (-8%)
		== defconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        11.6s     5.5s     -6.1s (-53%)
Threadripper, clang      11.6s     5.0s     -6.6s (-57%)
EPYC, gcc                19.3s     9.2s    -10.1s (-52%)
EPYC, clang              20.1s     8.6s    -11.5s (-57%)
M2, gcc                  18.6s     9.9s     -8.7s (-47%)
M2, clang                18.6s     8.2s    -10.4s (-56%)
		== defconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        0.96s    0.47s    -0.49s (-51%)
Threadripper, clang      1.21s    0.55s    -0.66s (-55%)
EPYC, gcc                1.47s    0.66s    -0.81s (-55%)
EPYC, clang              1.87s    0.80s    -1.07s (-57%)
M2, gcc                  5.59s    1.69s    -3.90s (-70%)
M2, clang                6.62s    1.74s    -4.88s (-74%)

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.

Quoted 5 lines

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.

I appreciate all of the testing that you have done! I will test this side by side on a couple of my own machines to see what results I get but I do like those results.

Quoted 10 lines
			== 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.x

Quoted 8 lines

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.

Thank you for calling all of this out as well.

Quoted 9 lines
			== 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.

Quoted 8 lines

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 ==

mksysmap (1, 2): A couple of bugfixes the rest of the series relies
upon.

As I note in other threads of this review, I think we should take these to Linus now, they seem Obviously CorrectTM and it helps chunk out the series.

I have just reviewed a few of the low hanging fruit patches. I will try to take a look at the rest over the next couple of weeks but I might not get to them until after Plumbers. I would greatly appreciate if there are others who are more knowledgeable in these areas who could review these changes, as I don't know too much about some of the corners of Kbuild yet.

Signature · 2 lines
Cheers,
Nathan
#124 lore raw
Quoted 107 lines · Nathan Chancellor
Quoted 107 lines

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:

		== allmodconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       345.3s   275.2s    -70.1s (-20%)
Threadripper, clang     345.5s   265.7s    -79.8s (-23%)
EPYC, gcc               188.6s   121.1s    -67.5s (-36%)
EPYC, clang             261.7s   184.6s    -77.1s (-29%)
		== allmodconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        46.4s    15.3s    -31.1s (-67%)
Threadripper, clang      44.4s    15.2s    -29.1s (-66%)
EPYC, gcc                82.0s    24.3s    -57.7s (-70%)
EPYC, clang              77.6s    24.3s    -53.3s (-69%)
		== allmodconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc       12.97s    1.18s   -11.79s (-91%)
Threadripper, clang     13.84s    1.64s   -12.20s (-88%)
EPYC, gcc               25.92s    1.52s   -24.40s (-94%)
EPYC, clang             27.58s    2.17s   -25.41s (-92%)
		== defconfig FULL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        35.3s    28.6s     -6.7s (-19%)
Threadripper, clang      33.5s    26.1s     -7.4s (-22%)
EPYC, gcc                31.2s    20.6s    -10.6s (-34%)
EPYC, clang              38.6s    32.2s     -6.4s (-17%)
M2, gcc                 564.0s   512.4s    -51.6s (-9%)
M2, clang               616.1s   569.4s    -46.7s (-8%)
		== defconfig INCREMENTAL build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        11.6s     5.5s     -6.1s (-53%)
Threadripper, clang      11.6s     5.0s     -6.6s (-57%)
EPYC, gcc                19.3s     9.2s    -10.1s (-52%)
EPYC, clang              20.1s     8.6s    -11.5s (-57%)
M2, gcc                  18.6s     9.9s     -8.7s (-47%)
M2, clang                18.6s     8.2s    -10.4s (-56%)
		== defconfig NO-OP build ==

                        before    after     delta
                      ----------------------------------
Threadripper, gcc        0.96s    0.47s    -0.49s (-51%)
Threadripper, clang      1.21s    0.55s    -0.66s (-55%)
EPYC, gcc                1.47s    0.66s    -0.81s (-55%)
EPYC, clang              1.87s    0.80s    -1.07s (-57%)
M2, gcc                  5.59s    1.69s    -3.90s (-70%)
M2, clang                6.62s    1.74s    -4.88s (-74%)

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.

Quoted 6 lines
Quoted 2 lines

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

I appreciate all of the testing that you have done! I will test this side by side on a couple of my own machines to see what results I get but I do like those results.

Ack thanks :)

Quoted 13 lines
Quoted 13 lines
			== 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.x

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

Quoted 8 lines
Quoted 6 lines

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.

Thank you for calling all of this out as well.

Of course, I am on the receiving end of a flood of LLM patches in mm, so it's important to me to be transparent and consistent.

I repeatedly tell people - audit what it makes with a human pass, fix up awful code/comments/commit msgs, make sure you understand it + on you to make upstreamable + obviously ack that you used it.

So what's good for the goose is good for the gander :)

Quoted 14 lines
Quoted 14 lines
			== 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.

Quoted 8 lines
Quoted 4 lines
			== Patches ==

mksysmap (1, 2): A couple of bugfixes the rest of the series relies
upon.

As I note in other threads of this review, I think we should take these to Linus now, they seem Obviously CorrectTM and it helps chunk out the series.

Ack thanks. I will continue to include them in respins just to enforce the ordering in the meantime, but it should all come out in the wash I think?

I can add something in the cover letter too about these.

Quoted 7 lines

I have just reviewed a few of the low hanging fruit patches. I will try to take a look at the rest over the next couple of weeks but I might not get to them until after Plumbers. I would greatly appreciate if there are others who are more knowledgeable in these areas who could review these changes, as I don't know too much about some of the corners of Kbuild yet.

Thanks so much for taking a look! I'll be at plumbers so feel free to come say hi + discuss any of this in person.

And thanks to everybody else reviewing also!

I've replied to the more straightforward stuff, will take a deeper look at Linus's comments + anything else that needs a deeper think + sashiko reports a little later before sending a v2.

Quoted 5 lines

--
Cheers,
Nathan

--
Cheers, Lorenzo