[PATCH] Add MO(mod objs) variable to process ext modules with subdirs

From: Valerii Chernous
Date: Tue Apr 02 2024 - 11:31:54 EST


The change allow to build external modules with nested makefiles.
With current unofficial way(using "src" variable) it is posible to build
external(out of tree) kernel module with separating source and build
artifacts dirs but with nested makefiles it doesn't work properly.
Build system trap to recursion inside makefiles, articafts output dir
path grow with each iteration until exceed max path len and build failed
Providing "MO" variable and using "override" directive with declaring
"src" variable solve the problem
Usage example:
make -C KERNEL_SOURCE_TREE MO=BUILD_OUT_DIR M=EXT_MOD_SRC_DIR modules

Cc: xe-linux-external@xxxxxxxxx
Cc: Valerii Chernous <vchernou@xxxxxxxxx>
Signed-off-by: Valerii Chernous <vchernou@xxxxxxxxx>
---
Makefile | 17 +++++++++++++++++
scripts/Makefile.build | 7 +++++++
2 files changed, 24 insertions(+)

diff --git a/Makefile b/Makefile
index 4bef6323c47d..5858708d357c 100644
--- a/Makefile
+++ b/Makefile
@@ -142,6 +142,7 @@ ifeq ("$(origin M)", "command line")
KBUILD_EXTMOD := $(M)
endif

+define kbuild_extmod_check_TEMPLATE
$(if $(word 2, $(KBUILD_EXTMOD)), \
$(error building multiple external modules is not supported))

@@ -152,9 +153,25 @@ $(foreach x, % :, $(if $(findstring $x, $(KBUILD_EXTMOD)), \
ifneq ($(filter %/, $(KBUILD_EXTMOD)),)
KBUILD_EXTMOD := $(shell dirname $(KBUILD_EXTMOD).)
endif
+endef
+$(eval $(call kbuild_extmod_check_TEMPLATE))

export KBUILD_EXTMOD

+# Use make M=src_dir MO=ko_dir or set the environment variables:
+# KBUILD_EXTMOD_SRC, KBUILD_EXTMOD to specify separate directories of
+# external module sources and build artifacts.
+ifeq ("$(origin MO)", "command line")
+ifeq (KBUILD_EXTMOD,)
+ $(error Ext module objects without module sources is not supported))
+endif
+KBUILD_EXTMOD_SRC := $(KBUILD_EXTMOD)
+KBUILD_EXTMOD := $(MO)
+$(eval $(call kbuild_extmod_check_TEMPLATE))
+endif
+
+export KBUILD_EXTMOD_SRC
+
# backward compatibility
KBUILD_EXTRA_WARN ?= $(KBUILD_ENABLE_EXTRA_GCC_CHECKS)

diff --git a/scripts/Makefile.build b/scripts/Makefile.build
index baf86c0880b6..a293950e2e07 100644
--- a/scripts/Makefile.build
+++ b/scripts/Makefile.build
@@ -3,7 +3,14 @@
# Building
# ==========================================================================

+ifeq ($(KBUILD_EXTMOD_SRC),)
src := $(obj)
+else ifeq ($(KBUILD_EXTMOD),$(obj))
+override src := $(KBUILD_EXTMOD_SRC)
+else
+src_subdir := $(patsubst $(KBUILD_EXTMOD)/%,%,$(obj))
+override src := $(KBUILD_EXTMOD_SRC)/$(src_subdir)
+endif

PHONY := $(obj)/
$(obj)/:
--
2.35.6