#!/bin/sh
# - nr_task
# - runtime
# - build_kconfig
# - target

. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/reproduce-log.sh

## Build linux kernel

: ${runtime:=300}
: ${build_kconfig:=defconfig}

[ -n "$target" ] || target=vmlinux

run_kbuild()
{
	start_time=$(date +%s)
	iterations=0
	while true; do
		log_cmd make mrproper || die "make mrproper failed"
		log_cmd make $build_kconfig || die "make $build_kconfig failed"

		# git show v5.4:Makefile | grep -C2 autoksyms_recursive:
		# PHONY += autoksyms_recursive
		# ifdef CONFIG_TRIM_UNUSED_KSYMS
		# autoksyms_recursive: descend modules.order
		#         $(Q)$(CONFIG_SHELL) $(srctree)/scripts/adjust_autoksyms.sh \
		#           "$(MAKE) -f $(srctree)/Makefile vmlinux"

		# https://cateee.net/lkddb/web-lkddb/TRIM_UNUSED_KSYMS.html
		# The Linux kernel configuration item CONFIG_TRIM_UNUSED_KSYMS:
		#   depends on: ! CONFIG_UNUSED_SYMBOLS
		log_cmd scripts/config --file .config --disable CONFIG_UNUSED_SYMBOLS
		log_cmd scripts/config --file .config --enable CONFIG_TRIM_UNUSED_KSYMS

		log_cmd make -j $nr_task $target 2> /dev/null || die "make -j $nr_task $target failed"
		iterations=$((iterations + 1))
		now=$(date +%s)
		[ $((now - start_time)) -gt "$runtime" ] && break
	done
	echo "iterations: $iterations"
	echo "runtime: $((now - start_time))"
}

linux_src="$BENCHMARK_ROOT/kbuild/linux"
[ -d "$linux_src" ] || die "no kernel source code in $BENCHMARK_ROOT/kbuild/linux"

: ${kbuild_work_dirs:=$linux_src}

kbuild_tmp_dir="$TMP/kbuild"
i=0

mkdir -p $kbuild_tmp_dir

for wdir in $kbuild_work_dirs; do
	(
		log_eval cd "$wdir"
		run_kbuild > "$kbuild_tmp_dir/kbuild.$i"
	) &
	i=$((i+1))
done

wait

cat "$kbuild_tmp_dir"/kbuild.*
