add support for Clang LTO
Subsystems (23)
[email protected]
maintainerRe: [PATCH v2 05/28] objtool: Add a pass for generating __mcount_loc
In reply to Sami TolvanenQuoted 16 lines · Sami Tolvanen
Quoted 9 lines · Kees Cook
Quoted 7 lines · Sami Tolvanen
From: Peter Zijlstra <[email protected]>
Add the --mcount option for generating
__mcount_locsections needed for dynamic ftrace. Using this pass requires the kernel to be compiled with -mfentry andCC_USING_NOP_MCOUNTto be defined inMakefile.Quoted 5 lines
Quoted 2 lines
Hmm, I'm not sure why this hasn't gotten picked up yet. Is this expected to go through -tip or something else?
Quoted 7 lines
Note that I picked up this patch from Peter's original email, to which I included a link in the commit message, but it wasn't officially submitted as a patch. However, the previous discussion seems to have died, so I included the patch in this series, as it cleanly solves the problem of whitelisting non-call references to
__fentry__. I was hoping for Peter and Steven to comment on how they prefer to proceed here.
Right; so I'm obviously fine with this patch and I suppose I can pick it (and the next) into tip/objtool/core, provided Steve is okay with this approach.
Re: [PATCH v2 05/28] objtool: Add a pass for generating __mcount_loc
Quoted 25 lines · On Fri, Sep 04, 2020 at 11:31:04AM +0200, [email protected] wrote:
Quoted 16 lines · Sami Tolvanen
Quoted 9 lines · Kees Cook
Quoted 7 lines · Sami Tolvanen
From: Peter Zijlstra <[email protected]>
Add the --mcount option for generating
__mcount_locsections needed for dynamic ftrace. Using this pass requires the kernel to be compiled with -mfentry andCC_USING_NOP_MCOUNTto be defined inMakefile.Quoted 5 lines
Quoted 2 lines
Hmm, I'm not sure why this hasn't gotten picked up yet. Is this expected to go through -tip or something else?
Quoted 7 lines
Note that I picked up this patch from Peter's original email, to which I included a link in the commit message, but it wasn't officially submitted as a patch. However, the previous discussion seems to have died, so I included the patch in this series, as it cleanly solves the problem of whitelisting non-call references to
__fentry__. I was hoping for Peter and Steven to comment on how they prefer to proceed here.
Quoted 3 lines
Right; so I'm obviously fine with this patch and I suppose I can pick it (and the next) into tip/objtool/core, provided Steve is okay with this approach.
Hello Steven-of-the-future-after-4000-emails![1] ;)
Getting your Ack on this would be very welcome, and would unblock a portion of this series.
Thanks! :)
[1] https://twitter.com/srostedt/status/1303697650592755712
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 6/28 objtool: Don't autodetect vmlinux.o
In reply to Sami TolvanenWith LTO, we run objtool on vmlinux.o, but don't want noinstr validation. This change requires --vmlinux to be passed to objtool explicitly.
--- scripts/link-vmlinux.sh | 2 +- tools/objtool/builtin-check.c | 10 +--------- 2 files changed, 2 insertions(+), 10 deletions(-)
scripts/link-vmlinux.sh +1 -1
@@ -64,7 +64,7 @@ objtool_link() local objtoolopt; if [ -n "${CONFIG_VMLINUX_VALIDATION}" ]; then - objtoolopt="check" + objtoolopt="check --vmlinux" if [ -z "${CONFIG_FRAME_POINTER}" ]; then objtoolopt="${objtoolopt} --no-fp" fi
tools/objtool/builtin-check.c +1 -9
@@ -41,18 +41,10 @@ const struct option check_options[] = {int cmd_check (int argc,const char **argv) { -const char *objname, *s; - argc =parse_options (argc, argv, check_options, check_usage,0 );if (argc !=1 )usage_with_options (check_usage, check_options); - objname = argv[0 ]; - - s =strstr (objname,"vmlinux.o" ); -if (s && !s[9 ]) - vmlinux = true; - -return check (objname, false); +return check (argv[0 ], false); }
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 06/28] objtool: Don't autodetect vmlinux.o
Quoted 6 lines · Sami Tolvanen
With LTO, we run objtool on vmlinux.o, but don't want noinstr validation. This change requires --vmlinux to be passed to objtool explicitly.
Suggested-by Peter Zijlstra <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>
Looks right to me.
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 7/28 kbuild: add support for objtool mcount
In reply to Sami TolvanenThis change adds build support for using objtool to generate __mcount_loc sections.
--- Makefile | 38 ++++++++++++++++++++++++++++++-------- kernel/trace/Kconfig | 5 +++++ scripts/Makefile.build | 9 +++++---- 3 files changed, 40 insertions(+), 12 deletions(-)
Makefile +30 -8
@@ -859,17 +859,34 @@ ifdef CONFIG_HAVE_FENTRY ifeq ($(call cc-option-yn, -mfentry),y) CC_FLAGS_FTRACE += -mfentry CC_FLAGS_USING += -DCC_USING_FENTRY + export CC_USING_FENTRY := 1 endif endif export CC_FLAGS_FTRACE -KBUILD_CFLAGS += $(CC_FLAGS_FTRACE) $(CC_FLAGS_USING) -KBUILD_AFLAGS += $(CC_FLAGS_USING) ifdef CONFIG_DYNAMIC_FTRACE - ifdef CONFIG_HAVE_C_RECORDMCOUNT - BUILD_C_RECORDMCOUNT := y - export BUILD_C_RECORDMCOUNT - endif + ifndef CC_USING_RECORD_MCOUNT + ifndef CC_USING_PATCHABLE_FUNCTION_ENTRY + # use objtool or recordmcount to generate mcount tables + ifdef CONFIG_HAVE_OBJTOOL_MCOUNT + ifdef CC_USING_FENTRY + USE_OBJTOOL_MCOUNT := y + CC_FLAGS_USING += -DCC_USING_NOP_MCOUNT + export USE_OBJTOOL_MCOUNT + endif + endif + ifndef USE_OBJTOOL_MCOUNT + USE_RECORDMCOUNT := y + export USE_RECORDMCOUNT + ifdef CONFIG_HAVE_C_RECORDMCOUNT + BUILD_C_RECORDMCOUNT := y + export BUILD_C_RECORDMCOUNT + endif + endif + endif + endif endif +KBUILD_CFLAGS += $(CC_FLAGS_FTRACE) $(CC_FLAGS_USING) +KBUILD_AFLAGS += $(CC_FLAGS_USING) endif # We trigger additional mismatches with less inlining
@@ -1218,11 +1235,16 @@ uapi-asm-generic: PHONY += prepare-objtool prepare-resolve_btfids prepare-objtool: $(objtool_target) ifeq ($(SKIP_STACK_VALIDATION),1) +objtool-lib-prompt := "please install libelf-dev, libelf-devel or elfutils-libelf-devel" +ifdef USE_OBJTOOL_MCOUNT + @echo "error: Cannot generate __mcount_loc for CONFIG_DYNAMIC_FTRACE=y, $(objtool-lib-prompt)" >&2 + @false +endif ifdef CONFIG_UNWINDER_ORC - @echo "error: Cannot generate ORC metadata for CONFIG_UNWINDER_ORC=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel" >&2 + @echo "error: Cannot generate ORC metadata for CONFIG_UNWINDER_ORC=y, $(objtool-lib-prompt)" >&2 @false else - @echo "warning: Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel" >&2 + @echo "warning: Cannot use CONFIG_STACK_VALIDATION=y, $(objtool-lib-prompt)" >&2 endif endif
kernel/trace/Kconfig +5 -0
@@ -56,6 +56,11 @@ config HAVE_C_RECORDMCOUNT help C version of recordmcount available? +config HAVE_OBJTOOL_MCOUNT + bool + help + Arch supports objtool --mcount + config TRACER_MAX_TRACE bool
scripts/Makefile.build +5 -4
@@ -178,8 +178,7 @@ cmd_modversions_c = \ fi endif -ifdef CONFIG_FTRACE_MCOUNT_RECORD -ifndef CC_USING_RECORD_MCOUNT +ifdef USE_RECORDMCOUNT # compiler will not generate __mcount_loc use recordmcount or recordmcount.pl ifdef BUILD_C_RECORDMCOUNT ifeq ("$(origin RECORDMCOUNT_WARN)", "command line")
@@ -206,8 +205,7 @@ recordmcount_source := $(srctree)/scripts/recordmcount.pl endif # BUILD_C_RECORDMCOUNT cmd_record_mcount = $(if $(findstring $(strip $(CC_FLAGS_FTRACE)),$(_c_flags)), \ $(sub_cmd_record_mcount)) -endif # CC_USING_RECORD_MCOUNT -endif # CONFIG_FTRACE_MCOUNT_RECORD +endif # USE_RECORDMCOUNT ifdef CONFIG_STACK_VALIDATION ifneq ($(SKIP_STACK_VALIDATION),1)
@@ -230,6 +228,9 @@ endif ifdef CONFIG_X86_SMAP objtool_args += --uaccess endif +ifdef USE_OBJTOOL_MCOUNT + objtool_args += --mcount +endif # 'OBJECT_FILES_NON_STANDARD := y': skip objtool checking for a directory # 'OBJECT_FILES_NON_STANDARD_foo.o := 'y': skip objtool checking for a file
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 07/28] kbuild: add support for objtool mcount
Quoted 4 lines · Sami Tolvanen' via Clang Built Linux
This change adds build support for using objtool to generate
__mcount_locsections.Signed-off-by Sami Tolvanen <[email protected]>
Looks right to me. (There is probably an argument to be made to do all of the tooling detection in the Kconfig, but that's a larger issues and orthogonal to this fix, IMO.)
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 8/28 x86, build: use objtool mcount
In reply to Sami TolvanenSelect HAVE_OBJTOOL_MCOUNT if STACK_VALIDATION is selected to use objtool to generate __mcount_loc sections for dynamic ftrace with Clang and gcc <5.
--- arch/x86/Kconfig | 1 + 1 file changed, 1 insertion(+)
arch/x86/Kconfig +1 -0
@@ -163,6 +163,7 @@ config X86 select HAVE_CMPXCHG_LOCAL select HAVE_CONTEXT_TRACKING if X86_64 select HAVE_C_RECORDMCOUNT + select HAVE_OBJTOOL_MCOUNT if STACK_VALIDATION select HAVE_DEBUG_KMEMLEAK select HAVE_DMA_CONTIGUOUS select HAVE_DYNAMIC_FTRACE
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 08/28] x86, build: use objtool mcount
Quoted 5 lines · Sami Tolvanen
Select
HAVE_OBJTOOL_MCOUNTifSTACK_VALIDATIONis selected to use objtool to generate__mcount_locsections for dynamic ftrace with Clang and gcc <5.Signed-off-by Sami Tolvanen <[email protected]>
Am I right to understand that this fixes mcount for Clang generally (i.e. it's not _strictly_ related to LTO, though LTO depends on this change)? And does this mean mcount was working for gcc < 5?
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 08/28] x86, build: use objtool mcount
Quoted 11 lines · Kees Cook
Quoted 5 lines · Sami Tolvanen
Select
HAVE_OBJTOOL_MCOUNTifSTACK_VALIDATIONis selected to use objtool to generate__mcount_locsections for dynamic ftrace with Clang and gcc <5.Signed-off-by Sami Tolvanen <[email protected]>Am I right to understand that this fixes mcount for Clang generally (i.e. it's not _strictly_ related to LTO, though LTO depends on this change)?
No, this works fine with Clang when LTO is disabled, because recordmcount ignores files named "ftrace.o". However, with LTO, we process vmlinux.o instead, so we need a different method of ignoring __fentry__ relocations that are not calls.
In v1, I used a function attribute to whitelist functions that refer to __fentry__, but as Peter pointed out back then, objtool already knows where the call sites are, so using it to generate __mcount_loc is cleaner.
Quoted 1 line
And does this mean mcount was working for gcc < 5?
Yes. I should have been clearer in the commit message. The reason I mentioned gcc <5 is that later gcc versions support -mrecord-mcount, which means they don't need an external tool for generating __mcount_loc anymore.
Sami
Sami Tolvanen
maintainerPATCH v2 9/28 kbuild: add support for Clang LTO
In reply to Sami TolvanenThis change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The Kconfig option CONFIG_LTO_CLANG is implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must select ARCH_SUPPORTS_LTO_CLANG and support:
- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.
While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory. CONFIG_THINLTO enables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selects ARCH_SUPPORTS_THINLTO:
https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1
Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the CONFIG_LTO option, and LTO can be disabled for specific files by filtering out CC_FLAGS_LTO.
Note that support for DYNAMIC_FTRACE and MODVERSIONS are added in follow-up patches.
--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)
Makefile +17 -1
@@ -909,6 +909,22 @@ KBUILD_CFLAGS += $(CC_FLAGS_SCS) export CC_FLAGS_SCS endif +ifdef CONFIG_LTO_CLANG +ifdef CONFIG_THINLTO +CC_FLAGS_LTO_CLANG := -flto=thin -fsplit-lto-unit +KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cache +else +CC_FLAGS_LTO_CLANG := -flto +endif +CC_FLAGS_LTO_CLANG += -fvisibility=default +endif + +ifdef CONFIG_LTO +CC_FLAGS_LTO := $(CC_FLAGS_LTO_CLANG) +KBUILD_CFLAGS += $(CC_FLAGS_LTO) +export CC_FLAGS_LTO +endif + ifdef CONFIG_DEBUG_FORCE_FUNCTION_ALIGN_32B KBUILD_CFLAGS += -falign-functions=32 endif
@@ -1499,7 +1515,7 @@ MRPROPER_FILES += include/config include/generated \ *.spec # Directories & files removed with 'make distclean' -DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS +DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS .thinlto-cache # clean - Delete most, but leave enough to build external modules #
arch/Kconfig +68 -0
74 lines not on this page · raw message
include/asm-generic/vmlinux.lds.h +7 -4
@@ -89,15 +89,18 @@* .data. We don't want to pull in .data..other sections, which Linux * has defined. Same for text and bss. * +* With LTO_CLANG, the linker also splits sections by default, so we need +* these macros to combine the sections during the final link. +* * RODATA_MAIN is not used because existing code already defines .rodata.x * sections to be brought in with rodata. */ -#ifdef CONFIG_LD_DEAD_CODE_DATA_ELIMINATION +#if defined(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION ) || defined(CONFIG_LTO_CLANG )#define TEXT_MAIN .text .text.[0-9a-zA-Z_]* -#define DATA_MAIN .data .data.[0-9a-zA-Z_]* .data..LPBX* +#define DATA_MAIN .data .data.[0-9a-zA-Z_]* .data..L* .data..compoundliteral*#define SDATA_MAIN .sdata .sdata.[0-9a-zA-Z_]* -#define RODATA_MAIN .rodata .rodata.[0-9a-zA-Z_]* -#define BSS_MAIN .bss .bss.[0-9a-zA-Z_]* +#define RODATA_MAIN .rodata .rodata.[0-9a-zA-Z_]* .rodata..L* +#define BSS_MAIN .bss .bss.[0-9a-zA-Z_]* .bss..compoundliteral*#define SBSS_MAIN .sbss .sbss.[0-9a-zA-Z_]*#else #define TEXT_MAIN .text
scripts/Makefile.build +8 -1
@@ -111,7 +111,7 @@ endif # --------------------------------------------------------------------------- quiet_cmd_cc_s_c = CC $(quiet_modtag) $@ - cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS), $(c_flags)) $(DISABLE_LTO) -fverbose-asm -S -o $@ $< + cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS) $(CC_FLAGS_LTO), $(c_flags)) -fverbose-asm -S -o $@ $< $(obj)/%.s: $(src)/%.c FORCE $(call if_changed_dep,cc_s_c)
@@ -428,8 +428,15 @@ $(obj)/lib.a: $(lib-y) FORCE # Do not replace $(filter %.o,^) with $(real-prereqs). When a single object # module is turned into a multi object module, $^ will contain header file # dependencies recorded in the .*.cmd file. +ifdef CONFIG_LTO_CLANG +quiet_cmd_link_multi-m = AR [M] $@ +cmd_link_multi-m = \ + rm -f $@; \ + $(AR) rcsTP$(KBUILD_ARFLAGS) $@ $(filter %.o,$^) +else quiet_cmd_link_multi-m = LD [M] $@ cmd_link_multi-m = $(LD) $(ld_flags) -r -o $@ $(filter %.o,$^) +endif $(multi-used-m): FORCE $(call if_changed,link_multi-m)
scripts/Makefile.modfinal +8 -1
@@ -6,6 +6,7 @@ PHONY := __modfinal __modfinal: +include $(objtree)/include/config/auto.conf include $(srctree)/scripts/Kbuild.include # for c_flags
@@ -29,6 +30,12 @@ quiet_cmd_cc_o_c = CC [M] $@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink) +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to +# avoid a second slow LTO link +prelink-ext := .lto +endif + quiet_cmd_ld_ko_o = LD [M] $@ cmd_ld_ko_o = \ $(LD) -r $(KBUILD_LDFLAGS) \
@@ -37,7 +44,7 @@ quiet_cmd_ld_ko_o = LD [M] $@ -o $@ $(filter %.o, $^); \ $(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true) -$(modules): %.ko: %.o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(modules): %.ko: %$(prelink-ext).o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(call if_changed,ld_ko_o) targets += $(modules) $(modules:.ko=.mod.o)
scripts/Makefile.modpost +22 -2
@@ -102,12 +102,32 @@ $(input-symdump): @echo >&2 'WARNING: Symbol version dump "$@" is missing.' @echo >&2 ' Modules may not have dependencies or modversions.' +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, .o files might be LLVM bitcode, so we need to run +# LTO to compile them into native code before running modpost +prelink-ext = .lto + +quiet_cmd_cc_lto_link_modules = LTO [M] $@ +cmd_cc_lto_link_modules = \ + $(LD) $(ld_flags) -r -o $@ \ + --whole-archive $(filter-out FORCE,$^) + +%.lto.o: %.o FORCE + $(call if_changed,cc_lto_link_modules) + +PHONY += FORCE +FORCE: + +endif + +modules := $(sort $(shell cat $(MODORDER))) + # Read out modules.order to pass in modpost. # Otherwise, allmodconfig would fail with "Argument list too long". quiet_cmd_modpost = MODPOST $@ - cmd_modpost = sed 's/ko$$/o/' $< | $(MODPOST) -T - + cmd_modpost = sed 's/\.ko$$/$(prelink-ext)\.o/' $< | $(MODPOST) -T - -$(output-symdump): $(MODORDER) $(input-symdump) FORCE +$(output-symdump): $(MODORDER) $(input-symdump) $(modules:.ko=$(prelink-ext).o) FORCE $(call if_changed,modpost) targets += $(output-symdump)
scripts/link-vmlinux.sh +24 -8
@@ -56,6 +56,14 @@ modpost_link() ${KBUILD_VMLINUX_LIBS} \ --end-group" + if [ -n "${CONFIG_LTO_CLANG}" ]; then + # This might take a while, so indicate that we're doing + # an LTO link + info LTO ${1} + else + info LD ${1} + fi + ${LD} ${KBUILD_LDFLAGS} -r -o ${1} ${objects} }
@@ -103,13 +111,22 @@ vmlinux_link() fi if [ "${SRCARCH}" != "um" ]; then - objects="--whole-archive \ - ${KBUILD_VMLINUX_OBJS} \ - --no-whole-archive \ - --start-group \ - ${KBUILD_VMLINUX_LIBS} \ - --end-group \ - ${@}" + if [ -n "${CONFIG_LTO_CLANG}" ]; then + # Use vmlinux.o instead of performing the slow LTO + # link again. + objects="--whole-archive \ + vmlinux.o \ + --no-whole-archive \ + ${@}" + else + objects="--whole-archive \ + ${KBUILD_VMLINUX_OBJS} \ + --no-whole-archive \ + --start-group \ + ${KBUILD_VMLINUX_LIBS} \ + --end-group \ + ${@}" + fi ${LD} ${KBUILD_LDFLAGS} ${LDFLAGS_vmlinux} \ ${strip_debug#-Wl,} \
@@ -274,7 +291,6 @@ fi; ${MAKE} -f "${srctree}/scripts/Makefile.build" obj=init need-builtin=1 #link vmlinux.o -info LD vmlinux.o modpost_link vmlinux.o objtool_link vmlinux.o
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 09/28] kbuild: add support for Clang LTO
Quoted 35 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
Quoted 8 lines
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>
I remain crazy excited about being able to use this in upstream. :)
The only suggestion I have here, if it might help with clarity, would be to remove DISABLE_LTO globally as a separate patch, since it's entirely unused in the kernel right now. This series removes it as it goes, which I think is fine, but it might cause some reviewers to ponder "what's this DISABLE_LTO thing? Don't we need that?" without realizing currently unused in the kernel.
I'm glad to see the general CONFIG_LTO, as I think it should be easy for GCC LTO support to get added when someone steps up to do it. The bulk of the changed needed to support GCC LTO are part of this series already, since the build problems involving non-ELF .o files and init ordering are shared by Clang and GCC AFAICT.
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 09/28] kbuild: add support for Clang LTO
Quoted 45 lines · Kees Cook
Quoted 35 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
Quoted 8 lines
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>
Quoted 8 lines
I remain crazy excited about being able to use this in upstream. :)
The only suggestion I have here, if it might help with clarity, would be to remove
DISABLE_LTOglobally as a separate patch, since it's entirely unused in the kernel right now. This series removes it as it goes, which I think is fine, but it might cause some reviewers to ponder "what's thisDISABLE_LTOthing? Don't we need that?" without realizing currently unused in the kernel.
Sure, that makes sense. I'll add a patch to remove DISABLE_LTO treewide in v3.
Sami
Re: [PATCH v2 09/28] kbuild: add support for Clang LTO
In reply to Sami TolvanenQuoted 11 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled.
What is the reason for doing this in a choice? To turn off LTO_CLANG for compile-testing?
I would rather want to give LTO_CLANG more chances to be enabled/tested.
Quoted 49 lines
To use LTO, the architecture
must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)Makefile +0
-0
Makefile KBUILD_CFLAGS += $(CC_FLAGS_SCS) · line 915
Quoted 7 lines
Makefile +4
-0@@ -909,6 +909,22 @@ KBUILD_CFLAGS += $(CC_FLAGS_SCS) export CC_FLAGS_SCS endif +ifdef CONFIG_LTO_CLANG +ifdef CONFIG_THINLTO +CC_FLAGS_LTO_CLANG := -flto=thin -fsplit-lto-unit +KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cache
I think this would break external module builds because it would create cache files in the kernel source tree.
External module builds should never ever touch the kernel tree, which is usually located under the read-only /usr/src/ in distros.
.thinlto-cache should be created in the module tree when it is built with M=.
Quoted 16 lines
Makefile +12
-0+else +CC_FLAGS_LTO_CLANG := -flto +endif +CC_FLAGS_LTO_CLANG += -fvisibility=default +endif + +ifdef CONFIG_LTO +CC_FLAGS_LTO := $(CC_FLAGS_LTO_CLANG) +KBUILD_CFLAGS += $(CC_FLAGS_LTO) +export CC_FLAGS_LTO +endif + ifdef CONFIG_DEBUG_FORCE_FUNCTION_ALIGN_32B KBUILD_CFLAGS += -falign-functions=32 endif
Makefile MRPROPER_FILES += include/config include/generated \ · line 1518
Quoted 5 lines
Makefile +1
-1@@ -1499,7 +1515,7 @@ MRPROPER_FILES += include/config include/generated \ *.spec # Directories & files removed with 'make distclean' -DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS +DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS .thinlto-cache
This was suggested in v1, but I could not understand why doing this in distclean was appropriate.
Is keeping cache files of kernel objects useful for external module builds?
Also, please clean up .thinlto-cache for external module builds.
Quoted 269 lines
Makefile +0
-0# clean - Delete most, but leave enough to build external modules #arch/Kconfig +68
-0@@ -552,6 +552,74 @@ config SHADOW_CALL_STACK reading and writing arbitrary memory may be able to locate them and hijack control flow by modifying the stacks. +config LTO + bool + +config ARCH_SUPPORTS_LTO_CLANG + bool + help + An architecture should select this option if it supports: + - compiling with Clang, + - compiling inline assembly with Clang's integrated assembler, + - and linking with LLD. + +config ARCH_SUPPORTS_THINLTO + bool + help + An architecture should select this option if it supports Clang's + ThinLTO. + +config THINLTO + bool "Clang ThinLTO" + depends on LTO_CLANG && ARCH_SUPPORTS_THINLTO + default y + help + This option enables Clang's ThinLTO, which allows for parallel + optimization and faster incremental compiles. More information + can be found from Clang's documentation: + + https://clang.llvm.org/docs/ThinLTO.html + +choice + prompt "Link Time Optimization (LTO)" + default LTO_NONE + help + This option enables Link Time Optimization (LTO), which allows the + compiler to optimize binaries globally. + + If unsure, select LTO_NONE. + +config LTO_NONE + bool "None" + +config LTO_CLANG + bool "Clang's Link Time Optimization (EXPERIMENTAL)" + # Clang >= 11: https://github.com/ClangBuiltLinux/linux/issues/510 + depends on CC_IS_CLANG && CLANG_VERSION >= 110000 && LD_IS_LLD + depends on $(success,$(NM) --help | head -n 1 | grep -qi llvm) + depends on $(success,$(AR) --help | head -n 1 | grep -qi llvm) + depends on ARCH_SUPPORTS_LTO_CLANG + depends on !FTRACE_MCOUNT_RECORD + depends on !KASAN + depends on !GCOV_KERNEL + depends on !MODVERSIONS + select LTO + help + This option enables Clang's Link Time Optimization (LTO), which + allows the compiler to optimize the kernel globally. If you enable + this option, the compiler generates LLVM bitcode instead of ELF + object files, and the actual compilation from bitcode happens at + the LTO link step, which may take several minutes depending on the + kernel configuration. More information can be found from LLVM's + documentation: + + https://llvm.org/docs/LinkTimeOptimization.html + + To select this option, you also need to use LLVM tools to handle + the bitcode by passing LLVM=1 to make. + +endchoice + config HAVE_ARCH_WITHIN_STACK_FRAMES bool helpinclude/asm-generic/vmlinux.lds.h +7
-4@@ -89,15 +89,18 @@* .data. We don't want to pull in .data..other sections, which Linux * has defined. Same for text and bss. * +* With LTO_CLANG, the linker also splits sections by default, so we need +* these macros to combine the sections during the final link. +* * RODATA_MAIN is not used because existing code already defines .rodata.x * sections to be brought in with rodata. */ -#ifdef CONFIG_LD_DEAD_CODE_DATA_ELIMINATION +#if defined(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION ) || defined(CONFIG_LTO_CLANG )#define TEXT_MAIN .text .text.[0-9a-zA-Z_]* -#define DATA_MAIN .data .data.[0-9a-zA-Z_]* .data..LPBX* +#define DATA_MAIN .data .data.[0-9a-zA-Z_]* .data..L* .data..compoundliteral*#define SDATA_MAIN .sdata .sdata.[0-9a-zA-Z_]* -#define RODATA_MAIN .rodata .rodata.[0-9a-zA-Z_]* -#define BSS_MAIN .bss .bss.[0-9a-zA-Z_]* +#define RODATA_MAIN .rodata .rodata.[0-9a-zA-Z_]* .rodata..L* +#define BSS_MAIN .bss .bss.[0-9a-zA-Z_]* .bss..compoundliteral*#define SBSS_MAIN .sbss .sbss.[0-9a-zA-Z_]*#else #define TEXT_MAIN .textscripts/Makefile.build +8
-1@@ -111,7 +111,7 @@ endif # --------------------------------------------------------------------------- quiet_cmd_cc_s_c = CC $(quiet_modtag) $@ - cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS), $(c_flags)) $(DISABLE_LTO) -fverbose-asm -S -o $@ $< + cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS) $(CC_FLAGS_LTO), $(c_flags)) -fverbose-asm -S -o $@ $< $(obj)/%.s: $(src)/%.c FORCE $(call if_changed_dep,cc_s_c)@@ -428,8 +428,15 @@ $(obj)/lib.a: $(lib-y) FORCE # Do not replace $(filter %.o,^) with $(real-prereqs). When a single object # module is turned into a multi object module, $^ will contain header file # dependencies recorded in the .*.cmd file. +ifdef CONFIG_LTO_CLANG +quiet_cmd_link_multi-m = AR [M] $@ +cmd_link_multi-m = \ + rm -f $@; \ + $(AR) rcsTP$(KBUILD_ARFLAGS) $@ $(filter %.o,$^) +else quiet_cmd_link_multi-m = LD [M] $@ cmd_link_multi-m = $(LD) $(ld_flags) -r -o $@ $(filter %.o,$^) +endif $(multi-used-m): FORCE $(call if_changed,link_multi-m)scripts/Makefile.modfinal +8
-1@@ -6,6 +6,7 @@ PHONY := __modfinal __modfinal: +include $(objtree)/include/config/auto.conf include $(srctree)/scripts/Kbuild.include # for c_flags@@ -29,6 +30,12 @@ quiet_cmd_cc_o_c = CC [M] $@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink) +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to +# avoid a second slow LTO link +prelink-ext := .lto +endif + quiet_cmd_ld_ko_o = LD [M] $@ cmd_ld_ko_o = \ $(LD) -r $(KBUILD_LDFLAGS) \@@ -37,7 +44,7 @@ quiet_cmd_ld_ko_o = LD [M] $@ -o $@ $(filter %.o, $^); \ $(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true) -$(modules): %.ko: %.o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(modules): %.ko: %$(prelink-ext).o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(call if_changed,ld_ko_o) targets += $(modules) $(modules:.ko=.mod.o)scripts/Makefile.modpost +22
-2@@ -102,12 +102,32 @@ $(input-symdump): @echo >&2 'WARNING: Symbol version dump "$@" is missing.' @echo >&2 ' Modules may not have dependencies or modversions.' +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, .o files might be LLVM bitcode, so we need to run +# LTO to compile them into native code before running modpost +prelink-ext = .lto + +quiet_cmd_cc_lto_link_modules = LTO [M] $@ +cmd_cc_lto_link_modules = \ + $(LD) $(ld_flags) -r -o $@ \ + --whole-archive $(filter-out FORCE,$^) + +%.lto.o: %.o FORCE + $(call if_changed,cc_lto_link_modules) + +PHONY += FORCE +FORCE: + +endif + +modules := $(sort $(shell cat $(MODORDER))) + # Read out modules.order to pass in modpost. # Otherwise, allmodconfig would fail with "Argument list too long". quiet_cmd_modpost = MODPOST $@ - cmd_modpost = sed 's/ko$$/o/' $< | $(MODPOST) -T - + cmd_modpost = sed 's/\.ko$$/$(prelink-ext)\.o/' $< | $(MODPOST) -T - -$(output-symdump): $(MODORDER) $(input-symdump) FORCE +$(output-symdump): $(MODORDER) $(input-symdump) $(modules:.ko=$(prelink-ext).o) FORCE $(call if_changed,modpost) targets += $(output-symdump)scripts/link-vmlinux.sh +24
-9@@ -56,6 +56,14 @@ modpost_link() ${KBUILD_VMLINUX_LIBS} \ --end-group" + if [ -n "${CONFIG_LTO_CLANG}" ]; then + # This might take a while, so indicate that we're doing + # an LTO link + info LTO ${1} + else + info LD ${1} + fi + ${LD} ${KBUILD_LDFLAGS} -r -o ${1} ${objects} }@@ -103,13 +111,22 @@ vmlinux_link() fi if [ "${SRCARCH}" != "um" ]; then - objects="--whole-archive \ - ${KBUILD_VMLINUX_OBJS} \ - --no-whole-archive \ - --start-group \ - ${KBUILD_VMLINUX_LIBS} \ - --end-group \ - ${@}" + if [ -n "${CONFIG_LTO_CLANG}" ]; then + # Use vmlinux.o instead of performing the slow LTO + # link again. + objects="--whole-archive \ + vmlinux.o \ + --no-whole-archive \ + ${@}" + else + objects="--whole-archive \ + ${KBUILD_VMLINUX_OBJS} \ + --no-whole-archive \ + --start-group \ + ${KBUILD_VMLINUX_LIBS} \ + --end-group \ + ${@}" + fi ${LD} ${KBUILD_LDFLAGS} ${LDFLAGS_vmlinux} \ ${strip_debug#-Wl,} \@@ -274,7 +291,6 @@ fi; ${MAKE} -f "${srctree}/scripts/Makefile.build" obj=init need-builtin=1 #link vmlinux.o -info LD vmlinux.o modpost_link vmlinux.o objtool_link vmlinux.o --
Quoted 2 lines
2.28.0.402.g5ffc5be6b7-goog
--
Best Regards
Masahiro Yamada
Sami Tolvanen
maintainerRe: [PATCH v2 09/28] kbuild: add support for Clang LTO
Quoted 10 lines · Masahiro Yamada
Quoted 9 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
Quoted 8 lines
Quoted 2 lines
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled.What is the reason for doing this in a choice? To turn off
LTO_CLANGfor compile-testing?I would rather want to give
LTO_CLANGmore chances to be enabled/tested.
It's a choice to prevent LTO from being enabled by default with allyesconfig and allmodconfig. It would take hours to build these even on a fast computer, and probably days on older hardware.
Quoted 10 lines
Makefile KBUILD_CFLAGS += $(CC_FLAGS_SCS) · line 915
Quoted 4 lines
Makefile +4
-0+ifdef CONFIG_LTO_CLANG +ifdef CONFIG_THINLTO +CC_FLAGS_LTO_CLANG := -flto=thin -fsplit-lto-unit +KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cacheI think this would break external module builds because it would create cache files in the kernel source tree.
Quoted 7 lines
External module builds should never ever touch the kernel tree, which is usually located under the read-only
/usr/src/in distros..thinlto-cache should be created in the module tree when it is built with M=.
Thanks for pointing this out, I'll fix the path in v3.
Quoted 11 lines
Makefile MRPROPER_FILES += include/config include/generated \ · line 1518
Quoted 3 lines
# Directories & files removed with 'make distclean'
Makefile +1
-1-DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS +DISTCLEAN_FILES += tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS .thinlto-cacheThis was suggested in v1, but I could not understand why doing this in distclean was appropriate.
Is keeping cache files of kernel objects useful for external module builds?
No, the cache only speeds up incremental kernel builds.
Quoted 1 line
Also, please clean up .thinlto-cache for external module builds.
Ack.
Sami
Re: [PATCH v2 09/28] kbuild: add support for Clang LTO
In reply to Sami TolvanenQuoted 64 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)Makefile +2
-0@@ -909,6 +909,22 @@ KBUILD_CFLAGS += $(CC_FLAGS_SCS) export CC_FLAGS_SCS endif +ifdef CONFIG_LTO_CLANG +ifdef CONFIG_THINLTO
Makefile KBUILD_CFLAGS += $(CC_FLAGS_SCS) · line 923
Quoted 10 lines
Makefile +10
-0+CC_FLAGS_LTO_CLANG := -flto=thin -fsplit-lto-unit +KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cache +else +CC_FLAGS_LTO_CLANG := -flto +endif +CC_FLAGS_LTO_CLANG += -fvisibility=default +endif + +ifdef CONFIG_LTO +CC_FLAGS_LTO := $(CC_FLAGS_LTO_CLANG)
$(CC_FLAGS_LTO_CLANG) is not used elsewhere.
Why didn't you add the flags to CC_FLAGS_LTO
directly?
Will it be useful if LTO_GCC is supported ?
Quoted 3 lines
Makefile +3
-0+KBUILD_CFLAGS += $(CC_FLAGS_LTO) +export CC_FLAGS_LTO +endif
Signature · 2 lines
Best Regards Masahiro Yamada
Sami Tolvanen
maintainerRe: [PATCH v2 09/28] kbuild: add support for Clang LTO
Quoted 79 lines · Masahiro Yamada
Quoted 64 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)Makefile +2
-0@@ -909,6 +909,22 @@ KBUILD_CFLAGS += $(CC_FLAGS_SCS) export CC_FLAGS_SCS endif +ifdef CONFIG_LTO_CLANG +ifdef CONFIG_THINLTOMakefile KBUILD_CFLAGS += $(CC_FLAGS_SCS) · line 923
Quoted 10 lines
Makefile +10
-0+CC_FLAGS_LTO_CLANG := -flto=thin -fsplit-lto-unit +KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cache +else +CC_FLAGS_LTO_CLANG := -flto +endif +CC_FLAGS_LTO_CLANG += -fvisibility=default +endif + +ifdef CONFIG_LTO +CC_FLAGS_LTO := $(CC_FLAGS_LTO_CLANG)$(CC_FLAGS_LTO_CLANG) is not used elsewhere.
Quoted 4 lines
Why didn't you add the flags to
CC_FLAGS_LTO
directly?Will it be useful if
LTO_GCCis supported ?
The idea was to allow compiler-specific LTO flags to be filtered out separately if needed, but you're right, this is not really necessary right now. I'll drop CC_FLAGS_LTO_CLANG in v3.
Sami
Re: [PATCH v2 09/28] kbuild: add support for Clang LTO
In reply to Sami TolvanenQuoted 71 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)#define
TEXT_MAIN.textscripts/Makefile.build +1
-1@@ -111,7 +111,7 @@ endif # --------------------------------------------------------------------------- quiet_cmd_cc_s_c = CC $(quiet_modtag) $@ - cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS), $(c_flags)) $(DISABLE_LTO) -fverbose-asm -S -o $@ $< + cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS) $(CC_FLAGS_LTO), $(c_flags)) -fverbose-asm -S -o $@ $< $(obj)/%.s: $(src)/%.c FORCE $(call if_changed_dep,cc_s_c)
scripts/Makefile.build $(obj)/lib.a: $(lib-y) FORCE · line 435
Quoted 8 lines
scripts/Makefile.build +5
-0@@ -428,8 +428,15 @@ $(obj)/lib.a: $(lib-y) FORCE # Do not replace $(filter %.o,^) with $(real-prereqs). When a single object # module is turned into a multi object module, $^ will contain header file # dependencies recorded in the .*.cmd file. +ifdef CONFIG_LTO_CLANG +quiet_cmd_link_multi-m = AR [M] $@ +cmd_link_multi-m = \ + rm -f $@; \ + $(AR) rcsTP$(KBUILD_ARFLAGS) $@ $(filter %.o,$^)
KBUILD_ARFLAGS no longer exists in the mainline.
(commit 13dc8c029cabf52ba95f60c56eb104d4d95d5889)
Quoted 46 lines
scripts/Makefile.build +2
-0+else quiet_cmd_link_multi-m = LD [M] $@ cmd_link_multi-m = $(LD) $(ld_flags) -r -o $@ $(filter %.o,$^) +endif $(multi-used-m): FORCE $(call if_changed,link_multi-m)scripts/Makefile.modfinal +8
-1@@ -6,6 +6,7 @@ PHONY := __modfinal __modfinal: +include $(objtree)/include/config/auto.conf include $(srctree)/scripts/Kbuild.include # for c_flags@@ -29,6 +30,12 @@ quiet_cmd_cc_o_c = CC [M] $@ ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink) +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to +# avoid a second slow LTO link +prelink-ext := .lto +endif + quiet_cmd_ld_ko_o = LD [M] $@ cmd_ld_ko_o = \ $(LD) -r $(KBUILD_LDFLAGS) \@@ -37,7 +44,7 @@ quiet_cmd_ld_ko_o = LD [M] $@ -o $@ $(filter %.o, $^); \ $(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true) -$(modules): %.ko: %.o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(modules): %.ko: %$(prelink-ext).o %.mod.o $(KBUILD_LDS_MODULE) FORCE +$(call if_changed,ld_ko_o) targets += $(modules) $(modules:.ko=.mod.o)scripts/Makefile.modpost +0
-0
scripts/Makefile.modpost $(input-symdump): · line 106
Quoted 5 lines
scripts/Makefile.modpost +2
-0@@ -102,12 +102,32 @@ $(input-symdump): @echo >&2 'WARNING: Symbol version dump "$@" is missing.' @echo >&2 ' Modules may not have dependencies or modversions.' +ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, .o files might be LLVM bitcode,
or, .o files might be even thin archives.
For example,
$ file net/ipv6/netfilter/nf_defrag_ipv6.o net/ipv6/netfilter/nf_defrag_ipv6.o: thin archive with 6 symbol entries
Now we have 3 possibilities for .o files:
- ELF (real .o)
- LLVM bitcode (.bc)
- Thin archive (.a)
Let me discuss how to proceed with this...
--
Best Regards
Masahiro Yamada
Sami Tolvanen
maintainerRe: [PATCH v2 09/28] kbuild: add support for Clang LTO
Quoted 69 lines · Masahiro Yamada
Quoted 68 lines · Sami Tolvanen
This change adds build system support for Clang's Link Time Optimization (LTO). With -flto, instead of ELF object files, Clang produces LLVM bitcode, which is compiled into native code at link time, allowing the final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
The
KconfigoptionCONFIG_LTO_CLANGis implemented as a choice, which defaults to LTO being disabled. To use LTO, the architecture must selectARCH_SUPPORTS_LTO_CLANGand support:- compiling with Clang,
- compiling inline assembly with Clang's integrated assembler,
- and linking with LLD.While using full LTO results in the best runtime performance, the compilation is not scalable in time or memory.
CONFIG_THINLTOenables ThinLTO, which allows parallel optimization and faster incremental builds. ThinLTO is used by default if the architecture also selectsARCH_SUPPORTS_THINLTO:https://clang.llvm.org/docs/ThinLTO.html
To enable LTO, LLVM tools must be used to handle bitcode files. The easiest way is to pass the LLVM=1 option to make:
$ make LLVM=1 defconfig $ scripts/config -e LTO_CLANG $ make LLVM=1Alternatively, at least the following LLVM tools must be used:
CC=clang LD=ld.lld AR=llvm-ar NM=llvm-nm
To prepare for LTO support with other compilers, common parts are gated behind the
CONFIG_LTOoption, and LTO can be disabled for specific files by filtering outCC_FLAGS_LTO.Note that support for
DYNAMIC_FTRACEand MODVERSIONS are added in follow-up patches.Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 18 +++++++- arch/Kconfig | 68 +++++++++++++++++++++++++++++++ include/asm-generic/vmlinux.lds.h | 11 +++-- scripts/Makefile.build | 9 +++- scripts/Makefile.modfinal | 9 +++- scripts/Makefile.modpost | 24 ++++++++++- scripts/link-vmlinux.sh | 32 +++++++++++---- 7 files changed, 154 insertions(+), 17 deletions(-)#define
TEXT_MAIN.textscripts/Makefile.build +1
-1@@ -111,7 +111,7 @@ endif # --------------------------------------------------------------------------- quiet_cmd_cc_s_c = CC $(quiet_modtag) $@ - cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS), $(c_flags)) $(DISABLE_LTO) -fverbose-asm -S -o $@ $< + cmd_cc_s_c = $(CC) $(filter-out $(DEBUG_CFLAGS) $(CC_FLAGS_LTO), $(c_flags)) -fverbose-asm -S -o $@ $<
Quoted 15 lines
scripts/Makefile.build $(obj)/lib.a: $(lib-y) FORCE · line 435
Quoted 11 lines
scripts/Makefile.build +5
-0$(obj)/%.s: $(src)/%.c FORCE $(call if_changed_dep,cc_s_c)@@ -428,8 +428,15 @@ $(obj)/lib.a: $(lib-y) FORCE # Do not replace $(filter %.o,^) with $(real-prereqs). When a single object # module is turned into a multi object module, $^ will contain header file # dependencies recorded in the .*.cmd file. +ifdef CONFIG_LTO_CLANG +quiet_cmd_link_multi-m = AR [M] $@ +cmd_link_multi-m = \ + rm -f $@; \ + $(AR) rcsTP$(KBUILD_ARFLAGS) $@ $(filter %.o,$^)
KBUILD_ARFLAGSno longer exists in the mainline.
(commit13dc8c029cabf52ba95f60c56eb104d4d95d5889)
Thanks, I'll drop this in the next version.
Quoted 4 lines
scripts/Makefile.build $(obj)/lib.a: $(lib-y) FORCE · line 437
Quoted 2 lines
scripts/Makefile.build +2
-0+ifdef CONFIG_LTO_CLANG +# With CONFIG_LTO_CLANG, .o files might be LLVM bitcode,or, .o files might be even thin archives.
Right, and with LTO the thin archive might also point to a mix of bitcode and ELF to further complicate things.
Quoted 6 lines
For example,
$ file net/ipv6/netfilter/nf_defrag_ipv6.o net/ipv6/netfilter/nf_defrag_ipv6.o: thin archive with 6 symbol entries
Quoted 8 lines
Now we have 3 possibilities for .o files:
- ELF (real .o)
- LLVM bitcode (.bc)
- Thin archive (.a)Let me discuss how to proceed with this...
Did you have something in mind to make this cleaner?
Sami
Sami Tolvanen
maintainerPATCH v2 10/28 kbuild: lto: fix module versioning
In reply to Sami TolvanenWith CONFIG_MODVERSIONS, version information is linked into each compilation unit that exports symbols. With LTO, we cannot use this method as all C code is compiled into LLVM bitcode instead. This change collects symbol versions into .symversions files and merges them in link-vmlinux.sh where they are all linked into vmlinux.o at the same time.
--- .gitignore | 1 + Makefile | 3 ++- arch/Kconfig | 1 - scripts/Makefile.build | 33 +++++++++++++++++++++++++++++++-- scripts/Makefile.modpost | 2 ++ scripts/link-vmlinux.sh | 25 ++++++++++++++++++++++++- 6 files changed, 60 insertions(+), 5 deletions(-)
.gitignore +1 -0
@@ -41,6 +41,7 @@ *.so.dbg *.su *.symtypes +*.symversions *.tab.[ch] *.tar *.xz
Makefile +2 -1
@@ -1847,7 +1847,8 @@ clean: $(clean-dirs) -o -name '.tmp_*.o.*' \ -o -name '*.c.[012]*.*' \ -o -name '*.ll' \ - -o -name '*.gcno' \) -type f -print | xargs rm -f + -o -name '*.gcno' \ + -o -name '*.*.symversions' \) -type f -print | xargs rm -f # Generate tags for editors # ---------------------------------------------------------------------------
arch/Kconfig +0 -1
@@ -602,7 +602,6 @@ config LTO_CLANG depends on !FTRACE_MCOUNT_RECORD depends on !KASAN depends on !GCOV_KERNEL - depends on !MODVERSIONS select LTO help This option enables Clang's Link Time Optimization (LTO), which
scripts/Makefile.build +31 -2
@@ -166,6 +166,15 @@ ifdef CONFIG_MODVERSIONS # the actual value of the checksum generated by genksyms # o remove .tmp_<file>.o to <file>.o +ifdef CONFIG_LTO_CLANG +# Generate .o.symversions files for each .o with exported symbols, and link these +# to the kernel and/or modules at the end. +cmd_modversions_c = \ + if $(NM) $@ 2>/dev/null | grep -q __ksymtab; then \ + $(call cmd_gensymtypes_c,$(KBUILD_SYMTYPES),$(@:.o=.symtypes)) \ + > [email protected]; \ + fi; +else cmd_modversions_c = \ if $(OBJDUMP) -h $@ | grep -q __ksymtab; then \ $(call cmd_gensymtypes_c,$(KBUILD_SYMTYPES),$(@:.o=.symtypes)) \
@@ -177,6 +186,7 @@ cmd_modversions_c = \ rm -f $(@D)/.tmp_$(@F:.o=.ver); \ fi endif +endif ifdef USE_RECORDMCOUNT # compiler will not generate __mcount_loc use recordmcount or recordmcount.pl
@@ -393,6 +403,18 @@ $(obj)/%.asn1.c $(obj)/%.asn1.h: $(src)/%.asn1 $(objtree)/scripts/asn1_compiler $(subdir-builtin): $(obj)/%/built-in.a: $(obj)/% ; $(subdir-modorder): $(obj)/%/modules.order: $(obj)/% ; +# combine symversions for later processing +quiet_cmd_update_lto_symversions = SYMVER $@ +ifeq ($(CONFIG_LTO_CLANG) $(CONFIG_MODVERSIONS),y y) + cmd_update_lto_symversions = \ + rm -f [email protected] \ + $(foreach n, $(filter-out FORCE,$^), \ + $(if $(wildcard $(n).symversions), \ + ; cat $(n).symversions >> [email protected])) +else + cmd_update_lto_symversions = echo >/dev/null +endif + # # Rule to compile a set of .o files into one .a file (without symbol table) #
@@ -400,8 +422,11 @@ $(subdir-modorder): $(obj)/%/modules.order: $(obj)/% ; quiet_cmd_ar_builtin = AR $@ cmd_ar_builtin = rm -f $@; $(AR) cDPrST $@ $(real-prereqs) +quiet_cmd_ar_and_symver = AR $@ + cmd_ar_and_symver = $(cmd_update_lto_symversions); $(cmd_ar_builtin) + $(obj)/built-in.a: $(real-obj-y) FORCE - $(call if_changed,ar_builtin) + $(call if_changed,ar_and_symver) # # Rule to create modules.order file
@@ -421,8 +446,11 @@ $(obj)/modules.order: $(obj-m) FORCE # # Rule to compile a set of .o files into one .a file (with symbol table) # +quiet_cmd_ar_lib = AR $@ + cmd_ar_lib = $(cmd_update_lto_symversions); $(cmd_ar) + $(obj)/lib.a: $(lib-y) FORCE - $(call if_changed,ar) + $(call if_changed,ar_lib) # NOTE: # Do not replace $(filter %.o,^) with $(real-prereqs). When a single object
@@ -431,6 +459,7 @@ $(obj)/lib.a: $(lib-y) FORCE ifdef CONFIG_LTO_CLANG quiet_cmd_link_multi-m = AR [M] $@ cmd_link_multi-m = \ + $(cmd_update_lto_symversions); \ rm -f $@; \ $(AR) rcsTP$(KBUILD_ARFLAGS) $@ $(filter %.o,$^) else
scripts/Makefile.modpost +2 -0
@@ -110,6 +110,8 @@ prelink-ext = .lto quiet_cmd_cc_lto_link_modules = LTO [M] $@ cmd_cc_lto_link_modules = \ $(LD) $(ld_flags) -r -o $@ \ + $(shell [ -s $(@:.lto.o=.o.symversions) ] && \ + echo -T $(@:.lto.o=.o.symversions)) \ --whole-archive $(filter-out FORCE,$^) %.lto.o: %.o FORCE
scripts/link-vmlinux.sh +24 -1
@@ -43,11 +43,28 @@ info() fi } +# If CONFIG_LTO_CLANG is selected, collect generated symbol versions into +# .tmp_symversions.lds +gen_symversions() +{ + info GEN .tmp_symversions.lds + rm -f .tmp_symversions.lds + + for a in ${KBUILD_VMLINUX_OBJS} ${KBUILD_VMLINUX_LIBS}; do + for o in $(${AR} t $a 2>/dev/null); do + if [ -f ${o}.symversions ]; then + cat ${o}.symversions >> .tmp_symversions.lds + fi + done + done +} + # Link of vmlinux.o used for section mismatch analysis # ${1} output file modpost_link() { local objects + local lds="" objects="--whole-archive \ ${KBUILD_VMLINUX_OBJS} \
@@ -57,6 +74,11 @@ modpost_link() --end-group" if [ -n "${CONFIG_LTO_CLANG}" ]; then + if [ -n "${CONFIG_MODVERSIONS}" ]; then + gen_symversions + lds="${lds} -T .tmp_symversions.lds" + fi + # This might take a while, so indicate that we're doing # an LTO link info LTO ${1}
@@ -64,7 +86,7 @@ modpost_link() info LD ${1} fi - ${LD} ${KBUILD_LDFLAGS} -r -o ${1} ${objects} + ${LD} ${KBUILD_LDFLAGS} -r -o ${1} ${lds} ${objects} } objtool_link()
@@ -242,6 +264,7 @@ cleanup() { rm -f .btf.* rm -f .tmp_System.map + rm -f .tmp_symversions.lds rm -f .tmp_vmlinux* rm -f System.map rm -f vmlinux
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 10/28] kbuild: lto: fix module versioning
Quoted 8 lines · Sami Tolvanen
With
CONFIG_MODVERSIONS, version information is linked into each compilation unit that exports symbols. With LTO, we cannot use this method as all C code is compiled into LLVM bitcode instead. This change collects symbol versions into .symversions files and merges them inlink-vmlinux.shwhere they are all linked into vmlinux.o at the same time.Signed-off-by Sami Tolvanen <[email protected]>
The only thought I have here is I wonder if this change could be made universally instead of gating on LTO? (i.e. is it noticeably slower to do it this way under non-LTO?)
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 10/28] kbuild: lto: fix module versioning
Quoted 8 lines · Kees Cook
Quoted 7 lines · Sami Tolvanen
With
CONFIG_MODVERSIONS, version information is linked into each compilation unit that exports symbols. With LTO, we cannot use this method as all C code is compiled into LLVM bitcode instead. This change collects symbol versions into .symversions files and merges them inlink-vmlinux.shwhere they are all linked into vmlinux.o at the same time.
Quoted 5 lines
Quoted 1 line
Signed-off-by Sami Tolvanen <[email protected]>The only thought I have here is I wonder if this change could be made universally instead of gating on LTO? (i.e. is it noticeably slower to do it this way under non-LTO?)
I don't think it's noticeably slower, but keeping the version information in object files when possible is cleaner, in my opinion.
Sami
Sami Tolvanen
maintainerPATCH v2 11/28 kbuild: lto: postpone objtool
In reply to Sami TolvanenWith LTO, LLVM bitcode won't be compiled into native code until modpost_link, or modfinal for modules. This change postpones calls to objtool until after these steps.
--- arch/Kconfig | 2 +- scripts/Makefile.build | 2 ++ scripts/Makefile.modfinal | 24 ++++++++++++++++++++++-- scripts/link-vmlinux.sh | 23 ++++++++++++++++++++++- 4 files changed, 47 insertions(+), 4 deletions(-)
arch/Kconfig +1 -1
@@ -599,7 +599,7 @@ config LTO_CLANG depends on $(success,$(NM) --help | head -n 1 | grep -qi llvm) depends on $(success,$(AR) --help | head -n 1 | grep -qi llvm) depends on ARCH_SUPPORTS_LTO_CLANG - depends on !FTRACE_MCOUNT_RECORD + depends on HAVE_OBJTOOL_MCOUNT || !(X86_64 && DYNAMIC_FTRACE) depends on !KASAN depends on !GCOV_KERNEL select LTO
scripts/Makefile.build +2 -0
@@ -218,6 +218,7 @@ cmd_record_mcount = $(if $(findstring $(strip $(CC_FLAGS_FTRACE)),$(_c_flags)), endif # USE_RECORDMCOUNT ifdef CONFIG_STACK_VALIDATION +ifndef CONFIG_LTO_CLANG ifneq ($(SKIP_STACK_VALIDATION),1) __objtool_obj := $(objtree)/tools/objtool/objtool
@@ -253,6 +254,7 @@ objtool_obj = $(if $(patsubst y%,, \ $(__objtool_obj)) endif # SKIP_STACK_VALIDATION +endif # CONFIG_LTO_CLANG endif # CONFIG_STACK_VALIDATION # Rebuild all objects when objtool changes, or is enabled/disabled.
scripts/Makefile.modfinal +22 -2
@@ -34,10 +34,30 @@ ifdef CONFIG_LTO_CLANG # With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to # avoid a second slow LTO link prelink-ext := .lto -endif + +# ELF processing was skipped earlier because we didn't have native code, +# so let's now process the prelinked binary before we link the module. + +ifdef CONFIG_STACK_VALIDATION +ifneq ($(SKIP_STACK_VALIDATION),1) +cmd_ld_ko_o += \ + $(objtree)/tools/objtool/objtool \ + $(if $(CONFIG_UNWINDER_ORC),orc generate,check) \ + --module \ + $(if $(CONFIG_FRAME_POINTER),,--no-fp) \ + $(if $(CONFIG_GCOV_KERNEL),--no-unreachable,) \ + $(if $(CONFIG_RETPOLINE),--retpoline,) \ + $(if $(CONFIG_X86_SMAP),--uaccess,) \ + $(if $(USE_OBJTOOL_MCOUNT),--mcount,) \ + $(@:.ko=$(prelink-ext).o); + +endif # SKIP_STACK_VALIDATION +endif # CONFIG_STACK_VALIDATION + +endif # CONFIG_LTO_CLANG quiet_cmd_ld_ko_o = LD [M] $@ - cmd_ld_ko_o = \ + cmd_ld_ko_o += \ $(LD) -r $(KBUILD_LDFLAGS) \ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ $(addprefix -T , $(KBUILD_LDS_MODULE)) \
scripts/link-vmlinux.sh +22 -1
@@ -93,8 +93,29 @@ objtool_link() { local objtoolopt; + if [ "${CONFIG_LTO_CLANG} ${CONFIG_STACK_VALIDATION}" = "y y" ]; then + # Don't perform vmlinux validation unless explicitly requested, + # but run objtool on vmlinux.o now that we have an object file. + if [ -n "${CONFIG_UNWINDER_ORC}" ]; then + objtoolopt="orc generate" + else + objtoolopt="check" + fi + + if [ -n ${USE_OBJTOOL_MCOUNT} ]; then + objtoolopt="${objtoolopt} --mcount" + fi + fi + if [ -n "${CONFIG_VMLINUX_VALIDATION}" ]; then - objtoolopt="check --vmlinux" + if [ -z "${objtoolopt}" ]; then + objtoolopt="check --vmlinux" + else + objtoolopt="${objtoolopt} --vmlinux" + fi + fi + + if [ -n "${objtoolopt}" ]; then if [ -z "${CONFIG_FRAME_POINTER}" ]; then objtoolopt="${objtoolopt} --no-fp" fi
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 11/28] kbuild: lto: postpone objtool
Quoted 5 lines · Sami Tolvanen
With LTO, LLVM bitcode won't be compiled into native code until
modpost_link, or modfinal for modules. This change postpones calls to objtool until after these steps.Signed-off-by Sami Tolvanen <[email protected]>
For a "fail fast" style of building, it makes sense to have objtool run as early as possible, so it makes sense to keep the current behavior in non-LTO mode. I do wonder, though, if there is a real benefit to having "fail fast" case. I imagine a lot of automated builds are using --keep-going with make, and actually waiting until the end to do the validation means more code will get build-tested before objtool rejects the results. *shrug*
Quoted 58 lines
--- arch/Kconfig | 2 +- scripts/Makefile.build | 2 ++ scripts/Makefile.modfinal | 24 ++++++++++++++++++++++-- scripts/link-vmlinux.sh | 23 ++++++++++++++++++++++- 4 files changed, 47 insertions(+), 4 deletions(-)arch/Kconfig +1
-1@@ -599,7 +599,7 @@ config LTO_CLANG depends on $(success,$(NM) --help | head -n 1 | grep -qi llvm) depends on $(success,$(AR) --help | head -n 1 | grep -qi llvm) depends on ARCH_SUPPORTS_LTO_CLANG - depends on !FTRACE_MCOUNT_RECORD + depends on HAVE_OBJTOOL_MCOUNT || !(X86_64 && DYNAMIC_FTRACE) depends on !KASAN depends on !GCOV_KERNEL select LTOscripts/Makefile.build +2
-0@@ -218,6 +218,7 @@ cmd_record_mcount = $(if $(findstring $(strip $(CC_FLAGS_FTRACE)),$(_c_flags)), endif # USE_RECORDMCOUNT ifdef CONFIG_STACK_VALIDATION +ifndef CONFIG_LTO_CLANG ifneq ($(SKIP_STACK_VALIDATION),1) __objtool_obj := $(objtree)/tools/objtool/objtool@@ -253,6 +254,7 @@ objtool_obj = $(if $(patsubst y%,, \ $(__objtool_obj)) endif # SKIP_STACK_VALIDATION +endif # CONFIG_LTO_CLANG endif # CONFIG_STACK_VALIDATION # Rebuild all objects when objtool changes, or is enabled/disabled.scripts/Makefile.modfinal +9
-1@@ -34,10 +34,30 @@ ifdef CONFIG_LTO_CLANG # With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to # avoid a second slow LTO link prelink-ext := .lto -endif + +# ELF processing was skipped earlier because we didn't have native code, +# so let's now process the prelinked binary before we link the module. + +ifdef CONFIG_STACK_VALIDATION +ifneq ($(SKIP_STACK_VALIDATION),1) +cmd_ld_ko_o += \ + $(objtree)/tools/objtool/objtool \ + $(if $(CONFIG_UNWINDER_ORC),orc generate,check) \
scripts/Makefile.modfinal ifdef CONFIG_LTO_CLANG · line 55
Quoted 10 lines
scripts/Makefile.modfinal +10
-0+ --module \ + $(if $(CONFIG_FRAME_POINTER),,--no-fp) \ + $(if $(CONFIG_GCOV_KERNEL),--no-unreachable,) \ + $(if $(CONFIG_RETPOLINE),--retpoline,) \ + $(if $(CONFIG_X86_SMAP),--uaccess,) \ + $(if $(USE_OBJTOOL_MCOUNT),--mcount,) \ + $(@:.ko=$(prelink-ext).o); + +endif # SKIP_STACK_VALIDATION +endif # CONFIG_STACK_VALIDATION
I wonder if objtool_args could be reused here instead of having two places to keep in sync? It looks like that might mean moving things around a bit before this patch, since I can't quite see if Makefile.build's variables are visible to Makefile.modfinal?
Quoted 47 lines
scripts/Makefile.modfinal +3
-1+ +endif # CONFIG_LTO_CLANG quiet_cmd_ld_ko_o = LD [M] $@ - cmd_ld_ko_o = \ + cmd_ld_ko_o += \ $(LD) -r $(KBUILD_LDFLAGS) \ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ $(addprefix -T , $(KBUILD_LDS_MODULE)) \scripts/link-vmlinux.sh +22
-1@@ -93,8 +93,29 @@ objtool_link() { local objtoolopt; + if [ "${CONFIG_LTO_CLANG} ${CONFIG_STACK_VALIDATION}" = "y y" ]; then + # Don't perform vmlinux validation unless explicitly requested, + # but run objtool on vmlinux.o now that we have an object file. + if [ -n "${CONFIG_UNWINDER_ORC}" ]; then + objtoolopt="orc generate" + else + objtoolopt="check" + fi + + if [ -n ${USE_OBJTOOL_MCOUNT} ]; then + objtoolopt="${objtoolopt} --mcount" + fi + fi + if [ -n "${CONFIG_VMLINUX_VALIDATION}" ]; then - objtoolopt="check --vmlinux" + if [ -z "${objtoolopt}" ]; then + objtoolopt="check --vmlinux" + else + objtoolopt="${objtoolopt} --vmlinux" + fi + fi + + if [ -n "${objtoolopt}" ]; then if [ -z "${CONFIG_FRAME_POINTER}" ]; then objtoolopt="${objtoolopt} --no-fp" fiSignature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 11/28] kbuild: lto: postpone objtool
Quoted 80 lines · Kees Cook
Quoted 5 lines · Sami Tolvanen
With LTO, LLVM bitcode won't be compiled into native code until
modpost_link, or modfinal for modules. This change postpones calls to objtool until after these steps.Signed-off-by Sami Tolvanen <[email protected]>For a "fail fast" style of building, it makes sense to have objtool run as early as possible, so it makes sense to keep the current behavior in non-LTO mode. I do wonder, though, if there is a real benefit to having "fail fast" case. I imagine a lot of automated builds are using --keep-going with make, and actually waiting until the end to do the validation means more code will get build-tested before objtool rejects the results. *shrug*
Quoted 65 lines
--- arch/Kconfig | 2 +- scripts/Makefile.build | 2 ++ scripts/Makefile.modfinal | 24 ++++++++++++++++++++++-- scripts/link-vmlinux.sh | 23 ++++++++++++++++++++++- 4 files changed, 47 insertions(+), 4 deletions(-)arch/Kconfig +1
-1@@ -599,7 +599,7 @@ config LTO_CLANG depends on $(success,$(NM) --help | head -n 1 | grep -qi llvm) depends on $(success,$(AR) --help | head -n 1 | grep -qi llvm) depends on ARCH_SUPPORTS_LTO_CLANG - depends on !FTRACE_MCOUNT_RECORD + depends on HAVE_OBJTOOL_MCOUNT || !(X86_64 && DYNAMIC_FTRACE) depends on !KASAN depends on !GCOV_KERNEL select LTOscripts/Makefile.build +2
-0@@ -218,6 +218,7 @@ cmd_record_mcount = $(if $(findstring $(strip $(CC_FLAGS_FTRACE)),$(_c_flags)), endif # USE_RECORDMCOUNT ifdef CONFIG_STACK_VALIDATION +ifndef CONFIG_LTO_CLANG ifneq ($(SKIP_STACK_VALIDATION),1) __objtool_obj := $(objtree)/tools/objtool/objtool@@ -253,6 +254,7 @@ objtool_obj = $(if $(patsubst y%,, \ $(__objtool_obj)) endif # SKIP_STACK_VALIDATION +endif # CONFIG_LTO_CLANG endif # CONFIG_STACK_VALIDATION # Rebuild all objects when objtool changes, or is enabled/disabled.scripts/Makefile.modfinal +16
-1@@ -34,10 +34,30 @@ ifdef CONFIG_LTO_CLANG # With CONFIG_LTO_CLANG, reuse the object file we compiled for modpost to # avoid a second slow LTO link prelink-ext := .lto -endif + +# ELF processing was skipped earlier because we didn't have native code, +# so let's now process the prelinked binary before we link the module. + +ifdef CONFIG_STACK_VALIDATION +ifneq ($(SKIP_STACK_VALIDATION),1) +cmd_ld_ko_o += \ + $(objtree)/tools/objtool/objtool \ + $(if $(CONFIG_UNWINDER_ORC),orc generate,check) \ + --module \ + $(if $(CONFIG_FRAME_POINTER),,--no-fp) \ + $(if $(CONFIG_GCOV_KERNEL),--no-unreachable,) \ + $(if $(CONFIG_RETPOLINE),--retpoline,) \ + $(if $(CONFIG_X86_SMAP),--uaccess,) \ + $(if $(USE_OBJTOOL_MCOUNT),--mcount,) \ + $(@:.ko=$(prelink-ext).o);
Quoted 8 lines
scripts/Makefile.modfinal ifdef CONFIG_LTO_CLANG · line 55
Quoted 3 lines
scripts/Makefile.modfinal +3
-0+ +endif # SKIP_STACK_VALIDATION +endif # CONFIG_STACK_VALIDATIONI wonder if
objtool_argscould be reused here instead of having two places to keep in sync? It looks like that might mean moving things around a bit before this patch, since I can't quite see if Makefile.build's variables are visible to Makefile.modfinal?
It doesn't look like they are. I suppose we could move objtool_args to Makefile.lib. Masahiro, any thoughts?
Sami
Sami Tolvanen
maintainerPATCH v2 12/28 kbuild: lto: limit inlining
In reply to Sami TolvanenThis change limits function inlining across translation unit boundaries in order to reduce the binary size with LTO. The -import-instr-limit flag defines a size limit, as the number of LLVM IR instructions, for importing functions from other TUs, defaulting to 100.
Based on testing with arm64 defconfig, we found that a limit of 5 is a reasonable compromise between performance and binary size, reducing the size of a stripped vmlinux by 11%.
--- Makefile | 4 ++++ 1 file changed, 4 insertions(+)
Makefile +4 -0
@@ -917,6 +917,10 @@ else CC_FLAGS_LTO_CLANG := -flto endif CC_FLAGS_LTO_CLANG += -fvisibility=default + +# Limit inlining across translation units to reduce binary size +LD_FLAGS_LTO_CLANG := -mllvm -import-instr-limit=5 +KBUILD_LDFLAGS += $(LD_FLAGS_LTO_CLANG) endif ifdef CONFIG_LTO
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 12/28] kbuild: lto: limit inlining
Quoted 11 lines · Sami Tolvanen
This change limits function inlining across translation unit boundaries in order to reduce the binary size with LTO. The -import-instr-limit flag defines a size limit, as the number of LLVM IR instructions, for importing functions from other TUs, defaulting to 100.
Based on testing with arm64 defconfig, we found that a limit of 5 is a reasonable compromise between performance and binary size, reducing the size of a stripped vmlinux by 11%.
Suggested-by George Burgess IV <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 13/28 kbuild: lto: merge module sections
In reply to Sami TolvanenLLD always splits sections with LTO, which increases module sizes. This change adds a linker script that merges the split sections in the final module.
--- Makefile | 2 ++ scripts/module-lto.lds | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 scripts/module-lto.lds
Makefile +2 -0
@@ -921,6 +921,8 @@ CC_FLAGS_LTO_CLANG += -fvisibility=default # Limit inlining across translation units to reduce binary size LD_FLAGS_LTO_CLANG := -mllvm -import-instr-limit=5 KBUILD_LDFLAGS += $(LD_FLAGS_LTO_CLANG) + +KBUILD_LDS_MODULE += $(srctree)/scripts/module-lto.lds endif ifdef CONFIG_LTO
scripts/module-lto.lds new file +26 -0
@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * With CONFIG_LTO_CLANG, LLD always enables -fdata-sections and + * -ffunction-sections, which increases the size of the final module. + * Merge the split sections in the final binary. + */ +SECTIONS { + __patchable_function_entries : { *(__patchable_function_entries) } + + .bss : { + *(.bss .bss.[0-9a-zA-Z_]*) + *(.bss..L*) + } + + .data : { + *(.data .data.[0-9a-zA-Z_]*) + *(.data..L*) + } + + .rodata : { + *(.rodata .rodata.[0-9a-zA-Z_]*) + *(.rodata..L*) + } + + .text : { *(.text .text.[0-9a-zA-Z_]*) } +}
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 13/28] kbuild: lto: merge module sections
Quoted 6 lines · Sami Tolvanen
LLD always splits sections with LTO, which increases module sizes. This change adds a linker script that merges the split sections in the final module.
Suggested-by Nick Desaulniers <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>
We'll likely need to come back around to this for FGKASLR (to keep the .text.* sections separated), but that's no different than the existing concerns for FGKASLR on the main kernel.
Signature · 1 line
Kees Cook
Re: [PATCH v2 13/28] kbuild: lto: merge module sections
In reply to Sami TolvanenQuoted 59 lines · Sami Tolvanen
LLD always splits sections with LTO, which increases module sizes. This change adds a linker script that merges the split sections in the final module.
Suggested-by Nick Desaulniers <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 2 ++ scripts/module-lto.lds | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 scripts/module-lto.ldsMakefile +2
-0@@ -921,6 +921,8 @@ CC_FLAGS_LTO_CLANG += -fvisibility=default # Limit inlining across translation units to reduce binary size LD_FLAGS_LTO_CLANG := -mllvm -import-instr-limit=5 KBUILD_LDFLAGS += $(LD_FLAGS_LTO_CLANG) + +KBUILD_LDS_MODULE += $(srctree)/scripts/module-lto.lds endif ifdef CONFIG_LTOscripts/module-lto.lds new file +26
-1@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * With CONFIG_LTO_CLANG, LLD always enables -fdata-sections and + * -ffunction-sections, which increases the size of the final module. + * Merge the split sections in the final binary. + */ +SECTIONS { + __patchable_function_entries : { *(__patchable_function_entries) } + + .bss : { + *(.bss .bss.[0-9a-zA-Z_]*) + *(.bss..L*) + } + + .data : { + *(.data .data.[0-9a-zA-Z_]*) + *(.data..L*) + } + + .rodata : { + *(.rodata .rodata.[0-9a-zA-Z_]*) + *(.rodata..L*) + } + + .text : { *(.text .text.[0-9a-zA-Z_]*) } +} --
Quoted 2 lines
2.28.0.402.g5ffc5be6b7-goog
After I apply https://patchwork.kernel.org/patch/11757323/,
is it possible to do like this ?
#ifdef CONFIG_LTO
SECTIONS {
...
};#endif
in scripts/module.lds.S
Signature · 2 lines
Best Regards Masahiro Yamada
Sami Tolvanen
maintainerRe: [PATCH v2 13/28] kbuild: lto: merge module sections
Quoted 68 lines · Masahiro Yamada
Quoted 59 lines · Sami Tolvanen
LLD always splits sections with LTO, which increases module sizes. This change adds a linker script that merges the split sections in the final module.
Suggested-by Nick Desaulniers <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>--- Makefile | 2 ++ scripts/module-lto.lds | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 scripts/module-lto.ldsMakefile +2
-0@@ -921,6 +921,8 @@ CC_FLAGS_LTO_CLANG += -fvisibility=default # Limit inlining across translation units to reduce binary size LD_FLAGS_LTO_CLANG := -mllvm -import-instr-limit=5 KBUILD_LDFLAGS += $(LD_FLAGS_LTO_CLANG) + +KBUILD_LDS_MODULE += $(srctree)/scripts/module-lto.lds endif ifdef CONFIG_LTOscripts/module-lto.lds new file +26
-1@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * With CONFIG_LTO_CLANG, LLD always enables -fdata-sections and + * -ffunction-sections, which increases the size of the final module. + * Merge the split sections in the final binary. + */ +SECTIONS { + __patchable_function_entries : { *(__patchable_function_entries) } + + .bss : { + *(.bss .bss.[0-9a-zA-Z_]*) + *(.bss..L*) + } + + .data : { + *(.data .data.[0-9a-zA-Z_]*) + *(.data..L*) + } + + .rodata : { + *(.rodata .rodata.[0-9a-zA-Z_]*) + *(.rodata..L*) + } + + .text : { *(.text .text.[0-9a-zA-Z_]*) } +} --Quoted 2 lines
2.28.0.402.g5ffc5be6b7-goog
After I apply https://patchwork.kernel.org/patch/11757323/,
is it possible to do like this ?
Quoted 7 lines
#ifdef
CONFIG_LTOSECTIONS { ... };#endif
in
scripts/module.lds.S
Yes, that should work. I'll change this in v3 after your change is applied.
Sami
Sami Tolvanen
maintainerPATCH v2 14/28 kbuild: lto: remove duplicate dependencies from .mod files
In reply to Sami TolvanenWith LTO, llvm-nm prints out symbols for each archive member separately, which results in a lot of duplicate dependencies in the .mod file when CONFIG_TRIM_UNUSED_SYMS is enabled. When a module consists of several compilation units, the output can exceed the default xargs command size limit and split the dependency list to multiple lines, which results in used symbols getting trimmed.
This change removes duplicate dependencies, which will reduce the probability of this happening and makes .mod files smaller and easier to read.
--- scripts/Makefile.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/Makefile.build +1 -1
@@ -286,7 +286,7 @@ endef # List module undefined symbols (or empty line if not enabled) ifdef CONFIG_TRIM_UNUSED_KSYMS -cmd_undef_syms = $(NM) $< | sed -n 's/^ *U //p' | xargs echo +cmd_undef_syms = $(NM) $< | sed -n 's/^ *U //p' | sort -u | xargs echo else cmd_undef_syms = echo endif
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 14/28] kbuild: lto: remove duplicate dependencies from .mod files
Quoted 7 lines · Sami Tolvanen
With LTO, llvm-nm prints out symbols for each archive member separately, which results in a lot of duplicate dependencies in the .mod file when
CONFIG_TRIM_UNUSED_SYMSis enabled. When a module consists of several compilation units, the output can exceed the default xargs command size limit and split the dependency list to multiple lines, which results in used symbols getting trimmed.
Quoted 5 lines
This change removes duplicate dependencies, which will reduce the probability of this happening and makes .mod files smaller and easier to read.
Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 15/28 init: lto: ensure initcall ordering
In reply to Sami TolvanenWith LTO, the compiler doesn't necessarily obey the link order for initcalls, and initcall variables need globally unique names to avoid collisions at link time.
This change exports __KBUILD_MODNAME and adds the initcall_id() macro, which uses it together with __COUNTER__ and __LINE__ to help ensure these variables have unique names, and moves each variable to its own section when LTO is enabled, so the correct order can be specified using a linker script.
The generate_initcall_ordering.pl script uses nm to find initcalls from the object files passed to the linker, and generates a linker script that specifies the intended order. With LTO, the script is called in link-vmlinux.sh.
--- include/linux/init.h | 52 +++++- scripts/Makefile.lib | 6 +- scripts/generate_initcall_order.pl | 270 +++++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 14 ++ 4 files changed, 333 insertions(+), 9 deletions(-) create mode 100755 scripts/generate_initcall_order.pl
include/linux/init.h +45 -7
@@ -184,19 +184,57 @@ extern bool initcall_debug;* as KEEP() in the linker script. */ +/* Format: <modname>__<counter>_<line>_<fn> */ +#define __initcall_id (fn) \ + __PASTE(__KBUILD_MODNAME, \ + __PASTE(__, \ + __PASTE(__COUNTER__, \ + __PASTE(_, \ + __PASTE(__LINE__, \ + __PASTE(_, fn)))))) + +/* Format: __<prefix>__<iid><id> */ +#define __initcall_name (prefix, __iid, id) \ + __PASTE(__, \ + __PASTE(prefix, \ + __PASTE(__, \ + __PASTE(__iid, id)))) + +#ifdef CONFIG_LTO_CLANG +/* +* With LTO, the compiler doesn't necessarily obey link order for +* initcalls. In order to preserve the correct order, we add each +* variable into its own section and generate a linker script (in +* scripts/link-vmlinux.sh) to specify the order of the sections. +*/ +#define __initcall_section (__sec, __iid) \ + #__sec ".init.." #__iid +#else +#define __initcall_section (__sec, __iid) \ + #__sec ".init" +#endif +#ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS -#define ___define_initcall (fn, id, __sec) \ +#define ____define_initcall (fn, __name, __sec) \ __ADDRESSABLE(fn) \ - asm(".section \"" #__sec ".init\", \"a\" \n" \ - "__initcall_" #fn #id ": \n" \ + asm(".section \"" __sec "\", \"a\" \n" \ + __stringify(__name) ": \n" \ ".long " #fn " - . \n" \ ".previous \n");#else -#define ___define_initcall (fn, id, __sec) \ - static initcall_t __initcall_##fn##id __used \ - __attribute__((__section__(#__sec ".init"))) = fn; +#define ____define_initcall (fn, __name, __sec) \ + static initcall_t __name __used \ + __attribute__((__section__(__sec))) = fn;#endif +#define __unique_initcall (fn, id, __sec, __iid) \ + ____define_initcall(fn, \ + __initcall_name(initcall, __iid, id), \ + __initcall_section(__sec, __iid)) + +#define ___define_initcall (fn, id, __sec) \ + __unique_initcall(fn, id, __sec, __initcall_id(fn)) +#define __define_initcall (fn, id) ___define_initcall(fn, id, .initcall##id)/*
@@ -236,7 +274,7 @@ extern bool initcall_debug;#define __exitcall (fn) \ static exitcall_t __exitcall_##fn __exit_call = fn -#define console_initcall (fn) ___define_initcall(fn,, .con_initcall) +#define console_initcall (fn) ___define_initcall(fn, con, .con_initcall)struct obs_kernel_param {const char *str;
scripts/Makefile.lib +4 -2
@@ -117,9 +117,11 @@ target-stem = $(basename $(patsubst $(obj)/%,%,$@)) # These flags are needed for modversions and compiling, so we define them here # $(modname_flags) defines KBUILD_MODNAME as the name of the module it will # end up in (or would, if it gets compiled in) -name-fix = $(call stringify,$(subst $(comma),_,$(subst -,_,$1))) +name-fix-token = $(subst $(comma),_,$(subst -,_,$1)) +name-fix = $(call stringify,$(call name-fix-token,$1)) basename_flags = -DKBUILD_BASENAME=$(call name-fix,$(basetarget)) -modname_flags = -DKBUILD_MODNAME=$(call name-fix,$(modname)) +modname_flags = -DKBUILD_MODNAME=$(call name-fix,$(modname)) \ + -D__KBUILD_MODNAME=kmod_$(call name-fix-token,$(modname)) modfile_flags = -DKBUILD_MODFILE=$(call stringify,$(modfile)) _c_flags = $(filter-out $(CFLAGS_REMOVE_$(target-stem).o), \
scripts/generate_initcall_order.pl new file +270 -0
270 lines not on this page · raw message
scripts/link-vmlinux.sh +14 -0
@@ -43,6 +43,16 @@ info() fi } +# Generate a linker script to ensure correct ordering of initcalls. +gen_initcalls() +{ + info GEN .tmp_initcalls.lds + + ${srctree}/scripts/generate_initcall_order.pl \ + ${KBUILD_VMLINUX_OBJS} ${KBUILD_VMLINUX_LIBS} \ + > .tmp_initcalls.lds +} + # If CONFIG_LTO_CLANG is selected, collect generated symbol versions into # .tmp_symversions.lds gen_symversions()
@@ -74,6 +84,9 @@ modpost_link() --end-group" if [ -n "${CONFIG_LTO_CLANG}" ]; then + gen_initcalls + lds="-T .tmp_initcalls.lds" + if [ -n "${CONFIG_MODVERSIONS}" ]; then gen_symversions lds="${lds} -T .tmp_symversions.lds"
@@ -285,6 +298,7 @@ cleanup() { rm -f .btf.* rm -f .tmp_System.map + rm -f .tmp_initcalls.lds rm -f .tmp_symversions.lds rm -f .tmp_vmlinux* rm -f System.map
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 15/28] init: lto: ensure initcall ordering
Quoted 10 lines · Sami Tolvanen
With LTO, the compiler doesn't necessarily obey the link order for initcalls, and initcall variables need globally unique names to avoid collisions at link time.
This change exports
__KBUILD_MODNAMEand adds theinitcall_id()macro, which uses it together with__COUNTER__and__LINE__to help ensure these variables have unique names, and moves each variable to its own section when LTO is enabled, so the correct order can be specified using a linker script.
Quoted 4 lines
The generate_initcall_ordering.pl script uses nm to find initcalls from the object files passed to the linker, and generates a linker script that specifies the intended order. With LTO, the script is called in
link-vmlinux.sh.
I think I asked before about this being made unconditional, but the hit on final link time was noticeable. Am I remembering that right? If so, sure, let's keep it separate.
Quoted 296 lines
Signed-off-by Sami Tolvanen <[email protected]>--- include/linux/init.h | 52 +++++- scripts/Makefile.lib | 6 +- scripts/generate_initcall_order.pl | 270 +++++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 14 ++ 4 files changed, 333 insertions(+), 9 deletions(-) create mode 100755 scripts/generate_initcall_order.plinclude/linux/init.h +45
-7@@ -184,19 +184,57 @@ extern bool initcall_debug;* as KEEP() in the linker script. */ +/* Format: <modname>__<counter>_<line>_<fn> */ +#define __initcall_id (fn) \ + __PASTE(__KBUILD_MODNAME, \ + __PASTE(__, \ + __PASTE(__COUNTER__, \ + __PASTE(_, \ + __PASTE(__LINE__, \ + __PASTE(_, fn)))))) + +/* Format: __<prefix>__<iid><id> */ +#define __initcall_name (prefix, __iid, id) \ + __PASTE(__, \ + __PASTE(prefix, \ + __PASTE(__, \ + __PASTE(__iid, id)))) + +#ifdef CONFIG_LTO_CLANG +/* +* With LTO, the compiler doesn't necessarily obey link order for +* initcalls. In order to preserve the correct order, we add each +* variable into its own section and generate a linker script (in +* scripts/link-vmlinux.sh) to specify the order of the sections. +*/ +#define __initcall_section (__sec, __iid) \ + #__sec ".init.." #__iid +#else +#define __initcall_section (__sec, __iid) \ + #__sec ".init" +#endif +#ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS -#define ___define_initcall (fn, id, __sec) \ +#define ____define_initcall (fn, __name, __sec) \ __ADDRESSABLE(fn) \ - asm(".section \"" #__sec ".init\", \"a\" \n" \ - "__initcall_" #fn #id ": \n" \ + asm(".section \"" __sec "\", \"a\" \n" \ + __stringify(__name) ": \n" \ ".long " #fn " - . \n" \ ".previous \n");#else -#define ___define_initcall (fn, id, __sec) \ - static initcall_t __initcall_##fn##id __used \ - __attribute__((__section__(#__sec ".init"))) = fn; +#define ____define_initcall (fn, __name, __sec) \ + static initcall_t __name __used \ + __attribute__((__section__(__sec))) = fn;#endif +#define __unique_initcall (fn, id, __sec, __iid) \ + ____define_initcall(fn, \ + __initcall_name(initcall, __iid, id), \ + __initcall_section(__sec, __iid)) + +#define ___define_initcall (fn, id, __sec) \ + __unique_initcall(fn, id, __sec, __initcall_id(fn)) +#define __define_initcall (fn, id) ___define_initcall(fn, id, .initcall##id)/* @@ -236,7 +274,7 @@ extern bool initcall_debug;#define __exitcall (fn) \ static exitcall_t __exitcall_##fn __exit_call = fn -#define console_initcall (fn) ___define_initcall(fn,, .con_initcall) +#define console_initcall (fn) ___define_initcall(fn, con, .con_initcall)struct obs_kernel_param {const char *str;scripts/Makefile.lib +4
-2@@ -117,9 +117,11 @@ target-stem = $(basename $(patsubst $(obj)/%,%,$@)) # These flags are needed for modversions and compiling, so we define them here # $(modname_flags) defines KBUILD_MODNAME as the name of the module it will # end up in (or would, if it gets compiled in) -name-fix = $(call stringify,$(subst $(comma),_,$(subst -,_,$1))) +name-fix-token = $(subst $(comma),_,$(subst -,_,$1)) +name-fix = $(call stringify,$(call name-fix-token,$1)) basename_flags = -DKBUILD_BASENAME=$(call name-fix,$(basetarget)) -modname_flags = -DKBUILD_MODNAME=$(call name-fix,$(modname)) +modname_flags = -DKBUILD_MODNAME=$(call name-fix,$(modname)) \ + -D__KBUILD_MODNAME=kmod_$(call name-fix-token,$(modname)) modfile_flags = -DKBUILD_MODFILE=$(call stringify,$(modfile)) _c_flags = $(filter-out $(CFLAGS_REMOVE_$(target-stem).o), \scripts/generate_initcall_order.pl new file +185
-0@@ -0,0 +1,270 @@ +#!/usr/bin/env perl +# SPDX-License-Identifier: GPL-2.0 +# +# Generates a linker script that specifies the correct initcall order. +# +# Copyright (C) 2019 Google LLC + +use strict; +use warnings; +use IO::Handle; +use IO::Select; +use POSIX ":sys_wait_h"; + +my $nm = $ENV{'NM'} || die "$0: ERROR: NM not set?"; +my $objtree = $ENV{'objtree'} || '.'; + +## currently active child processes +my $jobs = {}; # child process pid -> file handle +## results from child processes +my $results = {}; # object index -> [ { level, secname }, ... ] + +## reads _NPROCESSORS_ONLN to determine the maximum number of processes to +## start +sub get_online_processors { + open(my $fh, "getconf _NPROCESSORS_ONLN 2>/dev/null |") + or die "$0: ERROR: failed to execute getconf: $!"; + my $procs = <$fh>; + close($fh); + + if (!($procs =~ /^\d+$/)) { + return 1; + } + + return int($procs); +} + +## writes results to the parent process +## format: <file index> <initcall level> <base initcall section name> +sub write_results { + my ($index, $initcalls) = @_; + + # sort by the counter value to ensure the order of initcalls within + # each object file is correct + foreach my $counter (sort { $a <=> $b } keys(%{$initcalls})) { + my $level = $initcalls->{$counter}->{'level'}; + + # section name for the initcall function + my $secname = $initcalls->{$counter}->{'module'} . '__' . + $counter . '_' . + $initcalls->{$counter}->{'line'} . '_' . + $initcalls->{$counter}->{'function'}; + + print "$index $level $secname\n"; + } +} + +## reads a result line from a child process and adds it to the $results array +sub read_results{ + my ($fh) = @_; + + # each child prints out a full line w/ autoflush and exits after the + # last line, so even if buffered I/O blocks here, it shouldn't block + # very long + my $data = <$fh>; + + if (!defined($data)) { + return 0; + } + + chomp($data); + + my ($index, $level, $secname) = $data =~ + /^(\d+)\ ([^\ ]+)\ (.*)$/; + + if (!defined($index) || + !defined($level) || + !defined($secname)) { + die "$0: ERROR: child process returned invalid data: $data\n"; + } + + $index = int($index); + + if (!exists($results->{$index})) { + $results->{$index} = []; + } + + push (@{$results->{$index}}, { + 'level' => $level, + 'secname' => $secname + }); + + return 1; +} + +## finds initcalls from an object file or all object files in an archive, and +## writes results back to the parent process +sub find_initcalls { + my ($index, $file) = @_; + + die "$0: ERROR: file $file doesn't exist?" if (! -f $file); + + open(my $fh, "\"$nm\" --defined-only \"$file\" 2>/dev/null |") + or die "$0: ERROR: failed to execute \"$nm\": $!"; + + my $initcalls = {}; + + while (<$fh>) { + chomp; + + # check for the start of a new object file (if processing an + # archive) + my ($path)= $_ =~ /^(.+)\:$/; + + if (defined($path)) { + write_results($index, $initcalls); + $initcalls = {}; + next; + } + + # look for an initcall + my ($module, $counter, $line, $symbol) = $_ =~ + /[a-z]\s+__initcall__(\S*)__(\d+)_(\d+)_(.*)$/; + + if (!defined($module)) { + $module = '' + } + + if (!defined($counter) || + !defined($line) || + !defined($symbol)) { + next; + } + + # parse initcall level + my ($function, $level) = $symbol =~ + /^(.*)((early|rootfs|con|[0-9])s?)$/; + + die "$0: ERROR: invalid initcall name $symbol in $file($path)" + if (!defined($function) || !defined($level)); + + $initcalls->{$counter} = { + 'module' => $module, + 'line' => $line, + 'function' => $function, + 'level' => $level, + }; + } + + close($fh); + write_results($index, $initcalls); +} + +## waits for any child process to complete, reads the results, and adds them to +## the $results array for later processing +sub wait_for_results { + my ($select) = @_; + + my $pid = 0; + do { + # unblock children that may have a full write buffer + foreach my $fh ($select->can_read(0)) { + read_results($fh); + } + + # check for children that have exited, read the remaining data + # from them, and clean up + $pid = waitpid(-1, WNOHANG); + if ($pid > 0) { + if (!exists($jobs->{$pid})) { + next; + } + + my $fh = $jobs->{$pid}; + $select->remove($fh); + + while (read_results($fh)) { + # until eof + } + + close($fh); + delete($jobs->{$pid}); + } + } while ($pid > 0); +} +
scripts/generate_initcall_order.pl line 195
Quoted 10 lines
scripts/generate_initcall_order.pl new file +10
-0+## forks a child to process each file passed in the command line and collects +## the results +sub process_files { + my $index = 0; + my $njobs = get_online_processors(); + my $select = IO::Select->new(); + + while (my $file = shift(@ARGV)) { + # fork a child process and read it's stdout + my $pid = open(my $fh, '-|');
/me makes noises about make -jN and the jobserver and not using all processors on a machine if we were asked nicely not to.
I wrote a jobserver aware tool for the documentation builds, but it's in python (scripts/jobserver-exec). Instead of reinventing that wheel (and in Perl), we could:
1) ignore this problem and assume anyone using LTO is fine with using all CPUs
2) implement a jobserver-aware Perl script to do this
3) make Python a build dependency of CONFIG_LTO and re-use scripts/jobserver-exec
Quoted 97 lines
scripts/generate_initcall_order.pl new file +75
-0+ + if (!defined($pid)) { + die "$0: ERROR: failed to fork: $!"; + } elsif ($pid) { + # save the child process pid and the file handle + $select->add($fh); + $jobs->{$pid} = $fh; + } else { + # in the child process + STDOUT->autoflush(1); + find_initcalls($index, "$objtree/$file"); + exit; + } + + $index++; + + # limit the number of children to $njobs + if (scalar(keys(%{$jobs})) >= $njobs) { + wait_for_results($select); + } + } + + # wait for the remaining children to complete + while (scalar(keys(%{$jobs})) > 0) { + wait_for_results($select); + } +} + +sub generate_initcall_lds() { + process_files(); + + my $sections = {}; # level -> [ secname, ...] + + # sort results to retain link order and split to sections per + # initcall level + foreach my $index (sort { $a <=> $b } keys(%{$results})) { + foreach my $result (@{$results->{$index}}) { + my $level = $result->{'level'}; + + if (!exists($sections->{$level})) { + $sections->{$level} = []; + } + + push(@{$sections->{$level}}, $result->{'secname'}); + } + } + + die "$0: ERROR: no initcalls?" if (!keys(%{$sections})); + + # print out a linker script that defines the order of initcalls for + # each level + print "SECTIONS {\n"; + + foreach my $level (sort(keys(%{$sections}))) { + my $section; + + if ($level eq 'con') { + $section = '.con_initcall.init'; + } else { + $section = ".initcall${level}.init"; + } + + print "\t${section} : {\n"; + + foreach my $secname (@{$sections->{$level}}) { + print "\t\t*(${section}..${secname}) ;\n"; + } + + print "\t}\n"; + } + + print "}\n"; +} + +generate_initcall_lds();scripts/link-vmlinux.sh +10
-0@@ -43,6 +43,16 @@ info() fi } +# Generate a linker script to ensure correct ordering of initcalls. +gen_initcalls() +{ + info GEN .tmp_initcalls.lds + + ${srctree}/scripts/generate_initcall_order.pl \ + ${KBUILD_VMLINUX_OBJS} ${KBUILD_VMLINUX_LIBS} \ + > .tmp_initcalls.lds +} + # If CONFIG_LTO_CLANG is selected, collect generated symbol versions into # .tmp_symversions.lds gen_symversions()
scripts/link-vmlinux.sh modpost_link() · line 88
Quoted 5 lines
scripts/link-vmlinux.sh +2
-0@@ -74,6 +84,9 @@ modpost_link() --end-group" if [ -n "${CONFIG_LTO_CLANG}" ]; then + gen_initcalls + lds="-T .tmp_initcalls.lds"
Oh, I think lds should be explicitly a "local" at the start of this function, perhaps back in the symversions patch that touches this?
Quoted 15 lines
scripts/link-vmlinux.sh +2
-0+ if [ -n "${CONFIG_MODVERSIONS}" ]; then gen_symversions lds="${lds} -T .tmp_symversions.lds"@@ -285,6 +298,7 @@ cleanup() { rm -f .btf.* rm -f .tmp_System.map + rm -f .tmp_initcalls.lds rm -f .tmp_symversions.lds rm -f .tmp_vmlinux* rm -f System.mapSignature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 15/28] init: lto: ensure initcall ordering
Quoted 11 lines · Kees Cook
Quoted 10 lines · Sami Tolvanen
With LTO, the compiler doesn't necessarily obey the link order for initcalls, and initcall variables need globally unique names to avoid collisions at link time.
This change exports
__KBUILD_MODNAMEand adds theinitcall_id()macro, which uses it together with__COUNTER__and__LINE__to help ensure these variables have unique names, and moves each variable to its own section when LTO is enabled, so the correct order can be specified using a linker script.
Quoted 8 lines
Quoted 4 lines
The generate_initcall_ordering.pl script uses nm to find initcalls from the object files passed to the linker, and generates a linker script that specifies the intended order. With LTO, the script is called in
link-vmlinux.sh.I think I asked before about this being made unconditional, but the hit on final link time was noticeable. Am I remembering that right? If so, sure, let's keep it separate.
Yes, it was noticeable when compiling on systems with fewer CPU cores, so I would prefer to keep it separate.
Quoted 18 lines
scripts/generate_initcall_order.pl line 195
Quoted 10 lines
scripts/generate_initcall_order.pl new file +10
-0+## forks a child to process each file passed in the command line and collects +## the results +sub process_files { + my $index = 0; + my $njobs = get_online_processors(); + my $select = IO::Select->new(); + + while (my $file = shift(@ARGV)) { + # fork a child process and read it's stdout + my $pid = open(my $fh, '-|');/me makes noises about make -jN and the jobserver and not using all processors on a machine if we were asked nicely not to.
I wrote a jobserver aware tool for the documentation builds, but it's in python (
scripts/jobserver-exec). Instead of reinventing that wheel (and in Perl), we could:
Quoted 5 lines
1) ignore this problem and assume anyone using LTO is fine with using all CPUs
2) implement a jobserver-aware Perl script to do this
3) make Python a build dependency of
CONFIG_LTOand re-usescripts/jobserver-exec
I'm fine with any of these options, although I'm not sure why anyone would want to compile an LTO kernel without using all the available cores... :)
Using jobserver-exec seems like the easiest option if we want to limit the number of cores used here. Any preferences?
Quoted 6 lines
Quoted 6 lines
# If
CONFIG_LTO_CLANGis selected, collect generated symbol versions into# .tmp_symversions.lds gen_symversions()scripts/link-vmlinux.sh +0
-0@@ -74,6 +84,9 @@ modpost_link() --end-group"
Quoted 6 lines
scripts/link-vmlinux.sh modpost_link() · line 88
Quoted 3 lines
scripts/link-vmlinux.sh +2
-0if [ -n "${CONFIG_LTO_CLANG}" ]; then + gen_initcalls + lds="-T .tmp_initcalls.lds"Oh, I think lds should be explicitly a "local" at the start of this function, perhaps back in the symversions patch that touches this?
It's already local, that part is just not visible in this patch.
Sami
Re: [PATCH v2 15/28] init: lto: ensure initcall ordering
In reply to Sami TolvanenQuoted 10 lines · Sami Tolvanen
With LTO, the compiler doesn't necessarily obey the link order for initcalls, and initcall variables need globally unique names to avoid collisions at link time.
This change exports
__KBUILD_MODNAMEand adds theinitcall_id()macro, which uses it together with__COUNTER__and__LINE__to help ensure these variables have unique names, and moves each variable to its own section when LTO is enabled, so the correct order can be specified using a linker script.
Quoted 4 lines
The generate_initcall_ordering.pl script uses nm to find initcalls from the object files passed to the linker, and generates a linker script that specifies the intended order. With LTO, the script is called in
link-vmlinux.sh.
Is this guaranteed to give you the *same* initcall ordering with LTO as without?
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Sami Tolvanen
maintainerRe: [PATCH v2 15/28] init: lto: ensure initcall ordering
Quoted 11 lines · David Woodhouse
Quoted 10 lines · Sami Tolvanen
With LTO, the compiler doesn't necessarily obey the link order for initcalls, and initcall variables need globally unique names to avoid collisions at link time.
This change exports
__KBUILD_MODNAMEand adds theinitcall_id()macro, which uses it together with__COUNTER__and__LINE__to help ensure these variables have unique names, and moves each variable to its own section when LTO is enabled, so the correct order can be specified using a linker script.
Quoted 7 lines
Quoted 4 lines
The generate_initcall_ordering.pl script uses nm to find initcalls from the object files passed to the linker, and generates a linker script that specifies the intended order. With LTO, the script is called in
link-vmlinux.sh.Is this guaranteed to give you the *same* initcall ordering with LTO as without?
Yes. It follows the link order, just like the linker without LTO, and also preserves the order within each file.
Sami
Sami Tolvanen
maintainerPATCH v2 16/28 init: lto: fix PREL32 relocations
In reply to Sami TolvanenWith LTO, the compiler can rename static functions to avoid global naming collisions. As initcall functions are typically static, renaming can break references to them in inline assembly. This change adds a global stub with a stable name for each initcall to fix the issue when PREL32 relocations are used.
--- include/linux/init.h | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-)
include/linux/init.h +27 -4
@@ -209,26 +209,49 @@ extern bool initcall_debug;*/ #define __initcall_section (__sec, __iid) \ #__sec ".init.." #__iid + +/* +* With LTO, the compiler can rename static functions to avoid +* global naming collisions. We use a global stub function for +* initcalls to create a stable symbol name whose address can be +* taken in inline assembly when PREL32 relocations are used. +*/ +#define __initcall_stub (fn, __iid, id) \ + __initcall_name(initstub, __iid, id) + +#define __define_initcall_stub (__stub, fn) \ + int __init __stub(void); \ + int __init __stub(void) \ + { \ + return fn(); \ + } \ + __ADDRESSABLE(__stub)#else #define __initcall_section (__sec, __iid) \ #__sec ".init" + +#define __initcall_stub (fn, __iid, id) fn + +#define __define_initcall_stub (__stub, fn) \ + __ADDRESSABLE(fn)#endif #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS -#define ____define_initcall (fn, __name, __sec) \ - __ADDRESSABLE(fn) \ +#define ____define_initcall (fn, __stub, __name, __sec) \ + __define_initcall_stub(__stub, fn) \ asm(".section \"" __sec "\", \"a\" \n" \ __stringify(__name) ": \n" \ - ".long " #fn " - . \n" \ + ".long " __stringify(__stub) " - . \n" \ ".previous \n");#else -#define ____define_initcall (fn, __name, __sec) \ +#define ____define_initcall (fn, __unused, __name, __sec) \ static initcall_t __name __used \ __attribute__((__section__(__sec))) = fn;#endif #define __unique_initcall (fn, id, __sec, __iid) \ ____define_initcall(fn, \ + __initcall_stub(fn, __iid, id), \ __initcall_name(initcall, __iid, id), \ __initcall_section(__sec, __iid))
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 16/28] init: lto: fix PREL32 relocations
Quoted 7 lines · Sami Tolvanen' via Clang Built Linux
With LTO, the compiler can rename static functions to avoid global naming collisions. As initcall functions are typically static, renaming can break references to them in inline assembly. This change adds a global stub with a stable name for each initcall to fix the issue when PREL32 relocations are used.
Signed-off-by Sami Tolvanen <[email protected]>
This was a Delight(tm) to get right. Thanks for finding the right magic here. :)
Signature · 1 line
Kees Cook
Sasha Levin
maintainerRe: [PATCH v2 16/28] init: lto: fix PREL32 relocations
In reply to Sami TolvanenHi
[This is an automated email]
This commit has been processed because it contains a -stable tag. The stable tag indicates that it's relevant for the following trees: all
The bot has tested the following trees: v5.8.6, v5.4.62, v4.19.143, v4.14.196, v4.9.235, v4.4.235.
v5.8.6: Build OK!
v5.4.62: Build OK!
v4.19.143: Failed to apply! Possible dependencies:
458a3bf82df4 ("lib/string: Add strscpy_pad() function")
f51a03c82ca3 ("lib/string.c: implement stpcpy")v4.14.196: Failed to apply! Possible dependencies:
458a3bf82df4 ("lib/string: Add strscpy_pad() function")
f51a03c82ca3 ("lib/string.c: implement stpcpy")v4.9.235: Failed to apply! Possible dependencies:
458a3bf82df4 ("lib/string: Add strscpy_pad() function")
f51a03c82ca3 ("lib/string.c: implement stpcpy")v4.4.235: Failed to apply! Possible dependencies:
458a3bf82df4 ("lib/string: Add strscpy_pad() function")
f51a03c82ca3 ("lib/string.c: implement stpcpy")NOTE: The patch will not be queued to stable trees until it is upstream.
How should we proceed with this patch?
Signature · 2 lines
Thanks Sasha
Sami Tolvanen
maintainerPATCH v2 17/28 PCI: Fix PREL32 relocations for LTO
In reply to Sami TolvanenWith Clang's Link Time Optimization (LTO), the compiler can rename static functions to avoid global naming collisions. As PCI fixup functions are typically static, renaming can break references to them in inline assembly. This change adds a global stub to DECLARE_PCI_FIXUP_SECTION to fix the issue when PREL32 relocations are used.
--- include/linux/pci.h | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-)
include/linux/pci.h +14 -5
@@ -1909,19 +1909,28 @@ enum pci_fixup_pass { };#ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS -#define __DECLARE_PCI_FIXUP_SECTION (sec, name, vendor, device, class, \ - class_shift, hook) \ - __ADDRESSABLE(hook) \ +#define ___DECLARE_PCI_FIXUP_SECTION (sec, name, vendor, device, class, \ + class_shift, hook, stub) \ + void stub(struct pci_dev *dev); \ + void stub(struct pci_dev *dev) \ + { \ + hook(dev); \ + } \ asm(".section " #sec ", \"a\" \n" \ ".balign 16 \n" \ ".short " #vendor ", " #device " \n" \ ".long " #class ", " #class_shift " \n" \ - ".long " #hook " - . \n" \ + ".long " #stub " - . \n" \ ".previous \n"); + +#define __DECLARE_PCI_FIXUP_SECTION (sec, name, vendor, device, class, \ + class_shift, hook, stub) \ + ___DECLARE_PCI_FIXUP_SECTION(sec, name, vendor, device, class, \ + class_shift, hook, stub)#define DECLARE_PCI_FIXUP_SECTION (sec, name, vendor, device, class, \ class_shift, hook) \ __DECLARE_PCI_FIXUP_SECTION(sec, name, vendor, device, class, \ - class_shift, hook) + class_shift, hook, __UNIQUE_ID(hook))#else /* Anonymous variables would be nice... */ #define DECLARE_PCI_FIXUP_SECTION(section, name, vendor, device, class, \
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 17/28] PCI: Fix PREL32 relocations for LTO
Quoted 8 lines · Sami Tolvanen
With Clang's Link Time Optimization (LTO), the compiler can rename static functions to avoid global naming collisions. As PCI fixup functions are typically static, renaming can break references to them in inline assembly. This change adds a global stub to
DECLARE_PCI_FIXUP_SECTIONto fix the issue when PREL32 relocations are used.Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 18/28 modpost: lto: strip .lto from module names
In reply to Sami TolvanenWith LTO, everything is compiled into LLVM bitcode, so we have to link each module into native code before modpost. Kbuild uses the .lto.o suffix for these files, which also ends up in module information. This change strips the unnecessary .lto suffix from the module name.
--- scripts/mod/modpost.c | 16 +++++++--------- scripts/mod/modpost.h | 9 +++++++++ scripts/mod/sumversion.c | 6 +++++- 3 files changed, 21 insertions(+), 10 deletions(-)
scripts/mod/modpost.c +7 -9
@@ -17,7 +17,6 @@#include <ctype.h> #include <string.h> #include <limits.h> -#include <stdbool.h> #include <errno.h> #include "modpost.h" #include "../../include/linux/license.h"
@@ -80,14 +79,6 @@ modpost_log(enum loglevel loglevel, const char *fmt, ...)exit (1 ); } -static inline bool strends (const char *str,const char *postfix) -{ -if (strlen (str) <strlen (postfix)) -return false; - -return strcmp (str +strlen (str) -strlen (postfix), postfix) ==0 ; -} -void *do_nofail (void *ptr,const char *expr) {if (!ptr)
@@ -1984,6 +1975,10 @@ static char *remove_dot(char *s)size_t m =strspn (s + n +1 ,"0123456789" );if (m && (s[n + m] =='.' || s[n + m] ==0 )) s[n] =0 ; + +/* strip trailing .lto */ +if (strends (s,".lto" )) + s[strlen (s) -4 ] ='\0' ; }return s; }
@@ -2007,6 +2002,9 @@ static void read_symbols(const char *modname)/* strip trailing .o */ tmp =NOFAIL (strdup (modname)); tmp[strlen (tmp) -2 ] ='\0' ; +/* strip trailing .lto */ +if (strends (tmp,".lto" )) + tmp[strlen (tmp) -4 ] ='\0' ; mod =new_module (tmp);free (tmp); }
scripts/mod/modpost.h +9 -0
@@ -2,6 +2,7 @@#include <stdio.h> #include <stdlib.h> #include <stdarg.h> +#include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h>
@@ -180,6 +181,14 @@ static inline unsigned int get_secindex(const struct elf_info *info,return info->symtab_shndx_start[sym - info->symtab_start]; } +static inline bool strends (const char *str,const char *postfix) +{ +if (strlen (str) <strlen (postfix)) +return false; + +return strcmp (str +strlen (str) -strlen (postfix), postfix) ==0 ; +} +/* file2alias.c */ extern unsigned int cross_build; void handle_moddevtable(struct module *mod, struct elf_info *info,
scripts/mod/sumversion.c +5 -1
@@ -391,10 +391,14 @@ void get_src_version(const char *modname, char sum[], unsigned sumlen)struct md4_ctx md;char *fname;char filelist[PATH_MAX +1 ]; +int postfix_len =1 ; + +if (strends (modname,".lto.o" )) + postfix_len =5 ;/* objects for a module are listed in the first line of *.mod file. */ snprintf (filelist,sizeof (filelist),"%.*smod" , - (int )strlen (modname) -1 , modname); + (int )strlen (modname) - postfix_len, modname); buf =read_text_file (filelist);
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 18/28] modpost: lto: strip .lto from module names
Quoted 7 lines · Sami Tolvanen
With LTO, everything is compiled into LLVM bitcode, so we have to link each module into native code before modpost.
Kbuilduses the .lto.o suffix for these files, which also ends up in module information. This change strips the unnecessary .lto suffix from the module name.Suggested-by Bill Wendling <[email protected]>Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 19/28 scripts/mod: disable LTO for empty.c
In reply to Sami TolvanenWith CONFIG_LTO_CLANG, clang generates LLVM IR instead of ELF object files. As empty.o is used for probing target properties, disable LTO for it to produce an object file instead.
--- scripts/mod/Makefile | 1 + 1 file changed, 1 insertion(+)
scripts/mod/Makefile +1 -0
@@ -1,5 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 OBJECT_FILES_NON_STANDARD := y +CFLAGS_REMOVE_empty.o += $(CC_FLAGS_LTO) hostprogs-always-y += modpost mk_elfconfig always-y += empty.o
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 19/28] scripts/mod: disable LTO for empty.c
Quoted 5 lines · Sami Tolvanen
With
CONFIG_LTO_CLANG, clang generates LLVM IR instead of ELF object files. As empty.o is used for probing target properties, disable LTO for it to produce an object file instead.Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 20/28 efi/libstub: disable LTO
In reply to Sami TolvanenWith CONFIG_LTO_CLANG, we produce LLVM bitcode instead of ELF object files. Since LTO is not really needed here and the Makefile assumes we produce an object file, disable LTO for libstub.
--- drivers/firmware/efi/libstub/Makefile | 2 ++ 1 file changed, 2 insertions(+)
drivers/firmware/efi/libstub/Makefile +2 -0
@@ -35,6 +35,8 @@ KBUILD_CFLAGS := $(cflags-y) -Os -DDISABLE_BRANCH_PROFILING \ # remove SCS flags from all objects in this directory KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_SCS), $(KBUILD_CFLAGS)) +# disable LTO +KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_LTO), $(KBUILD_CFLAGS)) GCOV_PROFILE := n # Sanitizer runtimes are unavailable and cannot be linked here.
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 20/28] efi/libstub: disable LTO
Quoted 5 lines · Sami Tolvanen
With
CONFIG_LTO_CLANG, we produce LLVM bitcode instead of ELF object files. Since LTO is not really needed here and theMakefileassumes we produce an object file, disable LTO for libstub.Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 21/28 drivers/misc/lkdtm: disable LTO for rodata.o
In reply to Sami TolvanenDisable LTO for rodata.o to allow objcopy to be used to manipulate sections.
--- drivers/misc/lkdtm/Makefile | 1 + 1 file changed, 1 insertion(+)
drivers/misc/lkdtm/Makefile +1 -0
@@ -13,6 +13,7 @@ lkdtm-$(CONFIG_LKDTM) += cfi.o KASAN_SANITIZE_stackleak.o := n KCOV_INSTRUMENT_rodata.o := n +CFLAGS_REMOVE_rodata.o += $(CC_FLAGS_LTO) OBJCOPYFLAGS := OBJCOPYFLAGS_rodata_objcopy.o := \
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Sami Tolvanen
maintainerPATCH v2 22/28 arm64: export CC_USING_PATCHABLE_FUNCTION_ENTRY
In reply to Sami TolvanenSince arm64 does not use -pg in CC_FLAGS_FTRACE with DYNAMIC_FTRACE_WITH_REGS, skip running recordmcount by exporting CC_USING_PATCHABLE_FUNCTION_ENTRY.
--- arch/arm64/Makefile | 1 + 1 file changed, 1 insertion(+)
arch/arm64/Makefile +1 -0
@@ -127,6 +127,7 @@ endif ifeq ($(CONFIG_DYNAMIC_FTRACE_WITH_REGS),y) KBUILD_CPPFLAGS += -DCC_USING_PATCHABLE_FUNCTION_ENTRY CC_FLAGS_FTRACE := -fpatchable-function-entry=2 + export CC_USING_PATCHABLE_FUNCTION_ENTRY := 1 endif # Default value
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 22/28] arm64: export CC_USING_PATCHABLE_FUNCTION_ENTRY
Quoted 5 lines · Sami Tolvanen
Since arm64 does not use -pg in
CC_FLAGS_FTRACEwithDYNAMIC_FTRACE_WITH_REGS, skip running recordmcount by exportingCC_USING_PATCHABLE_FUNCTION_ENTRY.Signed-off-by Sami Tolvanen <[email protected]>
How stand-alone is this? Does it depend on the earlier mcount fixes?
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 22/28] arm64: export CC_USING_PATCHABLE_FUNCTION_ENTRY
Quoted 8 lines · Kees Cook
Quoted 5 lines · Sami Tolvanen
Since arm64 does not use -pg in
CC_FLAGS_FTRACEwithDYNAMIC_FTRACE_WITH_REGS, skip running recordmcount by exportingCC_USING_PATCHABLE_FUNCTION_ENTRY.Signed-off-by Sami Tolvanen <[email protected]>How stand-alone is this? Does it depend on the earlier mcount fixes?
It does, because exporting CC_USING_PATCHABLE_FUNCTION_ENTRY doesn't change anything without the earlier mcount changes.
Sami
Sami Tolvanen
maintainerPATCH v2 23/28 arm64: vdso: disable LTO
In reply to Sami TolvanenDisable LTO for the vDSO by filtering out CC_FLAGS_LTO, as there's no point in using link-time optimization for the small about of C code.
--- arch/arm64/kernel/vdso/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/arm64/kernel/vdso/Makefile +2 -2
@@ -30,8 +30,8 @@ ldflags-y := -shared -nostdlib -soname=linux-vdso.so.1 --hash-style=sysv \ ccflags-y := -fno-common -fno-builtin -fno-stack-protector -ffixed-x18 ccflags-y += -DDISABLE_BRANCH_PROFILING -CFLAGS_REMOVE_vgettimeofday.o = $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) $(GCC_PLUGINS_CFLAGS) -KBUILD_CFLAGS += $(DISABLE_LTO) +CFLAGS_REMOVE_vgettimeofday.o = $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) $(GCC_PLUGINS_CFLAGS) \ + $(CC_FLAGS_LTO) KASAN_SANITIZE := n UBSAN_SANITIZE := n OBJECT_FILES_NON_STANDARD := y
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 23/28] arm64: vdso: disable LTO
Quoted 4 lines · Sami Tolvanen
Disable LTO for the vDSO by filtering out
CC_FLAGS_LTO, as there's no point in using link-time optimization for the small about of C code.Signed-off-by Sami Tolvanen <[email protected]>
Yup. (And another replacement of the non-functional DISABLE_LTO...)
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 24/28 KVM: arm64: disable LTO for the nVHE directory
In reply to Sami TolvanenWe use objcopy to manipulate ELF binaries for the nvhe code, which fails with LTO as the compiler produces LLVM bitcode instead. Disable LTO for this code to allow objcopy to be used.
--- arch/arm64/kvm/hyp/nvhe/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/arm64/kvm/hyp/nvhe/Makefile +2 -2
@@ -45,9 +45,9 @@ quiet_cmd_hypcopy = HYPCOPY $@ --rename-section=.text=.hyp.text \ $< $@ -# Remove ftrace and Shadow Call Stack CFLAGS. +# Remove ftrace, LTO, and Shadow Call Stack CFLAGS. # This is equivalent to the 'notrace' and '__noscs' annotations. -KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_FTRACE) $(CC_FLAGS_SCS), $(KBUILD_CFLAGS)) +KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_FTRACE) $(CC_FLAGS_LTO) $(CC_FLAGS_SCS), $(KBUILD_CFLAGS)) # KVM nVHE code is run at a different exception code with a different map, so # compiler instrumentation that inserts callbacks or checks into the code may
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 24/28] KVM: arm64: disable LTO for the nVHE directory
Quoted 5 lines · Sami Tolvanen' via Clang Built Linux
We use objcopy to manipulate ELF binaries for the nvhe code, which fails with LTO as the compiler produces LLVM bitcode instead. Disable LTO for this code to allow objcopy to be used.
Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 25/28 arm64: allow LTO_CLANG and THINLTO to be selected
In reply to Sami TolvanenAllow CONFIG_LTO_CLANG and CONFIG_THINLTO to be enabled.
--- arch/arm64/Kconfig | 2 ++ 1 file changed, 2 insertions(+)
arch/arm64/Kconfig +2 -0
@@ -72,6 +72,8 @@ config ARM64 select ARCH_USE_SYM_ANNOTATIONS select ARCH_SUPPORTS_MEMORY_FAILURE select ARCH_SUPPORTS_SHADOW_CALL_STACK if CC_HAVE_SHADOW_CALL_STACK + select ARCH_SUPPORTS_LTO_CLANG + select ARCH_SUPPORTS_THINLTO select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_INT128 if CC_HAS_INT128 && (GCC_VERSION >= 50000 || CC_IS_CLANG) select ARCH_SUPPORTS_NUMA_BALANCING
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 25/28] arm64: allow LTO_CLANG and THINLTO to be selected
Quoted 3 lines · Sami Tolvanen
Allow
CONFIG_LTO_CLANGandCONFIG_THINLTOto be enabled.Signed-off-by Sami Tolvanen <[email protected]>
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 26/28 x86, vdso: disable LTO only for vDSO
In reply to Sami TolvanenRemove the undefined DISABLE_LTO flag from the vDSO, and filter out CC_FLAGS_LTO flags instead where needed. Note that while we could use Clang's LTO for the 64-bit vDSO, it won't add noticeable benefit for the small amount of C code.
--- arch/x86/entry/vdso/Makefile | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
arch/x86/entry/vdso/Makefile +2 -3
@@ -9,8 +9,6 @@ ARCH_REL_TYPE_ABS := R_X86_64_JUMP_SLOT|R_X86_64_GLOB_DAT|R_X86_64_RELATIVE| ARCH_REL_TYPE_ABS += R_386_GLOB_DAT|R_386_JMP_SLOT|R_386_RELATIVE include $(srctree)/lib/vdso/Makefile -KBUILD_CFLAGS += $(DISABLE_LTO) - # Sanitizer runtimes are unavailable and cannot be linked here. KASAN_SANITIZE := n UBSAN_SANITIZE := n
@@ -92,7 +90,7 @@ ifneq ($(RETPOLINE_VDSO_CFLAGS),) endif endif -$(vobjs): KBUILD_CFLAGS := $(filter-out $(GCC_PLUGINS_CFLAGS) $(RETPOLINE_CFLAGS),$(KBUILD_CFLAGS)) $(CFL) +$(vobjs): KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_LTO) $(GCC_PLUGINS_CFLAGS) $(RETPOLINE_CFLAGS),$(KBUILD_CFLAGS)) $(CFL) # # vDSO code runs in userspace and -pg doesn't help with profiling anyway.
@@ -150,6 +148,7 @@ KBUILD_CFLAGS_32 := $(filter-out -fno-pic,$(KBUILD_CFLAGS_32)) KBUILD_CFLAGS_32 := $(filter-out -mfentry,$(KBUILD_CFLAGS_32)) KBUILD_CFLAGS_32 := $(filter-out $(GCC_PLUGINS_CFLAGS),$(KBUILD_CFLAGS_32)) KBUILD_CFLAGS_32 := $(filter-out $(RETPOLINE_CFLAGS),$(KBUILD_CFLAGS_32)) +KBUILD_CFLAGS_32 := $(filter-out $(CC_FLAGS_LTO),$(KBUILD_CFLAGS_32)) KBUILD_CFLAGS_32 += -m32 -msoft-float -mregparm=0 -fpic KBUILD_CFLAGS_32 += -fno-stack-protector KBUILD_CFLAGS_32 += $(call cc-option, -foptimize-sibling-calls)
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 26/28] x86, vdso: disable LTO only for vDSO
Quoted 6 lines · Sami Tolvanen
Remove the undefined
DISABLE_LTOflag from the vDSO, and filter outCC_FLAGS_LTOflags instead where needed. Note that while we could use Clang's LTO for the 64-bit vDSO, it won't add noticeable benefit for the small amount of C code.Signed-off-by Sami Tolvanen <[email protected]>
Moar DISABLE_LTO...
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerPATCH v2 27/28 x86, relocs: Ignore L4_PAGE_OFFSET relocations
In reply to Sami TolvanenL4_PAGE_OFFSET is a constant value, so don't warn about absolute relocations.
--- arch/x86/tools/relocs.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/tools/relocs.c +1 -0
@@ -47,6 +47,7 @@ static const char * const sym_regex_kernel[S_NSYMTYPES] = { [S_ABS] ="^(xen_irq_disable_direct_reloc$|" "xen_save_fl_direct_reloc$|" +"L4_PAGE_OFFSET|" "VDSO|" "__crc_)",
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 27/28] x86, relocs: Ignore L4_PAGE_OFFSET relocations
Quoted 4 lines · Sami Tolvanen
L4_PAGE_OFFSETis a constant value, so don't warn about absolute relocations.Signed-off-by Sami Tolvanen <[email protected]>
Any other details on this? I assume this is an ld.lld-ism. Any idea why this is only a problem under LTO? (Or is this an LLVM integrated assembler-ism?) Regardless, yes, let's nail it down:
Signature · 1 line
Kees Cook
Sami Tolvanen
maintainerRe: [PATCH v2 27/28] x86, relocs: Ignore L4_PAGE_OFFSET relocations
Quoted 9 lines · Kees Cook
Quoted 4 lines · Sami Tolvanen
L4_PAGE_OFFSETis a constant value, so don't warn about absolute relocations.Signed-off-by Sami Tolvanen <[email protected]>Any other details on this? I assume this is an ld.lld-ism. Any idea why this is only a problem under LTO? (Or is this an LLVM integrated assembler-ism?) Regardless, yes, let's nail it down:
With the LTO v1 series, LLD generated this relocation somewhere in the .init.data section, but only with LTO:
$ arch/x86/tools/relocs --abs-relocs vmlinux WARNING: Absolute relocations present Offset Info Type Sym.Value Sym.Name ffffffff828e7fe0 0000000100000001 R_X86_64_64 0000000000000111 L4_PAGE_OFFSET
It actually looks like this might not be a problem anymore with the current ToT kernel and the v2 series, but I'll do some more testing to confirm this and drop the patch from v3 if it's no longer needed.
Sami
Sami Tolvanen
maintainerPATCH v2 28/28 x86, build: allow LTO_CLANG and THINLTO to be selected
In reply to Sami TolvanenAllow CONFIG_LTO_CLANG and CONFIG_THINLTO to be enabled.
--- arch/x86/Kconfig | 2 ++ arch/x86/Makefile | 5 +++++ 2 files changed, 7 insertions(+)
arch/x86/Kconfig +2 -0
@@ -92,6 +92,8 @@ config X86 select ARCH_SUPPORTS_ACPI select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_NUMA_BALANCING if X86_64 + select ARCH_SUPPORTS_LTO_CLANG if X86_64 + select ARCH_SUPPORTS_THINLTO if X86_64 select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_QUEUED_RWLOCKS select ARCH_USE_QUEUED_SPINLOCKS
arch/x86/Makefile +5 -0
@@ -173,6 +173,11 @@ ifeq ($(ACCUMULATE_OUTGOING_ARGS), 1) KBUILD_CFLAGS += $(call cc-option,-maccumulate-outgoing-args,) endif +ifdef CONFIG_LTO_CLANG +KBUILD_LDFLAGS += -plugin-opt=-code-model=kernel \ + -plugin-opt=-stack-alignment=$(if $(CONFIG_X86_32),4,8) +endif + # Workaround for a gcc prelease that unfortunately was shipped in a suse release KBUILD_CFLAGS += -Wno-sign-compare #
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
Re: [PATCH v2 28/28] x86, build: allow LTO_CLANG and THINLTO to be selected
Quoted 3 lines · Sami Tolvanen
Allow
CONFIG_LTO_CLANGandCONFIG_THINLTOto be enabled.Signed-off-by Sami Tolvanen <[email protected]>
I think it might be worth detailing why these arguments aren't handled in the normal fashion under Clang's LTO. Regardless, it's needed to make it work, so:
Signature · 1 line
Kees Cook
Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenQuoted 2 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).
FWIW, this gives me a happy booting x86 kernel:
# cat /proc/version Linux version 5.9.0-rc3+ (kees@amarok) (clang version 12.0.0 (https://github.com/llvm/llvm-project.git db1ec04963cce70f2593e58cecac55f2e6accf52), LLD 12.0.0 (https://github.com/llvm/llvm-project.git db1ec04963cce70f2593e58cecac55f2e6accf52)) #1 SMP Thu Sep 3 15:54:14 PDT 2020 # zgrep 'LTO[_=]' /proc/config.gz CONFIG_LTO=y CONFIG_ARCH_SUPPORTS_LTO_CLANG=y CONFIG_ARCH_SUPPORTS_THINLTO=y CONFIG_THINLTO=y # CONFIG_LTO_NONE is not set CONFIG_LTO_CLANG=y
I'd like to find a way to get this series landing sanely. It has dependencies on fixes/features in a few trees, and it looks like it's been difficult to keep forward momentum on LTO while trying to simultaneously chase changes in those trees, especially since it means no one care carry LTO in -next without shared branches. To that end, I'd like to find a way forward where Sami doesn't have to keep carrying a couple dozen patches. :)
The fixes/features outside of, or partially overlapping, Masahiro's kbuild tree appear to be:
[PATCH v2 01/28] x86/boot/compressed: Disable relocation relaxation [PATCH v2 02/28] x86/asm: Replace __force_order with memory clobber [PATCH v2 03/28] lib/string.c: implement stpcpy
[PATCH v2 04/28] RAS/CEC: Fix cec_init() prototype
[PATCH v2 05/28] objtool: Add a pass for generating __mcount_loc [PATCH v2 06/28] objtool: Don't autodetect vmlinux.o
[PATCH v2 07/28] kbuild: add support for objtool mcount [PATCH v2 08/28] x86, build: use objtool mcount
[PATCH v2 17/28] PCI: Fix PREL32 relocations for LTO
[PATCH v2 20/28] efi/libstub: disable LTO
[PATCH v2 21/28] drivers/misc/lkdtm: disable LTO for rodata.o [PATCH v2 22/28] arm64: export CC_USING_PATCHABLE_FUNCTION_ENTRY [PATCH v2 23/28] arm64: vdso: disable LTO
[PATCH v2 24/28] KVM: arm64: disable LTO for the nVHE directory [PATCH v2 25/28] arm64: allow LTO_CLANG and THINLTO to be selected [PATCH v2 26/28] x86, vdso: disable LTO only for vDSO
[PATCH v2 27/28] x86, relocs: Ignore L4_PAGE_OFFSET relocations [PATCH v2 28/28] x86, build: allow LTO_CLANG and THINLTO to be selected
The distinctly kbuild patches are:
[PATCH v2 09/28] kbuild: add support for Clang LTO
[PATCH v2 10/28] kbuild: lto: fix module versioning
[PATCH v2 11/28] kbuild: lto: postpone objtool
[PATCH v2 12/28] kbuild: lto: limit inlining
[PATCH v2 13/28] kbuild: lto: merge module sections
[PATCH v2 14/28] kbuild: lto: remove duplicate dependencies from .mod files [PATCH v2 15/28] init: lto: ensure initcall ordering
[PATCH v2 16/28] init: lto: fix PREL32 relocations
[PATCH v2 18/28] modpost: lto: strip .lto from module names [PATCH v2 19/28] scripts/mod: disable LTO for empty.c
Patch 3 is in -mm and I expect it will land in the next rc (I hope, since it's needed universally for Clang builds).
Patch 4 is living in -tip, to appear shortly in -next, AFAICT?
I would expect 1 and 2 to appear in -tip soon, but I'm not sure?
For patches 5, 6, 7, and 8 I would expect them to normally go via -tip's objtool tree, but getting an Ack would let them land elsewhere.
Patch 17 I'd expect to normally go via Bjorn's tree, but he's given an Ack so it can live elsewhere without surprises. :)
Patches 19, 20, 21, 23, 24, 26 are all simple "just disable LTO" patches.
This leaves 9-16 and 18. Patches 10, 12, 14, 16, and 18 seem mostly "mechanical" in nature, leaving the bulk of the review on patches 9, 11, 13, and 15.
Masahiro, given the spread of dependent patches between 2 (or more?) -tip branches and -mm, how do you want to proceed? I wonder if it might be possible to create a shared branch to avoid merge headaches, and I (or -tip folks, or you) could carry patches 1-8 there so patches 9 and later could have a common base?
Thanks!
Signature · 1 line
Kees Cook
Nathan Chancellor
Tested-byRe: [PATCH v2 00/28] Add support for Clang LTO
Quoted 5 lines · Kees Cook
Quoted 2 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).Tested-by Kees Cook <[email protected]>
I have been continuously running this series on virtualized x86_64 (WSL2 on my home workstation) and bare metal arm64 (Raspberry Pi 4) with no major issues or regressions noticed.
Quoted 75 lines
FWIW, this gives me a happy booting x86 kernel:
# cat /proc/version Linux version 5.9.0-rc3+ (kees@amarok) (clang version 12.0.0 (https://github.com/llvm/llvm-project.git db1ec04963cce70f2593e58cecac55f2e6accf52), LLD 12.0.0 (https://github.com/llvm/llvm-project.git db1ec04963cce70f2593e58cecac55f2e6accf52)) #1 SMP Thu Sep 3 15:54:14 PDT 2020 # zgrep 'LTO[_=]' /proc/config.gz CONFIG_LTO=y CONFIG_ARCH_SUPPORTS_LTO_CLANG=y CONFIG_ARCH_SUPPORTS_THINLTO=y CONFIG_THINLTO=y # CONFIG_LTO_NONE is not set CONFIG_LTO_CLANG=yI'd like to find a way to get this series landing sanely. It has dependencies on fixes/features in a few trees, and it looks like it's been difficult to keep forward momentum on LTO while trying to simultaneously chase changes in those trees, especially since it means no one care carry LTO in -next without shared branches. To that end, I'd like to find a way forward where Sami doesn't have to keep carrying a couple dozen patches. :)
The fixes/features outside of, or partially overlapping, Masahiro's kbuild tree appear to be:
[PATCH v2 01/28] x86/boot/compressed: Disable relocation relaxation [PATCH v2 02/28] x86/asm: Replace
__force_orderwith memory clobber [PATCH v2 03/28]lib/string.c: implement stpcpy
[PATCH v2 04/28] RAS/CEC: Fixcec_init()prototype
[PATCH v2 05/28] objtool: Add a pass for generating__mcount_loc[PATCH v2 06/28] objtool: Don't autodetect vmlinux.o
[PATCH v2 07/28] kbuild: add support for objtool mcount [PATCH v2 08/28] x86, build: use objtool mcount
[PATCH v2 17/28] PCI: Fix PREL32 relocations for LTO
[PATCH v2 20/28] efi/libstub: disable LTO
[PATCH v2 21/28]drivers/misc/lkdtm: disable LTO for rodata.o [PATCH v2 22/28] arm64: exportCC_USING_PATCHABLE_FUNCTION_ENTRY[PATCH v2 23/28] arm64: vdso: disable LTO
[PATCH v2 24/28] KVM: arm64: disable LTO for the nVHE directory [PATCH v2 25/28] arm64: allowLTO_CLANGand THINLTO to be selected [PATCH v2 26/28] x86, vdso: disable LTO only for vDSO
[PATCH v2 27/28] x86, relocs: IgnoreL4_PAGE_OFFSETrelocations [PATCH v2 28/28] x86, build: allowLTO_CLANGand THINLTO to be selectedThe distinctly kbuild patches are:
[PATCH v2 09/28] kbuild: add support for Clang LTO
[PATCH v2 10/28] kbuild: lto: fix module versioning
[PATCH v2 11/28] kbuild: lto: postpone objtool
[PATCH v2 12/28] kbuild: lto: limit inlining
[PATCH v2 13/28] kbuild: lto: merge module sections
[PATCH v2 14/28] kbuild: lto: remove duplicate dependencies from .mod files [PATCH v2 15/28] init: lto: ensure initcall ordering
[PATCH v2 16/28] init: lto: fix PREL32 relocations
[PATCH v2 18/28] modpost: lto: strip .lto from module names [PATCH v2 19/28]scripts/mod: disable LTO forempty.cPatch 3 is in -mm and I expect it will land in the next rc (I hope, since it's needed universally for Clang builds).
Patch 4 is living in -tip, to appear shortly in -next, AFAICT?
I would expect 1 and 2 to appear in -tip soon, but I'm not sure?
For patches 5, 6, 7, and 8 I would expect them to normally go via -tip's objtool tree, but getting an Ack would let them land elsewhere.
Patch 17 I'd expect to normally go via Bjorn's tree, but he's given an Ack so it can live elsewhere without surprises. :)
Patches 19, 20, 21, 23, 24, 26 are all simple "just disable LTO" patches.
This leaves 9-16 and 18. Patches 10, 12, 14, 16, and 18 seem mostly "mechanical" in nature, leaving the bulk of the review on patches 9, 11, 13, and 15.
Quoted 11 lines
Masahiro, given the spread of dependent patches between 2 (or more?) -tip branches and -mm, how do you want to proceed? I wonder if it might be possible to create a shared branch to avoid merge headaches, and I (or -tip folks, or you) could carry patches 1-8 there so patches 9 and later could have a common base?
Thanks!
Signature · 1 line
Kees Cook
For what it's worth, the static call series that is in -tip and about to land in -next conflicts relatively heavy with this. There are fairly innocuous conflicts in some objtool files but two contextual changes are needed to keep things building. It probably makes sense for most if not all of this to live in -tip with acks. Ideally, if the stpcpy patch gets merged into an -rc, this can just be based on that.
check.c:556:80: error: too few arguments to function call, expected 5, have 4
sec = elf_create_section(file->elf, "__mcount_loc", sizeof(unsigned long), idx);
~~~~~~~~~~~~~~~~~~ ^
./elf.h:124:17: note: 'elf_create_section' declared here
struct section *elf_create_section(struct elf *elf, const char *name, unsigned int sh_flags, size_t entsize, int nr);
^1 error generated.
kernel/static_call.c:438:16: error: returning 'void' from a function with incompatible result type 'int' early_initcall(static_call_init);
~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~include/linux/init.h:268:47: note: expanded from macro 'early_initcall'
#define early_initcall(fn) __define_initcall(fn, early)
~~~~~~~~~~~~~~~~~~^~~~~~~~~~
include/linux/init.h:261:54: note: expanded from macro '__define_initcall'
#define __define_initcall(fn, id) ___define_initcall(fn, id, .initcall##id)
~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
include/linux/init.h:259:20: note: expanded from macro '___define_initcall'
__unique_initcall(fn, id, __sec, __initcall_id(fn))
~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
include/linux/init.h:253:22: note: expanded from macro '__unique_initcall'
____define_initcall(fn, \
~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
include/linux/init.h:241:33: note: expanded from macro '____define_initcall'
__define_initcall_stub(__stub, fn) \
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
include/linux/init.h:226:10: note: expanded from macro '__define_initcall_stub'
return fn(); \
^~~~1 error generated.
Below is what I ended up with for fixes.
Cheers,
Nathan
include/linux/static_call.h +1 -1
@@ -136,7 +136,7 @@ extern void arch_static_call_transform(void *site, void *tramp, void *func, bool #ifdef CONFIG_HAVE_STATIC_CALL_INLINE -extern void __init static_call_init(void); +extern int __init static_call_init(void); struct static_call_mod { struct static_call_mod *next;
kernel/static_call.c +3 -2
@@ -410,12 +410,12 @@ int static_call_text_reserved(void *start, void *end)return __static_call_mod_text_reserved (start, end); } -void __init static_call_init (void ) +int __init static_call_init (void ) {int ret;if (static_call_initialized) -return ; +return 0 ;cpus_read_lock ();static_call_lock ();
@@ -434,6 +434,7 @@ void __init static_call_init(void)#ifdef CONFIG_MODULES register_module_notifier (&static_call_module_nb);#endif +return 0 ; }early_initcall (static_call_init);
tools/objtool/check.c +1 -1
@@ -553,7 +553,7 @@ static int create_mcount_loc_sections(struct objtool_file *file)list_for_each_entry (insn, &file->mcount_loc_list, mcount_loc_node) idx++; - sec =elf_create_section (file->elf,"__mcount_loc" ,sizeof (unsigned long ), idx); + sec =elf_create_section (file->elf,"__mcount_loc" ,0 ,sizeof (unsigned long ), idx);if (!sec)return -1 ;
Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenQuoted 4 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).
[...]
base-commit:e28f0104343d0c132fa37f479870c9e43355fee4
And if you're not a b4 user, this tree can be found at either of these places:
https://github.com/samitolvanen/linux/commits/clang-lto
git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux.git kspp/sami/lto/v2
Signature · 1 line
Kees Cook
Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenQuoted 14 lines · Sami Tolvanen' via Clang Built Linux
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Quoted 9 lines
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
I jumped to Sami's clang-cfi Git tree which includes clang-lto v2.
My LLVM toolchain is version 11.0.0.0-rc2+ more precisely git 97ac9e82002d6b12831ca2c78f739cca65a4fa05.
If this is OK, feel free to add my...
- Sedat -
[1] https://github.com/samitolvanen/linux/commits/clang-cfi
Quoted 111 lines
---
Changes in v2:- Fixed -Wmissing-prototypes warnings with W=1.
- Dropped cc-option from -fsplit-lto-unit and added .thinlto-cache scrubbing to make distclean.
- Added a comment about Clang >=11 being required.
- Added a patch to disable LTO for the arm64 KVM nVHE code.
- Disabled objtool's noinstr validation with LTO unless enabled.
- Included Peter's proposed objtool mcount patch in the series and replaced recordmcount with the objtool pass to avoid whitelisting relocations that are not calls.
- Updated several commit messages with better explanations.
Arvind Sankar (2):
x86/boot/compressed: Disable relocation relaxation x86/asm: Replace__force_orderwith memory clobberLuca Stefani (1):
RAS/CEC: Fixcec_init()prototypeNick Desaulniers (1):
lib/string.c: implement stpcpyPeter Zijlstra (1):
objtool: Add a pass for generating__mcount_locSami Tolvanen (23):
objtool: Don't autodetect vmlinux.o
kbuild: add support for objtool mcount
x86, build: use objtool mcount
kbuild: add support for Clang LTO
kbuild: lto: fix module versioning
kbuild: lto: postpone objtool
kbuild: lto: limit inlining
kbuild: lto: merge module sections
kbuild: lto: remove duplicate dependencies from .mod files
init: lto: ensure initcall ordering
init: lto: fix PREL32 relocations
PCI: Fix PREL32 relocations for LTO
modpost: lto: strip .lto from module namesscripts/mod: disable LTO forempty.cefi/libstub: disable LTO
drivers/misc/lkdtm: disable LTO for rodata.o
arm64: exportCC_USING_PATCHABLE_FUNCTION_ENTRY
arm64: vdso: disable LTO
KVM: arm64: disable LTO for the nVHE directory
arm64: allowLTO_CLANGand THINLTO to be selected x86, vdso: disable LTO only for vDSO
x86, relocs: IgnoreL4_PAGE_OFFSETrelocations x86, build: allowLTO_CLANGand THINLTO to be selected.gitignore | 1 + Makefile | 65 ++++++- arch/Kconfig | 67 +++++++ arch/arm64/Kconfig | 2 + arch/arm64/Makefile | 1 + arch/arm64/kernel/vdso/Makefile | 4 +- arch/arm64/kvm/hyp/nvhe/Makefile | 4 +- arch/x86/Kconfig | 3 + arch/x86/Makefile | 5 + arch/x86/boot/compressed/Makefile | 2 + arch/x86/boot/compressed/pgtable_64.c | 9 - arch/x86/entry/vdso/Makefile | 5 +- arch/x86/include/asm/special_insns.h | 28 +-- arch/x86/kernel/cpu/common.c | 4 +- arch/x86/tools/relocs.c | 1 + drivers/firmware/efi/libstub/Makefile | 2 + drivers/misc/lkdtm/Makefile | 1 + drivers/ras/cec.c | 9 +- include/asm-generic/vmlinux.lds.h | 11 +- include/linux/init.h | 79 +++++++- include/linux/pci.h | 19 +- kernel/trace/Kconfig | 5 + lib/string.c | 24 +++ scripts/Makefile.build | 55 +++++- scripts/Makefile.lib | 6 +- scripts/Makefile.modfinal | 31 ++- scripts/Makefile.modpost | 26 ++- scripts/generate_initcall_order.pl | 270 ++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 94 ++++++++- scripts/mod/Makefile | 1 + scripts/mod/modpost.c | 16 +- scripts/mod/modpost.h | 9 + scripts/mod/sumversion.c | 6 +- scripts/module-lto.lds | 26 +++ tools/objtool/builtin-check.c | 13 +- tools/objtool/builtin.h | 2 +- tools/objtool/check.c | 83 ++++++++ tools/objtool/check.h | 1 + tools/objtool/objtool.h | 1 + 39 files changed, 883 insertions(+), 108 deletions(-) create mode 100755 scripts/generate_initcall_order.pl create mode 100644 scripts/module-lto.ldsbase-commit:
e28f0104343d0c132fa37f479870c9e43355fee4--
2.28.0.402.g5ffc5be6b7-goog--
You received this message because you are subscribed to the Google Groups "Clang Built Linux" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/clang-built-linux/20200903203053.3411268-1-samitolvanen%40google.com.
[email protected]
maintainerRe: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenPlease don't nest series!
Start a new thread for every posting.
Re: [PATCH v2 00/28] Add support for Clang LTO
Quoted 6 lines · On Fri, Sep 4, 2020 at 10:55 AM <[email protected]> wrote:
Please don't nest series!
Start a new thread for every posting.
You are right Peter, my apologies.
- Sedat -
Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenQuoted 14 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Quoted 9 lines
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
I still do not understand how this patch set works. (only me?)
Please let me ask fundamental questions.
I applied this series on top of Linus' tree,
and compiled for ARCH=arm64.
I compared the kernel size with/without LTO.
[1] No LTO (arm64 defconfig, CONFIG_LTO_NONE)
$ llvm-size vmlinux text data bss dec hex filename 15848692 10099449 493060 26441201 19375f1 vmlinux
[2] Clang LTO (arm64 defconfig + CONFIG_LTO_CLANG)
$ llvm-size vmlinux text data bss dec hex filename 15906864 10197445 490804 26595113 195cf29 vmlinux
I compared the size of raw binary, arch/arm64/boot/Image. Its size increased too.
So, in my experiment, enabling CONFIG_LTO_CLANG
increases the kernel size.
Is this correct?
One more thing, could you teach me
how Clang LTO optimizes the code against
relocatable objects?
When I learned Clang LTO first, I read this document:
https://llvm.org/docs/LinkTimeOptimization.html
It is easy to confirm the final executable
does not contain foo2, foo3...
In contrast to userspace programs,
kernel modules are basically relocatable objects.
Does Clang drop unused symbols from relocatable objects? If so, how?
I implemented an example module (see the attachment), and checked the symbols.
Nothing was dropped.
The situation is the same for build-in
because LTO is run against vmlinux.o, which is
relocatable as well.
--
Best Regards
Masahiro Yamada
From c1dc646f73bd948edbf0c4a7f1baa93ecf8c208e Mon Sep 17 00:00:00 2001
From: Masahiro Yamada <[email protected]>
Date: Sun, 6 Sep 2020 08:11:32 +0900
Subject: [PATCH] lto: test module
Here is a great example for LTO:
https://llvm.org/docs/LinkTimeOptimization.html
LTO removes foo2() and foo3() from the final executable file, "main". (and foo4() is also dropped if you pass -flto to main.c)
This patch integrates the example code into a kernel module.
a.c -> kernel/lto-test-a.c main.c -> kernel/lto-test-main.c
Of course, I replaced printf() with printk().
I applied this test patch on top of Sami's v2:
https://patchwork.kernel.org/project/linux-kbuild/list/?series=343153
I compiled arm64 defconfig + CONFIG_LTO_CLANG.
This is the result:
$ aarch64-linux-gnu-nm kernel/lto-test.ko
0000000000000010 T foo1
0000000000000000 T foo2
000000000000004c T foo4
0000000000000000 B i.llvm.7710645642085602891
0000000000000000 r __kstrtab_lto_test_main
000000000000000e r __kstrtabns_lto_test_main
0000000000000000 r __ksymtab_lto_test_main
0000000000000068 T lto_test_main
0000000000000000 r _note_7
U printk
0000000000000000 R .str.llvm.887650332484512380
0000000000000000 D __this_module
0000000000000063 r __UNIQUE_ID_depends254
000000000000005a r __UNIQUE_ID_intree253
000000000000004c r __UNIQUE_ID_name252
0000000000000000 r __UNIQUE_ID_vermagic251Modules are relocatable objects, not executables. How can clang LTO know unreachable symbols are really unreachable?
According to the result above, foo2 is remaining.
The behavior is the same for obj-y because LTO is run against vmlinux.o, which is a relocatable ELF.
--- kernel/Makefile | 3 +++ kernel/lto-test-a.c | 22 ++++++++++++++++++++++ kernel/lto-test-a.h | 3 +++ kernel/lto-test-main.c | 12 ++++++++++++ 4 files changed, 40 insertions(+) create mode 100644 kernel/lto-test-a.c create mode 100644 kernel/lto-test-a.h create mode 100644 kernel/lto-test-main.c
kernel/Makefile +3 -0
@@ -147,3 +147,6 @@ $(obj)/kheaders_data.tar.xz: FORCE $(call cmd,genikh) clean-files := kheaders_data.tar.xz kheaders.md5 + +obj-m += lto-test.o +lto-test-objs := lto-test-a.o lto-test-main.o
kernel/lto-test-a.c new file +22 -0
@@ -0,0 +1,22 @@ +#include "lto-test-a.h" + +static signed int i =0 ; + +void foo2 (void ) { + i =-1 ; +} + +static int foo3 (void ) { +foo4 (); +return 10 ; +} + +int foo1 (void ) { +int data =0 ; + +if (i <0 ) + data =foo3 (); + + data = data +42 ; +return data; +}
kernel/lto-test-a.h new file +3 -0
@@ -0,0 +1,3 @@ +extern int foo1 (void ); +extern void foo2 (void ); +extern void foo4 (void );
kernel/lto-test-main.c new file +12 -0
@@ -0,0 +1,12 @@ +#include <linux/module.h> +#include <linux/export.h> +#include "lto-test-a.h" + +void foo4 (void ) { +printk ("Hi\n" ); +} + +int lto_test_main (void ) { +return foo1 (); +} +EXPORT_SYMBOL (lto_test_main);
Signature · 1 line
2.25.1
Sami Tolvanen
maintainerRe: [PATCH v2 00/28] Add support for Clang LTO
Quoted 55 lines · Masahiro Yamada
Quoted 14 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Quoted 9 lines
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
I still do not understand how this patch set works. (only me?)
Please let me ask fundamental questions.
I applied this series on top of Linus' tree,
and compiled for ARCH=arm64.I compared the kernel size with/without LTO.
[1] No LTO (arm64 defconfig,
CONFIG_LTO_NONE)$ llvm-size vmlinux text data bss dec hex filename 15848692 10099449 493060 26441201 19375f1 vmlinux[2] Clang LTO (arm64 defconfig +
CONFIG_LTO_CLANG)$ llvm-size vmlinux text data bss dec hex filename 15906864 10197445 490804 26595113 195cf29 vmlinux
Quoted 8 lines
I compared the size of raw binary,
arch/arm64/boot/Image. Its size increased too.So, in my experiment, enabling
CONFIG_LTO_CLANG
increases the kernel size.
Is this correct?
Yes. LTO does produce larger binaries, mostly due to function inlining between translation units, I believe. The compiler people can probably give you a more detailed answer here. Without -mllvm -import-instr-limit, the binaries would be even larger.
Quoted 14 lines
One more thing, could you teach me
how Clang LTO optimizes the code against
relocatable objects?When I learned Clang LTO first, I read this document:
https://llvm.org/docs/LinkTimeOptimization.htmlIt is easy to confirm the final executable
does not contain foo2, foo3...
Quoted 5 lines
In contrast to userspace programs,
kernel modules are basically relocatable objects.Does Clang drop unused symbols from relocatable objects? If so, how?
I don't think the compiler can legally drop global symbols from relocatable objects, but it can rename and possibly even drop static functions. This is why we need global wrappers for initcalls, for example, to have stable symbol names.
Sami
Re: [PATCH v2 00/28] Add support for Clang LTO
Quoted 88 lines · Sami Tolvanen
Quoted 55 lines · Masahiro Yamada
Quoted 14 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Quoted 9 lines
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
I still do not understand how this patch set works. (only me?)
Please let me ask fundamental questions.
I applied this series on top of Linus' tree,
and compiled for ARCH=arm64.I compared the kernel size with/without LTO.
[1] No LTO (arm64 defconfig,
CONFIG_LTO_NONE)$ llvm-size vmlinux text data bss dec hex filename 15848692 10099449 493060 26441201 19375f1 vmlinux[2] Clang LTO (arm64 defconfig +
CONFIG_LTO_CLANG)$ llvm-size vmlinux text data bss dec hex filename 15906864 10197445 490804 26595113 195cf29 vmlinuxQuoted 8 lines
I compared the size of raw binary,
arch/arm64/boot/Image. Its size increased too.So, in my experiment, enabling
CONFIG_LTO_CLANG
increases the kernel size.
Is this correct?Yes. LTO does produce larger binaries, mostly due to function inlining between translation units, I believe. The compiler people can probably give you a more detailed answer here. Without -mllvm -import-instr-limit, the binaries would be even larger.
Quoted 17 lines
One more thing, could you teach me
how Clang LTO optimizes the code against
relocatable objects?When I learned Clang LTO first, I read this document:
https://llvm.org/docs/LinkTimeOptimization.htmlIt is easy to confirm the final executable
does not contain foo2, foo3...In contrast to userspace programs,
kernel modules are basically relocatable objects.
Quoted 6 lines
Quoted 2 lines
Does Clang drop unused symbols from relocatable objects? If so, how?
I don't think the compiler can legally drop global symbols from relocatable objects, but it can rename and possibly even drop static functions.
Compilers can drop static functions without LTO. Rather, it is a compiler warning (-Wunused-function), so the code should be cleaned up.
Quoted 4 lines
This is why we need global wrappers for initcalls, for example, to have stable symbol names.
Sami
At first, I thought the motivation of LTO
was to remove unused global symbols, and
to perform further optimization.
It is true for userspace programs.
In fact, the example of
https://llvm.org/docs/LinkTimeOptimization.html
produces a smaller binary.
In contrast, this patch set produces a bigger kernel because LTO cannot remove any unused symbol.
So, I do not understand what the benefit is.
Is inlining beneficial?
I am not sure.
Documentation/process/coding-style.rst
"15) The inline disease"
mentions that inlining is not always
a good thing.
As a whole, I still do not understand
the motivation of this patch set.
Signature · 2 lines
Best Regards Masahiro Yamada
Sami Tolvanen
maintainerRe: [PATCH v2 00/28] Add support for Clang LTO
Quoted 131 lines · Masahiro Yamada
Quoted 88 lines · Sami Tolvanen
Quoted 55 lines · Masahiro Yamada
Quoted 14 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Quoted 9 lines
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
I still do not understand how this patch set works. (only me?)
Please let me ask fundamental questions.
I applied this series on top of Linus' tree,
and compiled for ARCH=arm64.I compared the kernel size with/without LTO.
[1] No LTO (arm64 defconfig,
CONFIG_LTO_NONE)$ llvm-size vmlinux text data bss dec hex filename 15848692 10099449 493060 26441201 19375f1 vmlinux[2] Clang LTO (arm64 defconfig +
CONFIG_LTO_CLANG)$ llvm-size vmlinux text data bss dec hex filename 15906864 10197445 490804 26595113 195cf29 vmlinuxQuoted 8 lines
I compared the size of raw binary,
arch/arm64/boot/Image. Its size increased too.So, in my experiment, enabling
CONFIG_LTO_CLANG
increases the kernel size.
Is this correct?Yes. LTO does produce larger binaries, mostly due to function inlining between translation units, I believe. The compiler people can probably give you a more detailed answer here. Without -mllvm -import-instr-limit, the binaries would be even larger.
Quoted 17 lines
One more thing, could you teach me
how Clang LTO optimizes the code against
relocatable objects?When I learned Clang LTO first, I read this document:
https://llvm.org/docs/LinkTimeOptimization.htmlIt is easy to confirm the final executable
does not contain foo2, foo3...In contrast to userspace programs,
kernel modules are basically relocatable objects.Quoted 6 lines
Quoted 2 lines
Does Clang drop unused symbols from relocatable objects? If so, how?
I don't think the compiler can legally drop global symbols from relocatable objects, but it can rename and possibly even drop static functions.
Compilers can drop static functions without LTO. Rather, it is a compiler warning (-Wunused-function), so the code should be cleaned up.
Quoted 4 lines
This is why we need global wrappers for initcalls, for example, to have stable symbol names.
Sami
At first, I thought the motivation of LTO
was to remove unused global symbols, and
to perform further optimization.It is true for userspace programs.
In fact, the example of
https://llvm.org/docs/LinkTimeOptimization.html
produces a smaller binary.In contrast, this patch set produces a bigger kernel because LTO cannot remove any unused symbol.
So, I do not understand what the benefit is.
Is inlining beneficial?
I am not sure.
Quoted 8 lines
Documentation/process/coding-style.rst
"15) The inline disease"
mentions that inlining is not always
a good thing.As a whole, I still do not understand
the motivation of this patch set.
Clang produces faster code with LTO even if unused functions are not removed, and I'm not sure how many unused globals there really are in the kernel that aren't exported for modules. However, as I mentioned in the cover letter, we also need LTO for Control-Flow Integrity (CFI), which we have used in Pixel kernels for a couple of years now, and plan to use in more Android devices in future:
https://clang.llvm.org/docs/ControlFlowIntegrity.html
Sami
Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Masahiro YamadaQuoted 24 lines · Masahiro Yamada
Quoted 23 lines · Sami Tolvanen
Quoted 20 lines · Masahiro Yamada
Quoted 3 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).[...]
One more thing, could you teach me how Clang LTO optimizes the code against relocatable objects?When I learned Clang LTO first, I read this document:
https://llvm.org/docs/LinkTimeOptimization.htmlIt is easy to confirm the final executable does not contain foo2, foo3...
In contrast to userspace programs,
kernel modules are basically relocatable objects.Does Clang drop unused symbols from relocatable objects? If so, how?
Quoted 7 lines
Quoted 3 lines
I don't think the compiler can legally drop global symbols from relocatable objects, but it can rename and possibly even drop static functions.
Compilers can drop static functions without LTO. Rather, it is a compiler warning (-Wunused-function), so the code should be cleaned up.
Right -- I think you're both saying the same thing. Unused static functions can be dropped (modulo a warning) in both regular and LTO builds.
Quoted 3 lines
At first, I thought the motivation of LTO was to remove unused global symbols, and
to perform further optimization.
One of LTO's benefits is the performance optimizations, but that's not the driving motivation for it here. The performance optimizations are possible because LTO provides the compiler with a view of the entire built-in portion of the kernel (i.e. not shared objects). That "visible all at once" state is the central concern because CFI (Control Flow Integrity, the driving motivation for this series) needs it in the same way that the performance optimization passes need it.
i.e. to gain CFI coverage, LTO is required. Since LTO is a distinct first step independent of CFI, it was split out to be upstreamed while fixes for CFI continued to land independently[1]. Once LTO is landed, CFI comes next.
Quoted 7 lines
In contrast, this patch set produces a bigger kernel because LTO cannot remove any unused symbol.
So, I do not understand what the benefit is.
Is inlining beneficial?
I am not sure.
This is just a side-effect of LTO. As Sami mentions, it's entirely tunable, and that tuning was chosen based on measurements made for the kernel being built with LTO[2].
Quoted 2 lines
As a whole, I still do not understand
the motivation of this patch set.
It is a prerequisite for CFI, and CFI has been protecting *mumble*billion Android device kernels against code-reuse attacks for the last 2ish years[3]. I want this available for the entire Linux ecosystem, not just Android; it is a strong security flaw mitigation technique.
I hope that helps explain it!
-Kees
[1] for example, these are some:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/log/?qt=grep&q=Control+Flow+Integrity
[2] https://lore.kernel.org/lkml/[email protected]/T/#m6b576c3af79bdacada10f21651a2b02d33a4e32e
[3] https://android-developers.googleblog.com/2018/10/control-flow-integrity-in-android-kernel.html
Signature · 1 line
Kees Cook
Nick Desaulniers
reviewerRe: [PATCH v2 00/28] Add support for Clang LTO
In reply to Sami TolvanenHey Ian,
It was nice to meet you at Linux plumbers. You might want to take a look at this series. It implements builds of the Linux kernel with LTO. It would be good to get eyes on it and help review it from folks working on this from the GCC angle. The series has some configs that split where Clang specific changes need to be made; it might be of interest to think about what would the similar changes be needed for GCC. Also, congrats on your LWN article!
https://lwn.net/Articles/830300/
Quoted 130 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
---
Changes in v2:- Fixed -Wmissing-prototypes warnings with W=1.
- Dropped cc-option from -fsplit-lto-unit and added .thinlto-cache scrubbing to make distclean.
- Added a comment about Clang >=11 being required.
- Added a patch to disable LTO for the arm64 KVM nVHE code.
- Disabled objtool's noinstr validation with LTO unless enabled.
- Included Peter's proposed objtool mcount patch in the series and replaced recordmcount with the objtool pass to avoid whitelisting relocations that are not calls.
- Updated several commit messages with better explanations.
Arvind Sankar (2):
x86/boot/compressed: Disable relocation relaxation x86/asm: Replace__force_orderwith memory clobberLuca Stefani (1):
RAS/CEC: Fixcec_init()prototypeNick Desaulniers (1):
lib/string.c: implement stpcpyPeter Zijlstra (1):
objtool: Add a pass for generating__mcount_locSami Tolvanen (23):
objtool: Don't autodetect vmlinux.o
kbuild: add support for objtool mcount
x86, build: use objtool mcount
kbuild: add support for Clang LTO
kbuild: lto: fix module versioning
kbuild: lto: postpone objtool
kbuild: lto: limit inlining
kbuild: lto: merge module sections
kbuild: lto: remove duplicate dependencies from .mod files
init: lto: ensure initcall ordering
init: lto: fix PREL32 relocations
PCI: Fix PREL32 relocations for LTO
modpost: lto: strip .lto from module namesscripts/mod: disable LTO forempty.cefi/libstub: disable LTO
drivers/misc/lkdtm: disable LTO for rodata.o
arm64: exportCC_USING_PATCHABLE_FUNCTION_ENTRY
arm64: vdso: disable LTO
KVM: arm64: disable LTO for the nVHE directory
arm64: allowLTO_CLANGand THINLTO to be selected x86, vdso: disable LTO only for vDSO
x86, relocs: IgnoreL4_PAGE_OFFSETrelocations x86, build: allowLTO_CLANGand THINLTO to be selected.gitignore | 1 + Makefile | 65 ++++++- arch/Kconfig | 67 +++++++ arch/arm64/Kconfig | 2 + arch/arm64/Makefile | 1 + arch/arm64/kernel/vdso/Makefile | 4 +- arch/arm64/kvm/hyp/nvhe/Makefile | 4 +- arch/x86/Kconfig | 3 + arch/x86/Makefile | 5 + arch/x86/boot/compressed/Makefile | 2 + arch/x86/boot/compressed/pgtable_64.c | 9 - arch/x86/entry/vdso/Makefile | 5 +- arch/x86/include/asm/special_insns.h | 28 +-- arch/x86/kernel/cpu/common.c | 4 +- arch/x86/tools/relocs.c | 1 + drivers/firmware/efi/libstub/Makefile | 2 + drivers/misc/lkdtm/Makefile | 1 + drivers/ras/cec.c | 9 +- include/asm-generic/vmlinux.lds.h | 11 +- include/linux/init.h | 79 +++++++- include/linux/pci.h | 19 +- kernel/trace/Kconfig | 5 + lib/string.c | 24 +++ scripts/Makefile.build | 55 +++++- scripts/Makefile.lib | 6 +- scripts/Makefile.modfinal | 31 ++- scripts/Makefile.modpost | 26 ++- scripts/generate_initcall_order.pl | 270 ++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 94 ++++++++- scripts/mod/Makefile | 1 + scripts/mod/modpost.c | 16 +- scripts/mod/modpost.h | 9 + scripts/mod/sumversion.c | 6 +- scripts/module-lto.lds | 26 +++ tools/objtool/builtin-check.c | 13 +- tools/objtool/builtin.h | 2 +- tools/objtool/check.c | 83 ++++++++ tools/objtool/check.h | 1 + tools/objtool/objtool.h | 1 + 39 files changed, 883 insertions(+), 108 deletions(-) create mode 100755 scripts/generate_initcall_order.pl create mode 100644 scripts/module-lto.ldsbase-commit:
e28f0104343d0c132fa37f479870c9e43355fee4--
2.28.0.402.g5ffc5be6b7-goog
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH v2 00/28] Add support for Clang LTO
Quoted 10 lines · Nick Desaulniers' via Clang Built Linux
Hey Ian,
It was nice to meet you at Linux plumbers. You might want to take a look at this series. It implements builds of the Linux kernel with LTO. It would be good to get eyes on it and help review it from folks working on this from the GCC angle. The series has some configs that split where Clang specific changes need to be made; it might be of interest to think about what would the similar changes be needed for GCC. Also, congrats on your LWN article!
https://lwn.net/Articles/830300/
FYI.
Some people may remember GCC LTO was posted in 2014 (and rejected by Linus).
https://lore.kernel.org/linux-kbuild/[email protected]/
In my understanding, GCC LTO does not work for relocatable objects because GNU linker is agnostic about LTO.
GCC LTO was implemented in the final link stage (i.e. vmlinux) by using $(CC) as a linker driver.
On the other hand, Clang LTO, in this series implementation, works in the pre-mospost stage (i.e. vmlinux.o).
--
Best Regards
Masahiro Yamada
RE: [EXTERNAL] Re: [PATCH v2 00/28] Add support for Clang LTO
In reply to Nick DesaulniersHi, Nick. Thanks for reaching out again. I'm excited to see other groups taking an interest in LTO and PGO for Linux. CFI for the kernel sounds like a huge deal, nice!
I'd like to introduce you to @Russell Hadley. Russell wears a couple of hats right now, he's both the group manager for the MSVC code generation team as well as the (interim) team for the Linux tools team that i built and lead last year. He has inherited the various efforts my team was working on and is the right contact going forward to collaborate on Linux compiler and tools efforts.
ian Bearman
Principal Software Engineering Manager
Microsoft Visual C++ Team: ML Optimization & Code Generation #BlackLivesMatter
/* Making your code faster, smaller, smarter! */
-----Original Message-----
From: Nick Desaulniers <[email protected]>
Sent: Thursday, September 10, 2020 10:46 AM
To: Ian Bearman <[email protected]>
Cc: clang-built-linux <[email protected]>; LKML <[email protected]>; Sami Tolvanen <[email protected]>
Subject: [EXTERNAL] Re: [PATCH v2 00/28] Add support for Clang LTO
Hey Ian,
It was nice to meet you at Linux plumbers. You might want to take a look at this series. It implements builds of the Linux kernel with LTO. It would be good to get eyes on it and help review it from folks working on this from the GCC angle. The series has some configs that split where Clang specific changes need to be made; it might be of interest to think about what would the similar changes be needed for GCC. Also, congrats on your LWN article!
https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Flwn.net%2FArticles%2F830300%2F&data=02%7C01%7Cian.bearman%40microsoft.com%7C9adc842104f640d3ebb308d855b17221%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637353568334933757&sdata=uM6%2BGj5z0gNAuIravVWOeVeIVsRI5YaPIJqB8qYsZ94%3D&reserved=0
Quoted 126 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
---
Changes in v2:- Fixed -Wmissing-prototypes warnings with W=1.
- Dropped cc-option from -fsplit-lto-unit and added .thinlto-cache scrubbing to make distclean.
- Added a comment about Clang >=11 being required.
- Added a patch to disable LTO for the arm64 KVM nVHE code.
- Disabled objtool's noinstr validation with LTO unless enabled.
- Included Peter's proposed objtool mcount patch in the series and replaced recordmcount with the objtool pass to avoid whitelisting relocations that are not calls.
- Updated several commit messages with better explanations.
Arvind Sankar (2):
x86/boot/compressed: Disable relocation relaxation x86/asm: Replace__force_orderwith memory clobberLuca Stefani (1):
RAS/CEC: Fixcec_init()prototypeNick Desaulniers (1):
lib/string.c: implement stpcpyPeter Zijlstra (1):
objtool: Add a pass for generating__mcount_locSami Tolvanen (23):
objtool: Don't autodetect vmlinux.o
kbuild: add support for objtool mcount
x86, build: use objtool mcount
kbuild: add support for Clang LTO
kbuild: lto: fix module versioning
kbuild: lto: postpone objtool
kbuild: lto: limit inlining
kbuild: lto: merge module sections
kbuild: lto: remove duplicate dependencies from .mod files
init: lto: ensure initcall ordering
init: lto: fix PREL32 relocations
PCI: Fix PREL32 relocations for LTO
modpost: lto: strip .lto from module namesscripts/mod: disable LTO forempty.cefi/libstub: disable LTO
drivers/misc/lkdtm: disable LTO for rodata.o
arm64: exportCC_USING_PATCHABLE_FUNCTION_ENTRY
arm64: vdso: disable LTO
KVM: arm64: disable LTO for the nVHE directory
arm64: allowLTO_CLANGand THINLTO to be selected x86, vdso: disable LTO only for vDSO
x86, relocs: IgnoreL4_PAGE_OFFSETrelocations x86, build: allowLTO_CLANGand THINLTO to be selected.gitignore | 1 + Makefile | 65 ++++++- arch/Kconfig | 67 +++++++ arch/arm64/Kconfig | 2 + arch/arm64/Makefile | 1 + arch/arm64/kernel/vdso/Makefile | 4 +- arch/arm64/kvm/hyp/nvhe/Makefile | 4 +- arch/x86/Kconfig | 3 + arch/x86/Makefile | 5 + arch/x86/boot/compressed/Makefile | 2 + arch/x86/boot/compressed/pgtable_64.c | 9 - arch/x86/entry/vdso/Makefile | 5 +- arch/x86/include/asm/special_insns.h | 28 +-- arch/x86/kernel/cpu/common.c | 4 +- arch/x86/tools/relocs.c | 1 + drivers/firmware/efi/libstub/Makefile | 2 + drivers/misc/lkdtm/Makefile | 1 + drivers/ras/cec.c | 9 +- include/asm-generic/vmlinux.lds.h | 11 +- include/linux/init.h | 79 +++++++- include/linux/pci.h | 19 +- kernel/trace/Kconfig | 5 + lib/string.c | 24 +++ scripts/Makefile.build | 55 +++++- scripts/Makefile.lib | 6 +- scripts/Makefile.modfinal | 31 ++- scripts/Makefile.modpost | 26 ++- scripts/generate_initcall_order.pl | 270 ++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 94 ++++++++- scripts/mod/Makefile | 1 + scripts/mod/modpost.c | 16 +- scripts/mod/modpost.h | 9 + scripts/mod/sumversion.c | 6 +- scripts/module-lto.lds | 26 +++ tools/objtool/builtin-check.c | 13 +- tools/objtool/builtin.h | 2 +- tools/objtool/check.c | 83 ++++++++ tools/objtool/check.h | 1 + tools/objtool/objtool.h | 1 + 39 files changed, 883 insertions(+), 108 deletions(-) create mode 100755 scripts/generate_initcall_order.pl create mode 100644 scripts/module-lto.lds
Quoted 4 lines
base-commit:
e28f0104343d0c132fa37f479870c9e43355fee4--
2.28.0.402.g5ffc5be6b7-goog
--
Thanks,
~Nick Desaulniers
Nick Desaulniers
reviewerRe: [EXTERNAL] Re: [PATCH v2 00/28] Add support for Clang LTO
Quoted 2 lines · Ian Bearman
Hi, Nick. Thanks for reaching out again. I'm excited to see other groups taking an interest in LTO and PGO for Linux. CFI for the kernel sounds like a huge deal, nice!
Yes, CFI is quite nice. There are some hardware extensions in the works, but CFI has some additional coverage implemented in software. That said, all new compiler technologies have bugs, and expose issues in various code bases.
Quoted 2 lines
I'd like to introduce you to @Russell Hadley. Russell wears a couple of hats right now, he's both the group manager for the MSVC code generation team as well as the (interim) team for the Linux tools team that i built and lead last year. He has inherited the various efforts my team was working on and is the right contact going forward to collaborate on Linux compiler and tools efforts.
Hey Russell, Ian,
Russel, Ian mentioned shipping LTO+PGO for a "downstream customer." I assume they'd like to rebase at some point, so getting tweaks to the build system upstream will help them lower their technical debt. We're in the process of upstreaming LTO patches for Clang and would love help collaborating on getting it working for GCC, too.
If you'd like to speak more about this virtually, we have our public meeting every other week coming up tomorrow. It's noon pacific time, see https://clangbuiltlinux.github.io/ for calendar invite and Google meet link. Please stop by, even if it's just to say hello!
Quoted 154 lines
ian Bearman
Principal Software Engineering Manager
Microsoft Visual C++ Team: ML Optimization & Code Generation #BlackLivesMatter
/* Making your code faster, smaller, smarter! */-----Original Message-----
From: Nick Desaulniers <[email protected]>
Sent: Thursday, September 10, 2020 10:46 AM
To: Ian Bearman <[email protected]>
Cc: clang-built-linux <[email protected]>; LKML <[email protected]>; Sami Tolvanen <[email protected]>
Subject: [EXTERNAL] Re: [PATCH v2 00/28] Add support for Clang LTOHey Ian,
It was nice to meet you at Linux plumbers. You might want to take a look at this series. It implements builds of the Linux kernel with LTO. It would be good to get eyes on it and help review it from folks working on this from the GCC angle. The series has some configs that split where Clang specific changes need to be made; it might be of interest to think about what would the similar changes be needed for GCC. Also, congrats on your LWN article!
https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Flwn.net%2FArticles%2F830300%2F&data=02%7C01%7Cian.bearman%40microsoft.com%7C9adc842104f640d3ebb308d855b17221%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637353568334933757&sdata=uM6%2BGj5z0gNAuIravVWOeVeIVsRI5YaPIJqB8qYsZ94%3D&reserved=0Quoted 126 lines · Sami Tolvanen
This patch series adds support for building
x86_64and arm64 kernels with Clang's Link Time Optimization (LTO).In addition to performance, the primary motivation for LTO is to allow Clang's Control-Flow Integrity (CFI) to be used in the kernel. Google has shipped millions of Pixel devices running three major kernel versions with LTO+CFI since 2018.
Most of the patches are build system changes for handling LLVM bitcode, which Clang produces with LTO instead of ELF object files, postponing ELF processing until a later stage, and ensuring initcall ordering.
Note that patches 1-4 are not directly related to LTO, but are needed to compile LTO kernels with ToT Clang, so I'm including them in the series for your convenience:
- Patches 1-3 are required for building the kernel with ToT Clang, and IAS, and patch 4 is needed to build allmodconfig with LTO.
- Patches 3-4 are already in linux-next, but not yet in 5.9-rc.
---
Changes in v2:- Fixed -Wmissing-prototypes warnings with W=1.
- Dropped cc-option from -fsplit-lto-unit and added .thinlto-cache scrubbing to make distclean.
- Added a comment about Clang >=11 being required.
- Added a patch to disable LTO for the arm64 KVM nVHE code.
- Disabled objtool's noinstr validation with LTO unless enabled.
- Included Peter's proposed objtool mcount patch in the series and replaced recordmcount with the objtool pass to avoid whitelisting relocations that are not calls.
- Updated several commit messages with better explanations.
Arvind Sankar (2):
x86/boot/compressed: Disable relocation relaxation x86/asm: Replace__force_orderwith memory clobberLuca Stefani (1):
RAS/CEC: Fixcec_init()prototypeNick Desaulniers (1):
lib/string.c: implement stpcpyPeter Zijlstra (1):
objtool: Add a pass for generating__mcount_locSami Tolvanen (23):
objtool: Don't autodetect vmlinux.o
kbuild: add support for objtool mcount
x86, build: use objtool mcount
kbuild: add support for Clang LTO
kbuild: lto: fix module versioning
kbuild: lto: postpone objtool
kbuild: lto: limit inlining
kbuild: lto: merge module sections
kbuild: lto: remove duplicate dependencies from .mod files
init: lto: ensure initcall ordering
init: lto: fix PREL32 relocations
PCI: Fix PREL32 relocations for LTO
modpost: lto: strip .lto from module namesscripts/mod: disable LTO forempty.cefi/libstub: disable LTO
drivers/misc/lkdtm: disable LTO for rodata.o
arm64: exportCC_USING_PATCHABLE_FUNCTION_ENTRY
arm64: vdso: disable LTO
KVM: arm64: disable LTO for the nVHE directory
arm64: allowLTO_CLANGand THINLTO to be selected x86, vdso: disable LTO only for vDSO
x86, relocs: IgnoreL4_PAGE_OFFSETrelocations x86, build: allowLTO_CLANGand THINLTO to be selected.gitignore | 1 + Makefile | 65 ++++++- arch/Kconfig | 67 +++++++ arch/arm64/Kconfig | 2 + arch/arm64/Makefile | 1 + arch/arm64/kernel/vdso/Makefile | 4 +- arch/arm64/kvm/hyp/nvhe/Makefile | 4 +- arch/x86/Kconfig | 3 + arch/x86/Makefile | 5 + arch/x86/boot/compressed/Makefile | 2 + arch/x86/boot/compressed/pgtable_64.c | 9 - arch/x86/entry/vdso/Makefile | 5 +- arch/x86/include/asm/special_insns.h | 28 +-- arch/x86/kernel/cpu/common.c | 4 +- arch/x86/tools/relocs.c | 1 + drivers/firmware/efi/libstub/Makefile | 2 + drivers/misc/lkdtm/Makefile | 1 + drivers/ras/cec.c | 9 +- include/asm-generic/vmlinux.lds.h | 11 +- include/linux/init.h | 79 +++++++- include/linux/pci.h | 19 +- kernel/trace/Kconfig | 5 + lib/string.c | 24 +++ scripts/Makefile.build | 55 +++++- scripts/Makefile.lib | 6 +- scripts/Makefile.modfinal | 31 ++- scripts/Makefile.modpost | 26 ++- scripts/generate_initcall_order.pl | 270 ++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 94 ++++++++- scripts/mod/Makefile | 1 + scripts/mod/modpost.c | 16 +- scripts/mod/modpost.h | 9 + scripts/mod/sumversion.c | 6 +- scripts/module-lto.lds | 26 +++ tools/objtool/builtin-check.c | 13 +- tools/objtool/builtin.h | 2 +- tools/objtool/check.c | 83 ++++++++ tools/objtool/check.h | 1 + tools/objtool/objtool.h | 1 + 39 files changed, 883 insertions(+), 108 deletions(-) create mode 100755 scripts/generate_initcall_order.pl create mode 100644 scripts/module-lto.ldsQuoted 4 lines
base-commit:
e28f0104343d0c132fa37f479870c9e43355fee4--
2.28.0.402.g5ffc5be6b7-goog--
Thanks,
~Nick Desaulniers
Signature · 2 lines
Thanks, ~Nick Desaulniers