diff --git a/Documentation/core-api/symbol-namespaces.rst b/Documentation/core-api/symbol-namespaces.rst
index 982ed7b568ac28881f6263ad1137da862e303714..9b76337f6756adaaab191262743d54e91ac0861c 100644
--- a/Documentation/core-api/symbol-namespaces.rst
+++ b/Documentation/core-api/symbol-namespaces.rst
@@ -152,3 +152,6 @@ in-tree modules::
 	- notice the warning of modpost telling about a missing import
 	- run `make nsdeps` to add the import to the correct code location
 
+You can also run nsdeps for external module builds. A typical usage is::
+
+	$ make -C <path_to_kernel_src> M=$PWD nsdeps
diff --git a/Makefile b/Makefile
index 084016405f69fde08c146cc92b5541b8ea0f80b9..4c14d708040573e5540c81b74a129f0e17f9c09e 100644
--- a/Makefile
+++ b/Makefile
@@ -1008,6 +1008,7 @@ endif
 PHONY += prepare0
 
 export MODORDER := $(extmod-prefix)modules.order
+export MODULES_NSDEPS := $(extmod-prefix)modules.nsdeps
 
 ifeq ($(KBUILD_EXTMOD),)
 core-y		+= kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/
@@ -1620,7 +1621,7 @@ _emodinst_post: _emodinst_
 	$(call cmd,depmod)
 
 clean-dirs := $(KBUILD_EXTMOD)
-clean: rm-files := $(KBUILD_EXTMOD)/Module.symvers
+clean: rm-files := $(KBUILD_EXTMOD)/Module.symvers $(KBUILD_EXTMOD)/modules.nsdeps
 
 PHONY += /
 /:
diff --git a/scripts/Makefile.modpost b/scripts/Makefile.modpost
index 62e127028b48d4359683673dd9991275c9a04e74..69897d5d3a7004a0fc8dc5497b1156802cd86c22 100644
--- a/scripts/Makefile.modpost
+++ b/scripts/Makefile.modpost
@@ -66,7 +66,7 @@ __modpost:
 else
 
 MODPOST += $(subst -i,-n,$(filter -i,$(MAKEFLAGS))) -s -T - \
-	$(if $(KBUILD_NSDEPS),-d modules.nsdeps)
+	$(if $(KBUILD_NSDEPS),-d $(MODULES_NSDEPS))
 
 ifeq ($(KBUILD_EXTMOD),)
 MODPOST += $(wildcard vmlinux)
diff --git a/scripts/nsdeps b/scripts/nsdeps
index f802c6f7b8609876dd19db4b708274e8f5c9e6a5..03a8e7cbe6c77731ddd77d4fa815c6eddf1490c2 100644
--- a/scripts/nsdeps
+++ b/scripts/nsdeps
@@ -21,6 +21,12 @@ if [ "$SPATCH_VERSION_NUM" -lt "$SPATCH_REQ_VERSION_NUM" ] ; then
 	exit 1
 fi
 
+if [ "$KBUILD_EXTMOD" ]; then
+	src_prefix=
+else
+	src_prefix=$srctree/
+fi
+
 generate_deps_for_ns() {
 	$SPATCH --very-quiet --in-place --sp-file \
 		$srctree/scripts/coccinelle/misc/add_namespace.cocci -D ns=$1 $2
@@ -32,7 +38,7 @@ generate_deps() {
 	local namespaces="$*"
 	local mod_source_files="`cat $mod.mod | sed -n 1p                      \
 					      | sed -e 's/\.o/\.c/g'           \
-					      | sed "s|[^ ]* *|${srctree}/&|g"`"
+					      | sed "s|[^ ]* *|${src_prefix}&|g"`"
 	for ns in $namespaces; do
 		echo "Adding namespace $ns to module $mod.ko."
 		generate_deps_for_ns $ns "$mod_source_files"
@@ -54,4 +60,4 @@ generate_deps() {
 while read line
 do
 	generate_deps $line
-done < modules.nsdeps
+done < $MODULES_NSDEPS