1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4# Library of helpers for test scripts.
5set -e
6
7DIR=/sys/devices/virtual/misc/test_firmware
8
9PROC_CONFIG="/proc/config.gz"
10TEST_DIR=$(dirname $0)
11
12print_reqs_exit()
13{
14	echo "You must have the following enabled in your kernel:" >&2
15	cat $TEST_DIR/config >&2
16	exit 1
17}
18
19test_modprobe()
20{
21	if [ ! -d $DIR ]; then
22		print_reqs_exit
23	fi
24}
25
26check_mods()
27{
28	trap "test_modprobe" EXIT
29	if [ ! -d $DIR ]; then
30		modprobe test_firmware
31	fi
32	if [ ! -f $PROC_CONFIG ]; then
33		if modprobe configs 2>/dev/null; then
34			echo "Loaded configs module"
35			if [ ! -f $PROC_CONFIG ]; then
36				echo "You must have the following enabled in your kernel:" >&2
37				cat $TEST_DIR/config >&2
38				echo "Resorting to old heuristics" >&2
39			fi
40		else
41			echo "Failed to load configs module, using old heuristics" >&2
42		fi
43	fi
44}
45
46check_setup()
47{
48	HAS_FW_LOADER_USER_HELPER="$(kconfig_has CONFIG_FW_LOADER_USER_HELPER=y)"
49	HAS_FW_LOADER_USER_HELPER_FALLBACK="$(kconfig_has CONFIG_FW_LOADER_USER_HELPER_FALLBACK=y)"
50
51	if [ "$HAS_FW_LOADER_USER_HELPER" = "yes" ]; then
52	       OLD_TIMEOUT="$(cat /sys/class/firmware/timeout)"
53	fi
54
55	OLD_FWPATH="$(cat /sys/module/firmware_class/parameters/path)"
56}
57
58verify_reqs()
59{
60	if [ "$TEST_REQS_FW_SYSFS_FALLBACK" = "yes" ]; then
61		if [ ! "$HAS_FW_LOADER_USER_HELPER" = "yes" ]; then
62			echo "usermode helper disabled so ignoring test"
63			exit 0
64		fi
65	fi
66}
67
68setup_tmp_file()
69{
70	FWPATH=$(mktemp -d)
71	FW="$FWPATH/test-firmware.bin"
72	echo "ABCD0123" >"$FW"
73	NAME=$(basename "$FW")
74	if [ "$TEST_REQS_FW_SET_CUSTOM_PATH" = "yes" ]; then
75		echo -n "$FWPATH" >/sys/module/firmware_class/parameters/path
76	fi
77}
78
79test_finish()
80{
81	if [ "$HAS_FW_LOADER_USER_HELPER" = "yes" ]; then
82		echo "$OLD_TIMEOUT" >/sys/class/firmware/timeout
83	fi
84	if [ "$OLD_FWPATH" = "" ]; then
85		OLD_FWPATH=" "
86	fi
87	if [ "$TEST_REQS_FW_SET_CUSTOM_PATH" = "yes" ]; then
88		echo -n "$OLD_FWPATH" >/sys/module/firmware_class/parameters/path
89	fi
90	if [ -f $FW ]; then
91		rm -f "$FW"
92	fi
93	if [ -d $FWPATH ]; then
94		rm -rf "$FWPATH"
95	fi
96}
97
98kconfig_has()
99{
100	if [ -f $PROC_CONFIG ]; then
101		if zgrep -q $1 $PROC_CONFIG 2>/dev/null; then
102			echo "yes"
103		else
104			echo "no"
105		fi
106	else
107		# We currently don't have easy heuristics to infer this
108		# so best we can do is just try to use the kernel assuming
109		# you had enabled it. This matches the old behaviour.
110		if [ "$1" = "CONFIG_FW_LOADER_USER_HELPER_FALLBACK=y" ]; then
111			echo "yes"
112		elif [ "$1" = "CONFIG_FW_LOADER_USER_HELPER=y" ]; then
113			if [ -d /sys/class/firmware/ ]; then
114				echo yes
115			else
116				echo no
117			fi
118		fi
119	fi
120}
121