build.sh: Allow building external modules in parallel

Allow external modules to be built in parallel by letting projects
provide their own makefile for building external modules.

Currently, build.sh employs a simple for loop to build and install
modules listed in EXT_MODULES. Unfortunately, this prevents parallel
compilation across modules and results in poor utilization of build
machines with multiple CPUs.

If EXT_MODULES_MAKEFILE is set to the file path of a custom makefile,
build.sh will invoke make on it with all the necessary parameters that
are needed to build and install kernel modules.

Signed-off-by: Daniel Mentz <danielmentz@google.com>
Change-Id: I357a524a831cf5a0a522fee66bc9c6afd249f1f1
(cherry picked from commit e2f698e689fcab16b15831a0cf6f5320cf30f0f6)
diff --git a/build.sh b/build.sh
index 2be333f..e6430f1 100755
--- a/build.sh
+++ b/build.sh
@@ -55,6 +55,12 @@
 #   EXT_MODULES
 #     Space separated list of external kernel modules to be build.
 #
+#   EXT_MODULES_MAKEFILE
+#     Location of a makefile to build external modules. If set, it will get
+#     called with all the necessary parameters to build and install external
+#     modules.  This allows for building them in parallel using makefile
+#     parallelization.
+#
 #   UNSTRIPPED_MODULES
 #     Space separated list of modules to be copied to <DIST_DIR>/unstripped
 #     for debugging purposes.
@@ -421,7 +427,7 @@
   cp ${src_dir}/modules.order ${dest_dir}/modules.order
   cp ${src_dir}/modules.builtin ${dest_dir}/modules.builtin
 
-  if [ -n "${EXT_MODULES}" ]; then
+  if [[ -n "${EXT_MODULES}" ]] || [[ -n "${EXT_MODULES_MAKEFILE}" ]]; then
     mkdir -p ${dest_dir}/extra/
     cp -r ${src_dir}/extra/* ${dest_dir}/extra/
     (cd ${dest_dir}/ && \
@@ -930,6 +936,15 @@
         INSTALL_MOD_PATH=${MODULES_STAGING_DIR} "${MAKE_ARGS[@]}" modules_install)
 fi
 
+if [[ -z "${SKIP_EXT_MODULES}" ]] && [[ -n "${EXT_MODULES_MAKEFILE}" ]]; then
+  echo "========================================================"
+  echo " Building and installing external modules using ${EXT_MODULES_MAKEFILE}"
+
+  make -f "${EXT_MODULES_MAKEFILE}" KERNEL_SRC=${ROOT_DIR}/${KERNEL_DIR} \
+          O=${OUT_DIR} ${TOOL_ARGS} ${MODULE_STRIP_FLAG}                 \
+          INSTALL_MOD_PATH=${MODULES_STAGING_DIR} "${MAKE_ARGS[@]}"
+fi
+
 if [[ -z "${SKIP_EXT_MODULES}" ]] && [[ -n "${EXT_MODULES}" ]]; then
   echo "========================================================"
   echo " Building external modules and installing them into staging directory"
@@ -1060,7 +1075,7 @@
 
 MODULES=$(find ${MODULES_STAGING_DIR} -type f -name "*.ko")
 if [ -n "${MODULES}" ]; then
-  if [ -n "${IN_KERNEL_MODULES}" -o -n "${EXT_MODULES}" ]; then
+  if [ -n "${IN_KERNEL_MODULES}" -o -n "${EXT_MODULES}" -o -n "${EXT_MODULES_MAKEFILE}" ]; then
     echo "========================================================"
     echo " Copying modules files"
     for FILE in ${MODULES}; do