xref: /spdk/test/common/autotest_common.sh (revision c680e3a05b1a903c18bf3f75b732765607126f45)
1#!/usr/bin/env bash
2#  SPDX-License-Identifier: BSD-3-Clause
3#  Copyright (C) 2015 Intel Corporation
4#  All rights reserved.
5#
6rpc_py=rpc_cmd
7
8function xtrace_fd() {
9	if [[ -n $BASH_XTRACEFD && -e /proc/self/fd/$BASH_XTRACEFD ]]; then
10		# Close it first to make sure it's sane
11		exec {BASH_XTRACEFD}>&-
12	fi
13	exec {BASH_XTRACEFD}>&2
14
15	set -x
16}
17
18function xtrace_disable() {
19	if [ "$XTRACE_DISABLED" != "yes" ]; then
20		PREV_BASH_OPTS="$-"
21		if [[ "$PREV_BASH_OPTS" == *"x"* ]]; then
22			XTRACE_DISABLED="yes"
23		fi
24		set +x
25	elif [ -z $XTRACE_NESTING_LEVEL ]; then
26		XTRACE_NESTING_LEVEL=1
27	else
28		XTRACE_NESTING_LEVEL=$((++XTRACE_NESTING_LEVEL))
29	fi
30}
31
32xtrace_disable
33set -e
34shopt -s expand_aliases
35
36if [[ -e $rootdir/test/common/build_config.sh ]]; then
37	source "$rootdir/test/common/build_config.sh"
38elif [[ -e $rootdir/mk/config.mk ]]; then
39	build_config=$(< "$rootdir/mk/config.mk")
40	source <(echo "${build_config//\?=/=}")
41else
42	source "$rootdir/CONFIG"
43fi
44
45# Source scripts after the config so that the definitions are available.
46source "$rootdir/test/common/applications.sh"
47source "$rootdir/scripts/common.sh"
48
49# Dummy function to be called after restoring xtrace just so that it appears in the
50# xtrace log. This way we can consistently track when xtrace is enabled/disabled.
51function xtrace_enable() {
52	# We have to do something inside a function in bash, and calling any command
53	# (even `:`) will produce an xtrace entry, so we just define another function.
54	function xtrace_dummy() { :; }
55}
56
57# Keep it as alias to avoid xtrace_enable backtrace always pointing to xtrace_restore.
58# xtrace_enable will appear as called directly from the user script, from the same line
59# that "called" xtrace_restore.
60alias xtrace_restore='if [ -z $XTRACE_NESTING_LEVEL ]; then
61        if [[ "$PREV_BASH_OPTS" == *"x"* ]]; then
62		XTRACE_DISABLED="no"; PREV_BASH_OPTS=""; set -x; xtrace_enable;
63	fi
64else
65	XTRACE_NESTING_LEVEL=$((--XTRACE_NESTING_LEVEL));
66	if [ $XTRACE_NESTING_LEVEL -eq "0" ]; then
67		unset XTRACE_NESTING_LEVEL
68	fi
69fi'
70
71: ${RUN_NIGHTLY:=0}
72export RUN_NIGHTLY
73
74# Set defaults for missing test config options
75: ${SPDK_AUTOTEST_DEBUG_APPS:=0}
76export SPDK_AUTOTEST_DEBUG_APPS
77: ${SPDK_RUN_VALGRIND=0}
78export SPDK_RUN_VALGRIND
79: ${SPDK_RUN_FUNCTIONAL_TEST=0}
80export SPDK_RUN_FUNCTIONAL_TEST
81: ${SPDK_TEST_UNITTEST=0}
82export SPDK_TEST_UNITTEST
83: ${SPDK_TEST_AUTOBUILD=""}
84export SPDK_TEST_AUTOBUILD
85: ${SPDK_TEST_RELEASE_BUILD=0}
86export SPDK_TEST_RELEASE_BUILD
87: ${SPDK_TEST_ISAL=0}
88export SPDK_TEST_ISAL
89: ${SPDK_TEST_ISCSI=0}
90export SPDK_TEST_ISCSI
91: ${SPDK_TEST_ISCSI_INITIATOR=0}
92export SPDK_TEST_ISCSI_INITIATOR
93: ${SPDK_TEST_NVME=0}
94export SPDK_TEST_NVME
95: ${SPDK_TEST_NVME_PMR=0}
96export SPDK_TEST_NVME_PMR
97: ${SPDK_TEST_NVME_SCC=0}
98export SPDK_TEST_NVME_SCC
99: ${SPDK_TEST_NVME_BP=0}
100export SPDK_TEST_NVME_BP
101: ${SPDK_TEST_NVME_CLI=0}
102export SPDK_TEST_NVME_CLI
103: ${SPDK_TEST_NVME_CUSE=0}
104export SPDK_TEST_NVME_CUSE
105: ${SPDK_TEST_NVMF=0}
106export SPDK_TEST_NVMF
107: ${SPDK_TEST_VFIOUSER=0}
108export SPDK_TEST_VFIOUSER
109: ${SPDK_TEST_VFIOUSER_QEMU=0}
110export SPDK_TEST_VFIOUSER_QEMU
111: ${SPDK_TEST_FUZZER=0}
112export SPDK_TEST_FUZZER
113: ${SPDK_TEST_FUZZER_SHORT=0}
114export SPDK_TEST_FUZZER_SHORT
115: ${SPDK_TEST_NVMF_TRANSPORT="rdma"}
116export SPDK_TEST_NVMF_TRANSPORT
117: ${SPDK_TEST_RBD=0}
118export SPDK_TEST_RBD
119: ${SPDK_TEST_VHOST=0}
120export SPDK_TEST_VHOST
121: ${SPDK_TEST_BLOCKDEV=0}
122export SPDK_TEST_BLOCKDEV
123: ${SPDK_TEST_IOAT=0}
124export SPDK_TEST_IOAT
125: ${SPDK_TEST_BLOBFS=0}
126export SPDK_TEST_BLOBFS
127: ${SPDK_TEST_VHOST_INIT=0}
128export SPDK_TEST_VHOST_INIT
129: ${SPDK_TEST_PMDK=0}
130export SPDK_TEST_PMDK
131: ${SPDK_TEST_LVOL=0}
132export SPDK_TEST_LVOL
133: ${SPDK_TEST_REDUCE=0}
134export SPDK_TEST_REDUCE
135: ${SPDK_RUN_ASAN=0}
136export SPDK_RUN_ASAN
137: ${SPDK_RUN_UBSAN=0}
138export SPDK_RUN_UBSAN
139: ${SPDK_RUN_EXTERNAL_DPDK=""}
140export SPDK_RUN_EXTERNAL_DPDK
141: ${SPDK_RUN_NON_ROOT=0}
142export SPDK_RUN_NON_ROOT
143: ${SPDK_TEST_CRYPTO=0}
144export SPDK_TEST_CRYPTO
145: ${SPDK_TEST_FTL=0}
146export SPDK_TEST_FTL
147: ${SPDK_TEST_OCF=0}
148export SPDK_TEST_OCF
149: ${SPDK_TEST_VMD=0}
150export SPDK_TEST_VMD
151: ${SPDK_TEST_OPAL=0}
152export SPDK_TEST_OPAL
153: ${SPDK_TEST_NATIVE_DPDK}
154export SPDK_TEST_NATIVE_DPDK
155: ${SPDK_AUTOTEST_X=true}
156export SPDK_AUTOTEST_X
157: ${SPDK_TEST_RAID5=0}
158export SPDK_TEST_RAID5
159: ${SPDK_TEST_URING=0}
160export SPDK_TEST_URING
161: ${SPDK_TEST_USDT=0}
162export SPDK_TEST_USDT
163: ${SPDK_TEST_USE_IGB_UIO:=0}
164export SPDK_TEST_USE_IGB_UIO
165: ${SPDK_TEST_SCHEDULER:=0}
166export SPDK_TEST_SCHEDULER
167: ${SPDK_TEST_SCANBUILD:=0}
168export SPDK_TEST_SCANBUILD
169: ${SPDK_TEST_NVMF_NICS:=}
170export SPDK_TEST_NVMF_NICS
171: ${SPDK_TEST_SMA=0}
172export SPDK_TEST_SMA
173: ${SPDK_TEST_DAOS=0}
174export SPDK_TEST_DAOS
175: ${SPDK_TEST_XNVME:=0}
176export SPDK_TEST_XNVME
177# Comma-separated list of fuzzer targets matching test/fuzz/llvm/$target
178: ${SPDK_TEST_FUZZER_TARGET:=}
179export SPDK_TEST_FUZZER_TARGET
180
181# always test with SPDK shared objects.
182export SPDK_LIB_DIR="$rootdir/build/lib"
183export DPDK_LIB_DIR="${SPDK_RUN_EXTERNAL_DPDK:-$rootdir/dpdk/build}/lib"
184export VFIO_LIB_DIR="$rootdir/build/libvfio-user/usr/local/lib"
185export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SPDK_LIB_DIR:$DPDK_LIB_DIR:$VFIO_LIB_DIR
186
187# Tell setup.sh to wait for block devices upon each reset
188export PCI_BLOCK_SYNC_ON_RESET=yes
189
190# Export PYTHONPATH with addition of RPC framework. New scripts can be created
191# specific use cases for tests.
192export PYTHONPATH=$PYTHONPATH:$rootdir/python
193
194# Don't create Python .pyc files. When running with sudo these will be
195# created with root ownership and can cause problems when cleaning the repository.
196export PYTHONDONTWRITEBYTECODE=1
197
198# Export flag to skip the known bug that exists in librados
199# Bug is reported on ceph bug tracker with number 24078
200export ASAN_OPTIONS=new_delete_type_mismatch=0:disable_coredump=0
201export UBSAN_OPTIONS='halt_on_error=1:print_stacktrace=1:abort_on_error=1:disable_coredump=0'
202
203# Export LeakSanitizer option to use suppression file in order to prevent false positives
204# and known leaks in external executables or libraries from showing up.
205asan_suppression_file="/var/tmp/asan_suppression_file"
206rm -rf "$asan_suppression_file" 2> /dev/null || sudo rm -rf "$asan_suppression_file"
207cat << EOL >> "$asan_suppression_file"
208# ASAN has some bugs around thread_local variables.  We have a destructor in place
209# to free the thread contexts, but ASAN complains about the leak before those
210# destructors have a chance to run.  So suppress this one specific leak using
211# LSAN_OPTIONS.
212leak:spdk_fs_alloc_thread_ctx
213
214# Suppress known leaks in fio project
215leak:$CONFIG_FIO_SOURCE_DIR/parse.c
216leak:$CONFIG_FIO_SOURCE_DIR/iolog.c
217leak:$CONFIG_FIO_SOURCE_DIR/init.c
218leak:$CONFIG_FIO_SOURCE_DIR/filesetup.c
219leak:fio_memalign
220leak:spdk_fio_io_u_init
221# Suppress leaks in gperftools-libs from fio
222leak:libtcmalloc_minimal.so
223
224# Suppress leaks in libiscsi
225leak:libiscsi.so
226EOL
227
228# Suppress leaks in libfuse3
229echo "leak:libfuse3.so" >> "$asan_suppression_file"
230
231export LSAN_OPTIONS=suppressions="$asan_suppression_file"
232
233export DEFAULT_RPC_ADDR="/var/tmp/spdk.sock"
234
235if [ -z "$DEPENDENCY_DIR" ]; then
236	export DEPENDENCY_DIR=$HOME/spdk_dependencies
237else
238	export DEPENDENCY_DIR
239fi
240
241# Export location of where all the SPDK binaries are
242export SPDK_BIN_DIR="$rootdir/build/bin"
243export SPDK_EXAMPLE_DIR="$rootdir/build/examples"
244
245# for vhost, vfio-user tests
246export QEMU_BIN=${QEMU_BIN:-}
247export VFIO_QEMU_BIN=${VFIO_QEMU_BIN:-}
248
249export AR_TOOL=$rootdir/scripts/ar-xnvme-fixer
250
251# pass our valgrind desire on to unittest.sh
252if [ $SPDK_RUN_VALGRIND -eq 0 ]; then
253	export valgrind=''
254fi
255
256if [ "$(uname -s)" = "Linux" ]; then
257	HUGEMEM=${HUGEMEM:-4096}
258	export CLEAR_HUGE=yes
259	if [[ $SPDK_TEST_CRYPTO -eq 1 || $SPDK_TEST_REDUCE -eq 1 ]]; then
260		# Make sure that memory is distributed across all NUMA nodes - by default, all goes to
261		# node0, but if QAT devices are attached to a different node, all of their VFs will end
262		# up under that node too and memory needs to be available there for the tests.
263		export HUGE_EVEN_ALLOC=yes
264	fi
265
266	MAKE="make"
267	MAKEFLAGS=${MAKEFLAGS:--j$(nproc)}
268	if [[ $SPDK_TEST_USE_IGB_UIO -eq 1 ]]; then
269		export DRIVER_OVERRIDE=igb_uio
270		# Building kernel modules requires root privileges
271		MAKE="sudo $MAKE"
272	fi
273elif [ "$(uname -s)" = "FreeBSD" ]; then
274	MAKE="gmake"
275	MAKEFLAGS=${MAKEFLAGS:--j$(sysctl -a | grep -E -i 'hw.ncpu' | awk '{print $2}')}
276	# FreeBSD runs a much more limited set of tests, so keep the default 2GB.
277	HUGEMEM=${HUGEMEM:-2048}
278elif [ "$(uname -s)" = "Windows" ]; then
279	MAKE="make"
280	MAKEFLAGS=${MAKEFLAGS:--j$(nproc)}
281	# Keep the default 2GB for Windows.
282	HUGEMEM=${HUGEMEM:-2048}
283else
284	echo "Unknown OS \"$(uname -s)\""
285	exit 1
286fi
287
288export HUGEMEM=$HUGEMEM
289
290if [ -z "$output_dir" ]; then
291	mkdir -p "$rootdir/../output"
292	export output_dir="$rootdir/../output"
293fi
294
295TEST_MODE=
296for i in "$@"; do
297	case "$i" in
298		--iso)
299			TEST_MODE=iso
300			;;
301		--transport=*)
302			TEST_TRANSPORT="${i#*=}"
303			;;
304		--sock=*)
305			TEST_SOCK="${i#*=}"
306			;;
307	esac
308done
309
310# start rpc.py coprocess if it's not started yet
311if [[ -z $RPC_PIPE_PID ]] || ! kill -0 "$RPC_PIPE_PID" &> /dev/null; then
312	# Include list to all known plugins we use in the tests
313	PYTHONPATH+=":$rootdir/test/rpc_plugins"
314	coproc RPC_PIPE { PYTHONPATH="$PYTHONPATH" "$rootdir/scripts/rpc.py" --server; }
315	exec {RPC_PIPE_OUTPUT}<&${RPC_PIPE[0]} {RPC_PIPE_INPUT}>&${RPC_PIPE[1]}
316	# all descriptors will automatically close together with this bash
317	# process, this will make rpc.py stop reading and exit gracefully
318fi
319
320function set_test_storage() {
321	[[ -v testdir ]] || return 0
322
323	local requested_size=$1 # bytes
324	local mount target_dir
325
326	local -A mounts fss sizes avails uses
327	local source fs size avail mount use
328
329	local storage_fallback storage_candidates
330
331	storage_fallback=$(mktemp -udt spdk.XXXXXX)
332	storage_candidates=(
333		"$testdir"
334		"$storage_fallback/tests/${testdir##*/}"
335		"$storage_fallback"
336	)
337
338	if [[ -n $ADD_TEST_STORAGE ]]; then
339		# List of dirs|mounts separated by whitespaces
340		storage_candidates+=($ADD_TEST_STORAGE)
341	fi
342
343	if [[ -n $DEDICATED_TEST_STORAGE ]]; then
344		# Single, dedicated dir|mount
345		storage_candidates=("$DEDICATED_TEST_STORAGE")
346	fi
347
348	mkdir -p "${storage_candidates[@]}"
349
350	# add some headroom - 64M
351	requested_size=$((requested_size + (64 << 20)))
352
353	while read -r source fs size use avail _ mount; do
354		mounts["$mount"]=$source fss["$mount"]=$fs
355		avails["$mount"]=$((avail * 1024)) sizes["$mount"]=$((size * 1024))
356		uses["$mount"]=$((use * 1024))
357	done < <(df -T | grep -v Filesystem)
358
359	printf '* Looking for test storage...\n' >&2
360
361	local target_space new_size
362	for target_dir in "${storage_candidates[@]}"; do
363		# FreeBSD's df is lacking the --output arg
364		# mount=$(df --output=target "$target_dir" | grep -v "Mounted on")
365		mount=$(df "$target_dir" | awk '$1 !~ /Filesystem/{print $6}')
366
367		target_space=${avails["$mount"]}
368		if ((target_space == 0 || target_space < requested_size)); then
369			continue
370		fi
371		if ((target_space >= requested_size)); then
372			# For in-memory fs, and / make sure our requested size won't fill most of the space.
373			if [[ ${fss["$mount"]} == tmpfs ]] || [[ ${fss["$mount"]} == ramfs ]] || [[ $mount == / ]]; then
374				new_size=$((uses["$mount"] + requested_size))
375				if ((new_size * 100 / sizes["$mount"] > 95)); then
376					continue
377				fi
378			fi
379		fi
380		export SPDK_TEST_STORAGE=$target_dir
381		printf '* Found test storage at %s\n' "$SPDK_TEST_STORAGE" >&2
382		return 0
383	done
384	printf '* Test storage is not available\n'
385	return 1
386}
387
388function get_config_params() {
389	xtrace_disable
390	config_params='--enable-debug --enable-werror'
391
392	# for options with dependencies but no test flag, set them here
393	if [ -f /usr/include/infiniband/verbs.h ]; then
394		config_params+=' --with-rdma'
395	fi
396
397	if [ $SPDK_TEST_USDT -eq 1 ]; then
398		config_params+=" --with-usdt"
399	fi
400
401	if [ $(uname -s) == "FreeBSD" ]; then
402		intel="hw.model: Intel"
403		cpu_vendor=$(sysctl -a | grep hw.model | cut -c 1-15)
404	else
405		intel="GenuineIntel"
406		cpu_vendor=$(grep -i 'vendor' /proc/cpuinfo --max-count=1)
407	fi
408	if [[ "$cpu_vendor" != *"$intel"* ]]; then
409		config_params+=" --without-idxd"
410	else
411		config_params+=" --with-idxd"
412	fi
413
414	if [[ -d $CONFIG_FIO_SOURCE_DIR ]]; then
415		config_params+=" --with-fio=$CONFIG_FIO_SOURCE_DIR"
416	fi
417
418	if [ -d ${DEPENDENCY_DIR}/vtune_codes ]; then
419		config_params+=' --with-vtune='${DEPENDENCY_DIR}'/vtune_codes'
420	fi
421
422	if [ -d /usr/include/iscsi ]; then
423		[[ $(< /usr/include/iscsi/iscsi.h) =~ "define LIBISCSI_API_VERSION ("([0-9]+)")" ]] \
424			&& libiscsi_version=${BASH_REMATCH[1]}
425		if ((libiscsi_version >= 20150621)); then
426			config_params+=' --with-iscsi-initiator'
427		fi
428	fi
429
430	if [[ $SPDK_TEST_UNITTEST -eq 0 && \
431		$SPDK_TEST_SCANBUILD -eq 0 && -z \
432		$SPDK_TEST_AUTOBUILD ]]; then
433		config_params+=' --disable-unit-tests'
434	fi
435
436	if [ $SPDK_TEST_NVME_CUSE -eq 1 ]; then
437		config_params+=' --with-nvme-cuse'
438	fi
439
440	# for options with both dependencies and a test flag, set them here
441	if [ -f /usr/include/libpmemblk.h ] && [ $SPDK_TEST_PMDK -eq 1 ]; then
442		config_params+=' --with-pmdk'
443	fi
444
445	if [ -f /usr/include/libpmem.h ] && [ $SPDK_TEST_REDUCE -eq 1 ]; then
446		if ge "$(nasm --version | awk '{print $3}')" 2.14 && [[ $SPDK_TEST_ISAL -eq 1 ]]; then
447			config_params+=' --with-reduce'
448		fi
449	fi
450
451	if [ -d /usr/include/rbd ] && [ -d /usr/include/rados ] && [ $SPDK_TEST_RBD -eq 1 ]; then
452		config_params+=' --with-rbd'
453	fi
454
455	# for options with no required dependencies, just test flags, set them here
456	if [ $SPDK_TEST_CRYPTO -eq 1 ]; then
457		config_params+=' --with-crypto'
458	fi
459
460	if [ $SPDK_TEST_OCF -eq 1 ]; then
461		config_params+=" --with-ocf"
462	fi
463
464	if [ $SPDK_RUN_UBSAN -eq 1 ]; then
465		config_params+=' --enable-ubsan'
466	fi
467
468	if [ $SPDK_RUN_ASAN -eq 1 ]; then
469		config_params+=' --enable-asan'
470	fi
471
472	if [ "$(uname -s)" = "Linux" ]; then
473		config_params+=' --enable-coverage'
474	fi
475
476	if [ $SPDK_TEST_BLOBFS -eq 1 ]; then
477		if [[ -d /usr/include/fuse3 ]] || [[ -d /usr/local/include/fuse3 ]]; then
478			config_params+=' --with-fuse'
479		fi
480	fi
481
482	if [ $SPDK_TEST_RAID5 -eq 1 ]; then
483		config_params+=' --with-raid5f'
484	fi
485
486	if [ $SPDK_TEST_VFIOUSER -eq 1 ] || [ $SPDK_TEST_VFIOUSER_QEMU -eq 1 ]; then
487		config_params+=' --with-vfio-user'
488	fi
489
490	# Check whether liburing library header exists
491	if [ -f /usr/include/liburing/io_uring.h ] && [ $SPDK_TEST_URING -eq 1 ]; then
492		config_params+=' --with-uring'
493	fi
494
495	if [ -n "$SPDK_RUN_EXTERNAL_DPDK" ]; then
496		config_params+=" --with-dpdk=$SPDK_RUN_EXTERNAL_DPDK"
497	fi
498
499	if [[ $SPDK_TEST_SMA -eq 1 ]]; then
500		config_params+=' --with-sma'
501		config_params+=' --with-crypto'
502	fi
503
504	if [ -f /usr/include/daos.h ] && [ $SPDK_TEST_DAOS -eq 1 ]; then
505		config_params+=' --with-daos'
506	fi
507
508	# Make the xnvme module available for the tests
509	if [[ $SPDK_TEST_XNVME -eq 1 ]]; then
510		config_params+=' --with-xnvme'
511	fi
512
513	if [[ $SPDK_TEST_FUZZER -eq 1 ]]; then
514		config_params+=" $(get_fuzzer_target_config)"
515	fi
516
517	echo "$config_params"
518	xtrace_restore
519}
520
521function get_fuzzer_target_config() {
522	local -A fuzzer_targets_to_config=()
523	local config target
524
525	fuzzer_targets_to_config["vfio"]="--with-vfio-user"
526	for target in $(get_fuzzer_targets); do
527		[[ -n ${fuzzer_targets_to_config["$target"]} ]] || continue
528		config+=("${fuzzer_targets_to_config["$target"]}")
529	done
530
531	if ((${#config[@]} > 0)); then
532		echo "${config[*]}"
533	fi
534}
535
536function get_fuzzer_targets() {
537	local fuzzers=()
538
539	if [[ -n $SPDK_TEST_FUZZER_TARGET ]]; then
540		IFS="," read -ra fuzzers <<< "$SPDK_TEST_FUZZER_TARGET"
541	else
542		fuzzers=("$rootdir/test/fuzz/llvm/"*)
543		fuzzers=("${fuzzers[@]##*/}")
544	fi
545
546	echo "${fuzzers[*]}"
547}
548
549function rpc_cmd() {
550	xtrace_disable
551	local rsp rc=1
552	local stdin cmd cmds_number=0 status_number=0 status
553
554	if (($#)); then
555		cmds_number=1
556		echo "$@" >&$RPC_PIPE_INPUT
557	elif [[ ! -t 0 ]]; then
558		mapfile -t stdin <&0
559		cmds_number=${#stdin[@]}
560		printf '%s\n' "${stdin[@]}" >&$RPC_PIPE_INPUT
561	else
562		return 0
563	fi
564
565	while read -t 15 -ru $RPC_PIPE_OUTPUT rsp; do
566		if [[ $rsp == "**STATUS="* ]]; then
567			status[${rsp#*=}]=$rsp
568			if ((++status_number == cmds_number)); then
569				break
570			fi
571			continue
572		fi
573		echo "$rsp"
574	done
575
576	rc=${!status[*]}
577	xtrace_restore
578	[[ $rc == 0 ]]
579}
580
581function rpc_cmd_simple_data_json() {
582
583	local elems="$1[@]" elem
584	local -gA jq_out=()
585	local jq val
586
587	local lvs=(
588		"uuid"
589		"name"
590		"base_bdev"
591		"total_data_clusters"
592		"free_clusters"
593		"block_size"
594		"cluster_size"
595	)
596
597	local bdev=(
598		"name"
599		"aliases[0]"
600		"block_size"
601		"num_blocks"
602		"uuid"
603		"product_name"
604	)
605
606	[[ -v $elems ]] || return 1
607
608	for elem in "${!elems}"; do
609		jq="${jq:+$jq,\"\\n\",}\"$elem\",\" \",.[0].$elem"
610	done
611	jq+=',"\n"'
612
613	shift
614	while read -r elem val; do
615		jq_out["$elem"]=$val
616	done < <(rpc_cmd "$@" | jq -jr "$jq")
617	((${#jq_out[@]} > 0)) || return 1
618}
619
620function NOT() {
621	local es=0
622
623	"$@" || es=$?
624
625	# Logic looks like so:
626	#  - return false if command exit successfully
627	#  - return false if command exit after receiving a core signal (FIXME: or any signal?)
628	#  - return true if command exit with an error
629
630	# This naively assumes that the process doesn't exit with > 128 on its own.
631	if ((es > 128)); then
632		es=$((es & ~128))
633		case "$es" in
634			3) ;&       # SIGQUIT
635			4) ;&       # SIGILL
636			6) ;&       # SIGABRT
637			8) ;&       # SIGFPE
638			9) ;&       # SIGKILL
639			11) es=0 ;; # SIGSEGV
640			*) es=1 ;;
641		esac
642	elif [[ -n $EXIT_STATUS ]] && ((es != EXIT_STATUS)); then
643		es=0
644	fi
645
646	# invert error code of any command and also trigger ERR on 0 (unlike bash ! prefix)
647	((!es == 0))
648}
649
650function timing() {
651	direction="$1"
652	testname="$2"
653
654	now=$(date +%s)
655
656	if [ "$direction" = "enter" ]; then
657		export timing_stack="${timing_stack};${now}"
658		export test_stack="${test_stack};${testname}"
659	else
660		touch "$output_dir/timing.txt"
661		child_time=$(grep "^${test_stack:1};" $output_dir/timing.txt | awk '{s+=$2} END {print s}')
662
663		start_time=$(echo "$timing_stack" | sed -e 's@^.*;@@')
664		timing_stack=$(echo "$timing_stack" | sed -e 's@;[^;]*$@@')
665
666		elapsed=$((now - start_time - child_time))
667		echo "${test_stack:1} $elapsed" >> $output_dir/timing.txt
668
669		test_stack=$(echo "$test_stack" | sed -e 's@;[^;]*$@@')
670	fi
671}
672
673function timing_enter() {
674	xtrace_disable
675	timing "enter" "$1"
676	xtrace_restore
677}
678
679function timing_exit() {
680	xtrace_disable
681	timing "exit" "$1"
682	xtrace_restore
683}
684
685function timing_finish() {
686	flamegraph='/usr/local/FlameGraph/flamegraph.pl'
687	if [ -x "$flamegraph" ]; then
688		"$flamegraph" \
689			--title 'Build Timing' \
690			--nametype 'Step:' \
691			--countname seconds \
692			$output_dir/timing.txt \
693			> $output_dir/timing.svg
694	fi
695}
696
697function create_test_list() {
698	xtrace_disable
699	# First search all scripts in main SPDK directory.
700	completion=$(grep -shI -d skip --include="*.sh" -e "run_test " $rootdir/*)
701	# Follow up with search in test directory recursively.
702	completion+=$'\n'$(grep -rshI --include="*.sh" --exclude="*autotest_common.sh" -e "run_test " $rootdir/test)
703	printf "%s" "$completion" | grep -v "#" \
704		| sed 's/^.*run_test/run_test/' | awk '{print $2}' \
705		| sed 's/\"//g' | sort > $output_dir/all_tests.txt || true
706	xtrace_restore
707}
708
709function gdb_attach() {
710	gdb -q --batch \
711		-ex 'handle SIGHUP nostop pass' \
712		-ex 'handle SIGQUIT nostop pass' \
713		-ex 'handle SIGPIPE nostop pass' \
714		-ex 'handle SIGALRM nostop pass' \
715		-ex 'handle SIGTERM nostop pass' \
716		-ex 'handle SIGUSR1 nostop pass' \
717		-ex 'handle SIGUSR2 nostop pass' \
718		-ex 'handle SIGCHLD nostop pass' \
719		-ex 'set print thread-events off' \
720		-ex 'cont' \
721		-ex 'thread apply all bt' \
722		-ex 'quit' \
723		--tty=/dev/stdout \
724		-p $1
725}
726
727function process_core() {
728	# Note that this always was racy as we can't really sync with the kernel
729	# to see if there's any core queued up for writing. We could check if
730	# collector is running and wait for it explicitly, but it doesn't seem
731	# to be worth the effort. So assume that if we are being called via
732	# trap, as in, when some error has occurred, wait up to 10s for any
733	# potential cores. If we are called just for cleanup at the very end,
734	# don't wait since all the tests ended successfully, hence having any
735	# critical cores lying around is unlikely.
736	((autotest_es != 0)) && sleep 10
737
738	local coredumps core
739
740	shopt -s nullglob
741	coredumps=("$output_dir/coredumps/"*.bt.txt)
742	shopt -u nullglob
743
744	((${#coredumps[@]} > 0)) || return 0
745	chmod -R a+r "$output_dir/coredumps"
746
747	for core in "${coredumps[@]}"; do
748		cat <<- BT
749			##### CORE BT ${core##*/} #####
750
751			$(<"$core")
752
753			--
754		BT
755	done
756	return 1
757}
758
759function process_shm() {
760	type=$1
761	id=$2
762	if [ "$type" = "--pid" ]; then
763		id="pid${id}"
764	fi
765
766	shm_files=$(find /dev/shm -name "*.${id}" -printf "%f\n")
767
768	if [[ -z $shm_files ]]; then
769		echo "SHM File for specified PID or shared memory id: ${id} not found!"
770		return 1
771	fi
772	for n in $shm_files; do
773		tar -C /dev/shm/ -cvzf $output_dir/${n}_shm.tar.gz ${n}
774	done
775	return 0
776}
777
778# Parameters:
779# $1 - process pid
780# $2 - rpc address (optional)
781# $3 - max retries (optional)
782function waitforlisten() {
783	if [ -z "$1" ]; then
784		exit 1
785	fi
786
787	local rpc_addr="${2:-$DEFAULT_RPC_ADDR}"
788	local max_retries=${3:-100}
789
790	echo "Waiting for process to start up and listen on UNIX domain socket $rpc_addr..."
791	# turn off trace for this loop
792	xtrace_disable
793	local ret=0
794	local i
795	for ((i = max_retries; i != 0; i--)); do
796		# if the process is no longer running, then exit the script
797		#  since it means the application crashed
798		if ! kill -s 0 $1; then
799			echo "ERROR: process (pid: $1) is no longer running"
800			ret=1
801			break
802		fi
803
804		if $rootdir/scripts/rpc.py -t 1 -s "$rpc_addr" rpc_get_methods &> /dev/null; then
805			break
806		fi
807
808		sleep 0.5
809	done
810
811	xtrace_restore
812	if ((i == 0)); then
813		echo "ERROR: timeout while waiting for process (pid: $1) to start listening on '$rpc_addr'"
814		ret=1
815	fi
816	return $ret
817}
818
819function waitfornbd() {
820	local nbd_name=$1
821	local i
822
823	for ((i = 1; i <= 20; i++)); do
824		if grep -q -w $nbd_name /proc/partitions; then
825			break
826		else
827			sleep 0.1
828		fi
829	done
830
831	# The nbd device is now recognized as a block device, but there can be
832	#  a small delay before we can start I/O to that block device.  So loop
833	#  here trying to read the first block of the nbd block device to a temp
834	#  file.  Note that dd returns success when reading an empty file, so we
835	#  need to check the size of the output file instead.
836	for ((i = 1; i <= 20; i++)); do
837		dd if=/dev/$nbd_name of="$SPDK_TEST_STORAGE/nbdtest" bs=4096 count=1 iflag=direct
838		size=$(stat -c %s "$SPDK_TEST_STORAGE/nbdtest")
839		rm -f "$SPDK_TEST_STORAGE/nbdtest"
840		if [ "$size" != "0" ]; then
841			return 0
842		else
843			sleep 0.1
844		fi
845	done
846
847	return 1
848}
849
850function waitforbdev() {
851	local bdev_name=$1
852	local bdev_timeout=$2
853	local i
854	[[ -z $bdev_timeout ]] && bdev_timeout=2000 # ms
855
856	$rpc_py bdev_wait_for_examine
857
858	if $rpc_py bdev_get_bdevs -b $bdev_name -t $bdev_timeout; then
859		return 0
860	fi
861
862	return 1
863}
864
865function make_filesystem() {
866	local fstype=$1
867	local dev_name=$2
868	local i=0
869	local force
870
871	if [ $fstype = ext4 ]; then
872		force=-F
873	else
874		force=-f
875	fi
876
877	while ! mkfs.${fstype} $force ${dev_name}; do
878		if [ $i -ge 15 ]; then
879			return 1
880		fi
881		i=$((i + 1))
882		sleep 1
883	done
884
885	return 0
886}
887
888function killprocess() {
889	# $1 = process pid
890	if [ -z "$1" ]; then
891		return 1
892	fi
893
894	if kill -0 $1; then
895		if [ $(uname) = Linux ]; then
896			process_name=$(ps --no-headers -o comm= $1)
897		else
898			process_name=$(ps -c -o command $1 | tail -1)
899		fi
900		if [ "$process_name" = "sudo" ]; then
901			# kill the child process, which is the actual app
902			# (assume $1 has just one child)
903			local child
904			child="$(pgrep -P $1)"
905			echo "killing process with pid $child"
906			kill $child
907		else
908			echo "killing process with pid $1"
909			kill $1
910		fi
911
912		# wait for the process regardless if its the dummy sudo one
913		# or the actual app - it should terminate anyway
914		wait $1
915	else
916		# the process is not there anymore
917		echo "Process with pid $1 is not found"
918	fi
919}
920
921function iscsicleanup() {
922	echo "Cleaning up iSCSI connection"
923	iscsiadm -m node --logout || true
924	iscsiadm -m node -o delete || true
925	rm -rf /var/lib/iscsi/nodes/*
926}
927
928function stop_iscsi_service() {
929	if cat /etc/*-release | grep Ubuntu; then
930		service open-iscsi stop
931	else
932		service iscsid stop
933	fi
934}
935
936function start_iscsi_service() {
937	if cat /etc/*-release | grep Ubuntu; then
938		service open-iscsi start
939	else
940		service iscsid start
941	fi
942}
943
944function rbd_setup() {
945	# $1 = monitor ip address
946	# $2 = name of the namespace
947	if [ -z "$1" ]; then
948		echo "No monitor IP address provided for ceph"
949		exit 1
950	fi
951	if [ -n "$2" ]; then
952		if ip netns list | grep "$2"; then
953			NS_CMD="ip netns exec $2"
954		else
955			echo "No namespace $2 exists"
956			exit 1
957		fi
958	fi
959
960	if hash ceph; then
961		export PG_NUM=128
962		export RBD_POOL=rbd
963		export RBD_NAME=foo
964		$NS_CMD $rootdir/scripts/ceph/stop.sh || true
965		$NS_CMD $rootdir/scripts/ceph/start.sh $1
966
967		$NS_CMD ceph osd pool create $RBD_POOL $PG_NUM || true
968		$NS_CMD rbd create $RBD_NAME --size 1000
969	fi
970}
971
972function rbd_cleanup() {
973	if hash ceph; then
974		$rootdir/scripts/ceph/stop.sh || true
975		rm -f /var/tmp/ceph_raw.img
976	fi
977}
978
979function daos_setup() {
980	# $1 = pool name
981	# $2 = cont name
982	if [ -z "$1" ]; then
983		echo "No pool name provided"
984		exit 1
985	fi
986	if [ -z "$2" ]; then
987		echo "No cont name provided"
988		exit 1
989	fi
990
991	dmg pool create --size=10G $1 || true
992	daos container create --type=POSIX --label=$2 $1 || true
993}
994
995function daos_cleanup() {
996	local pool=${1:-testpool}
997	local cont=${2:-testcont}
998
999	daos container destroy -f $pool $cont || true
1000	sudo dmg pool destroy -f $pool || true
1001}
1002
1003function _start_stub() {
1004	# Disable ASLR for multi-process testing.  SPDK does support using DPDK multi-process,
1005	# but ASLR can still be unreliable in some cases.
1006	# We will reenable it again after multi-process testing is complete in kill_stub().
1007	# Save current setting so it can be restored upon calling kill_stub().
1008	_randomize_va_space=$(< /proc/sys/kernel/randomize_va_space)
1009	echo 0 > /proc/sys/kernel/randomize_va_space
1010	$rootdir/test/app/stub/stub $1 &
1011	stubpid=$!
1012	echo Waiting for stub to ready for secondary processes...
1013	while ! [ -e /var/run/spdk_stub0 ]; do
1014		# If stub dies while we wait, bail
1015		[[ -e /proc/$stubpid ]] || return 1
1016		sleep 1s
1017	done
1018	echo done.
1019}
1020
1021function start_stub() {
1022	if ! _start_stub "$@"; then
1023		echo "stub failed" >&2
1024		return 1
1025	fi
1026}
1027
1028function kill_stub() {
1029	if [[ -e /proc/$stubpid ]]; then
1030		kill $1 $stubpid
1031		wait $stubpid
1032	fi 2> /dev/null || :
1033	rm -f /var/run/spdk_stub0
1034	# Re-enable ASLR now that we are done with multi-process testing
1035	# Note: "1" enables ASLR w/o randomizing data segments, "2" adds data segment
1036	#  randomizing and is the default on all recent Linux kernels
1037	echo "${_randomize_va_space:-2}" > /proc/sys/kernel/randomize_va_space
1038}
1039
1040function run_test() {
1041	if [ $# -le 1 ]; then
1042		echo "Not enough parameters"
1043		echo "usage: run_test test_name test_script [script_params]"
1044		exit 1
1045	fi
1046
1047	xtrace_disable
1048	local test_name="$1"
1049	shift
1050
1051	if [ -n "$test_domain" ]; then
1052		export test_domain="${test_domain}.${test_name}"
1053	else
1054		export test_domain="$test_name"
1055	fi
1056
1057	timing_enter $test_name
1058	echo "************************************"
1059	echo "START TEST $test_name"
1060	echo "************************************"
1061	xtrace_restore
1062	time "$@"
1063	xtrace_disable
1064	echo "************************************"
1065	echo "END TEST $test_name"
1066	echo "************************************"
1067	timing_exit $test_name
1068
1069	export test_domain=${test_domain%"$test_name"}
1070	if [ -n "$test_domain" ]; then
1071		export test_domain=${test_domain%?}
1072	fi
1073
1074	if [ -z "$test_domain" ]; then
1075		echo "top_level $test_name" >> $output_dir/test_completions.txt
1076	else
1077		echo "$test_domain $test_name" >> $output_dir/test_completions.txt
1078	fi
1079	xtrace_restore
1080}
1081
1082function skip_run_test_with_warning() {
1083	echo "WARNING: $1"
1084	echo "Test run may fail if run with autorun.sh"
1085	echo "Please check your $rootdir/test/common/skipped_tests.txt"
1086}
1087
1088function print_backtrace() {
1089	# if errexit is not enabled, don't print a backtrace
1090	[[ "$-" =~ e ]] || return 0
1091
1092	local args=("${BASH_ARGV[@]}")
1093
1094	xtrace_disable
1095	# Reset IFS in case we were called from an environment where it was modified
1096	IFS=" "$'\t'$'\n'
1097	echo "========== Backtrace start: =========="
1098	echo ""
1099	for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
1100		local func="${FUNCNAME[$i]}"
1101		local line_nr="${BASH_LINENO[$((i - 1))]}"
1102		local src="${BASH_SOURCE[$i]}"
1103		local bt="" cmdline=()
1104
1105		if [[ -f $src ]]; then
1106			bt=$(nl -w 4 -ba -nln $src | grep -B 5 -A 5 "^${line_nr}[^0-9]" \
1107				| sed "s/^/   /g" | sed "s/^   $line_nr /=> $line_nr /g")
1108		fi
1109
1110		# If extdebug set the BASH_ARGC[i], try to fetch all the args
1111		if ((BASH_ARGC[i] > 0)); then
1112			# Use argc as index to reverse the stack
1113			local argc=${BASH_ARGC[i]} arg
1114			for arg in "${args[@]::BASH_ARGC[i]}"; do
1115				cmdline[argc--]="[\"$arg\"]"
1116			done
1117			args=("${args[@]:BASH_ARGC[i]}")
1118		fi
1119
1120		echo "in $src:$line_nr -> $func($(
1121			IFS=","
1122			printf '%s\n' "${cmdline[*]:-[]}"
1123		))"
1124		echo "     ..."
1125		echo "${bt:-backtrace unavailable}"
1126		echo "     ..."
1127	done
1128	echo ""
1129	echo "========== Backtrace end =========="
1130	xtrace_restore
1131	return 0
1132}
1133
1134function waitforserial() {
1135	local i=0
1136	local nvme_device_counter=1 nvme_devices=0
1137	if [[ -n "$2" ]]; then
1138		nvme_device_counter=$2
1139	fi
1140
1141	# Wait initially for min 4s to make sure all devices are ready for use. It seems
1142	# that we may be racing with a kernel where in some cases immediate disconnect may
1143	# leave dangling subsystem with no-op block devices which can't be used nor removed
1144	# (unless kernel is rebooted) and which start to negatively affect all the tests.
1145	sleep 4
1146	while ((i++ <= 15)); do
1147		nvme_devices=$(lsblk -l -o NAME,SERIAL | grep -c "$1")
1148		((nvme_devices == nvme_device_counter)) && return 0
1149		if ((nvme_devices > nvme_device_counter)); then
1150			echo "$nvme_device_counter device(s) expected, found $nvme_devices" >&2
1151		fi
1152		echo "Waiting for devices"
1153		sleep 1
1154	done
1155	return 1
1156}
1157
1158function waitforserial_disconnect() {
1159	local i=0
1160	while lsblk -o NAME,SERIAL | grep -q -w $1; do
1161		[ $i -lt 15 ] || break
1162		i=$((i + 1))
1163		echo "Waiting for disconnect devices"
1164		sleep 1
1165	done
1166
1167	if lsblk -l -o NAME,SERIAL | grep -q -w $1; then
1168		return 1
1169	fi
1170
1171	return 0
1172}
1173
1174function waitforblk() {
1175	local i=0
1176	while ! lsblk -l -o NAME | grep -q -w $1; do
1177		[ $i -lt 15 ] || break
1178		i=$((i + 1))
1179		sleep 1
1180	done
1181
1182	if ! lsblk -l -o NAME | grep -q -w $1; then
1183		return 1
1184	fi
1185
1186	return 0
1187}
1188
1189function waitforblk_disconnect() {
1190	local i=0
1191	while lsblk -l -o NAME | grep -q -w $1; do
1192		[ $i -lt 15 ] || break
1193		i=$((i + 1))
1194		sleep 1
1195	done
1196
1197	if lsblk -l -o NAME | grep -q -w $1; then
1198		return 1
1199	fi
1200
1201	return 0
1202}
1203
1204function waitforfile() {
1205	local i=0
1206	while [ ! -e $1 ]; do
1207		[ $i -lt 200 ] || break
1208		i=$((i + 1))
1209		sleep 0.1
1210	done
1211
1212	if [ ! -e $1 ]; then
1213		return 1
1214	fi
1215
1216	return 0
1217}
1218
1219function fio_config_gen() {
1220	local config_file=$1
1221	local workload=$2
1222	local bdev_type=$3
1223	local env_context=$4
1224	local fio_dir=$CONFIG_FIO_SOURCE_DIR
1225
1226	if [ -e "$config_file" ]; then
1227		echo "Configuration File Already Exists!: $config_file"
1228		return 1
1229	fi
1230
1231	if [ -z "$workload" ]; then
1232		workload=randrw
1233	fi
1234
1235	if [ -n "$env_context" ]; then
1236		env_context="env_context=$env_context"
1237	fi
1238
1239	touch $1
1240
1241	cat > $1 << EOL
1242[global]
1243thread=1
1244$env_context
1245group_reporting=1
1246direct=1
1247norandommap=1
1248percentile_list=50:99:99.9:99.99:99.999
1249time_based=1
1250ramp_time=0
1251EOL
1252
1253	if [ "$workload" == "verify" ]; then
1254		cat <<- EOL >> $config_file
1255			verify=sha1
1256			verify_backlog=1024
1257			rw=randwrite
1258		EOL
1259
1260		# To avoid potential data race issue due to the AIO device
1261		# flush mechanism, add the flag to serialize the writes.
1262		# This is to fix the intermittent IO failure issue of #935
1263		if [ "$bdev_type" == "AIO" ]; then
1264			if [[ $($fio_dir/fio --version) == *"fio-3"* ]]; then
1265				echo "serialize_overlap=1" >> $config_file
1266			fi
1267		fi
1268	elif [ "$workload" == "trim" ]; then
1269		echo "rw=trimwrite" >> $config_file
1270	else
1271		echo "rw=$workload" >> $config_file
1272	fi
1273}
1274
1275function fio_plugin() {
1276	# Setup fio binary cmd line
1277	local fio_dir=$CONFIG_FIO_SOURCE_DIR
1278	# gcc and clang uses different sanitizer libraries
1279	local sanitizers=(libasan libclang_rt.asan)
1280	local plugin=$1
1281	shift
1282
1283	local asan_lib=
1284	for sanitizer in "${sanitizers[@]}"; do
1285		asan_lib=$(ldd $plugin | grep $sanitizer | awk '{print $3}')
1286		if [[ -n "$asan_lib" ]]; then
1287			break
1288		fi
1289	done
1290
1291	# Preload the sanitizer library to fio if fio_plugin was compiled with it
1292	LD_PRELOAD="$asan_lib $plugin" "$fio_dir"/fio "$@"
1293}
1294
1295function fio_bdev() {
1296	fio_plugin "$rootdir/build/fio/spdk_bdev" "$@"
1297}
1298
1299function fio_nvme() {
1300	fio_plugin "$rootdir/build/fio/spdk_nvme" "$@"
1301}
1302
1303function get_lvs_free_mb() {
1304	local lvs_uuid=$1
1305	local lvs_info
1306	local fc
1307	local cs
1308	lvs_info=$($rpc_py bdev_lvol_get_lvstores)
1309	fc=$(jq ".[] | select(.uuid==\"$lvs_uuid\") .free_clusters" <<< "$lvs_info")
1310	cs=$(jq ".[] | select(.uuid==\"$lvs_uuid\") .cluster_size" <<< "$lvs_info")
1311
1312	# Change to MB's
1313	free_mb=$((fc * cs / 1024 / 1024))
1314	echo "$free_mb"
1315}
1316
1317function get_bdev_size() {
1318	local bdev_name=$1
1319	local bdev_info
1320	local bs
1321	local nb
1322	bdev_info=$($rpc_py bdev_get_bdevs -b $bdev_name)
1323	bs=$(jq ".[] .block_size" <<< "$bdev_info")
1324	nb=$(jq ".[] .num_blocks" <<< "$bdev_info")
1325
1326	# Change to MB's
1327	bdev_size=$((bs * nb / 1024 / 1024))
1328	echo "$bdev_size"
1329}
1330
1331function autotest_cleanup() {
1332	local autotest_es=$?
1333	xtrace_disable
1334
1335	# catch any stray core files and kill all remaining SPDK processes. Update
1336	# autotest_es in case autotest reported success but cores and/or processes
1337	# were left behind regardless.
1338
1339	process_core || autotest_es=1
1340	reap_spdk_processes || autotest_es=1
1341
1342	$rootdir/scripts/setup.sh reset
1343	$rootdir/scripts/setup.sh cleanup
1344	if [ $(uname -s) = "Linux" ]; then
1345		if [[ $SPDK_TEST_USE_IGB_UIO -eq 1 ]]; then
1346			[[ -e /sys/module/igb_uio ]] && rmmod igb_uio
1347		else
1348			modprobe -r uio_pci_generic
1349		fi
1350	fi
1351	rm -rf "$asan_suppression_file"
1352	if [[ -n $old_core_pattern ]]; then
1353		echo "$old_core_pattern" > /proc/sys/kernel/core_pattern
1354	fi
1355	if [[ -e /proc/$udevadm_pid/status ]]; then
1356		kill "$udevadm_pid" || :
1357	fi
1358
1359	shopt -s nullglob
1360	local storage_fallback_purge=("${TMPDIR:-/tmp}/spdk."??????)
1361	shopt -u nullglob
1362
1363	if ((${#storage_fallback_purge[@]} > 0)); then
1364		rm -rf "${storage_fallback_purge[@]}"
1365	fi
1366
1367	if ((autotest_es)); then
1368		if [[ $(uname) == FreeBSD ]]; then
1369			ps aux
1370		elif [[ $(uname) == Linux ]]; then
1371			# Get more detailed view
1372			grep . /proc/[0-9]*/status
1373			# Dump some extra info into kernel log
1374			echo "######## Autotest Cleanup Dump ########" > /dev/kmsg
1375			# Show cpus backtraces
1376			echo l > /proc/sysrq-trigger
1377			# Show mem usage
1378			echo m > /proc/sysrq-trigger
1379			# show task states
1380			echo t > /proc/sysrq-trigger
1381			# show blocked tasks
1382			echo w > /proc/sysrq-trigger
1383
1384		fi > "$output_dir/proc_list.txt" 2>&1 || :
1385	fi
1386	xtrace_restore
1387	return $autotest_es
1388}
1389
1390function freebsd_update_contigmem_mod() {
1391	if [ $(uname) = FreeBSD ]; then
1392		kldunload contigmem.ko || true
1393		if [ -n "$SPDK_RUN_EXTERNAL_DPDK" ]; then
1394			cp -f "$SPDK_RUN_EXTERNAL_DPDK/kmod/contigmem.ko" /boot/modules/
1395			cp -f "$SPDK_RUN_EXTERNAL_DPDK/kmod/contigmem.ko" /boot/kernel/
1396			cp -f "$SPDK_RUN_EXTERNAL_DPDK/kmod/nic_uio.ko" /boot/modules/
1397			cp -f "$SPDK_RUN_EXTERNAL_DPDK/kmod/nic_uio.ko" /boot/kernel/
1398		else
1399			cp -f "$rootdir/dpdk/build/kmod/contigmem.ko" /boot/modules/
1400			cp -f "$rootdir/dpdk/build/kmod/contigmem.ko" /boot/kernel/
1401			cp -f "$rootdir/dpdk/build/kmod/nic_uio.ko" /boot/modules/
1402			cp -f "$rootdir/dpdk/build/kmod/nic_uio.ko" /boot/kernel/
1403		fi
1404	fi
1405}
1406
1407function get_nvme_name_from_bdf() {
1408	blkname=()
1409
1410	nvme_devs=$(lsblk -d --output NAME | grep "^nvme") || true
1411	if [ -z "$nvme_devs" ]; then
1412		return
1413	fi
1414	for dev in $nvme_devs; do
1415		link_name=$(readlink /sys/block/$dev/device/device) || true
1416		if [ -z "$link_name" ]; then
1417			link_name=$(readlink /sys/block/$dev/device)
1418		fi
1419		bdf=$(basename "$link_name")
1420		if [ "$bdf" = "$1" ]; then
1421			blkname+=($dev)
1422		fi
1423	done
1424
1425	printf '%s\n' "${blkname[@]}"
1426}
1427
1428function get_nvme_ctrlr_from_bdf() {
1429	bdf_sysfs_path=$(readlink -f /sys/class/nvme/nvme* | grep "$1/nvme/nvme")
1430	if [[ -z "$bdf_sysfs_path" ]]; then
1431		return
1432	fi
1433
1434	printf '%s\n' "$(basename $bdf_sysfs_path)"
1435}
1436
1437# Get BDF addresses of all NVMe drives currently attached to
1438# uio-pci-generic or vfio-pci
1439function get_nvme_bdfs() {
1440	xtrace_disable
1441	bdfs=$(jq -r .config[].params.traddr <<< $($rootdir/scripts/gen_nvme.sh))
1442	if [[ -z $bdfs ]]; then
1443		echo "No devices to test on!"
1444		exit 1
1445	fi
1446	echo "$bdfs"
1447	xtrace_restore
1448}
1449
1450# Same as function above, but just get the first disks BDF address
1451function get_first_nvme_bdf() {
1452	head -1 <<< "$(get_nvme_bdfs)"
1453}
1454
1455function nvme_namespace_revert() {
1456	$rootdir/scripts/setup.sh
1457	sleep 1
1458	bdfs=$(get_nvme_bdfs)
1459
1460	$rootdir/scripts/setup.sh reset
1461
1462	for bdf in $bdfs; do
1463		nvme_ctrlr=/dev/$(get_nvme_ctrlr_from_bdf ${bdf})
1464		if [[ -z "$nvme_ctrlr" ]]; then
1465			continue
1466		fi
1467
1468		# Check Optional Admin Command Support for Namespace Management
1469		oacs=$(nvme id-ctrl ${nvme_ctrlr} | grep oacs | cut -d: -f2)
1470		oacs_ns_manage=$((oacs & 0x8))
1471
1472		if [[ "$oacs_ns_manage" -ne 0 ]]; then
1473			# This assumes every NVMe controller contains single namespace,
1474			# encompassing Total NVM Capacity and formatted as 512 block size.
1475			# 512 block size is needed for test/vhost/vhost_boot.sh to
1476			# successfully run.
1477
1478			unvmcap=$(nvme id-ctrl ${nvme_ctrlr} | grep unvmcap | cut -d: -f2)
1479			if [[ "$unvmcap" -eq 0 ]]; then
1480				# All available space already used
1481				continue
1482			fi
1483			tnvmcap=$(nvme id-ctrl ${nvme_ctrlr} | grep tnvmcap | cut -d: -f2)
1484			blksize=512
1485
1486			size=$((tnvmcap / blksize))
1487
1488			nvme detach-ns ${nvme_ctrlr} -n 0xffffffff -c 0 || true
1489			nvme delete-ns ${nvme_ctrlr} -n 0xffffffff || true
1490			nvme create-ns ${nvme_ctrlr} -s ${size} -c ${size} -b ${blksize}
1491			nvme attach-ns ${nvme_ctrlr} -n 1 -c 0
1492			nvme reset ${nvme_ctrlr}
1493			waitforfile "${nvme_ctrlr}n1"
1494		fi
1495	done
1496}
1497
1498# Get BDFs based on device ID, such as 0x0a54
1499function get_nvme_bdfs_by_id() {
1500	local bdfs=()
1501
1502	for bdf in $(get_nvme_bdfs); do
1503		device=$(cat /sys/bus/pci/devices/$bdf/device) || true
1504		if [[ "$device" == "$1" ]]; then
1505			bdfs+=($bdf)
1506		fi
1507	done
1508
1509	printf '%s\n' "${bdfs[@]}"
1510}
1511
1512function opal_revert_cleanup() {
1513	# The OPAL CI tests is only used for P4510 devices.
1514	mapfile -t bdfs < <(get_nvme_bdfs_by_id 0x0a54)
1515	if [[ -z ${bdfs[0]} ]]; then
1516		return 0
1517	fi
1518
1519	$SPDK_BIN_DIR/spdk_tgt &
1520	spdk_tgt_pid=$!
1521	waitforlisten $spdk_tgt_pid
1522
1523	bdf_id=0
1524	for bdf in "${bdfs[@]}"; do
1525		$rootdir/scripts/rpc.py bdev_nvme_attach_controller -b "nvme"${bdf_id} -t "pcie" -a ${bdf}
1526		# Ignore if this fails.
1527		$rootdir/scripts/rpc.py bdev_nvme_opal_revert -b "nvme"${bdf_id} -p test || true
1528		((++bdf_id))
1529	done
1530
1531	killprocess $spdk_tgt_pid
1532}
1533
1534function pap() {
1535	while read -r file; do
1536		cat <<- FILE
1537			--- $file ---
1538			$(<"$file")
1539			--- $file ---
1540		FILE
1541		rm -f "$file"
1542	done < <(find "$@" -type f | sort -u)
1543}
1544
1545function get_proc_paths() {
1546	local procs proc
1547	if [[ $(uname -s) == Linux ]]; then
1548		for proc in /proc/[0-9]*; do
1549			[[ -e $proc/exe ]] || continue
1550			procs[${proc##*/}]=$(readlink -f "$proc/exe")
1551		done
1552	elif [[ $(uname -s) == FreeBSD ]]; then
1553		while read -r proc _ _ path; do
1554			[[ -e $path ]] || continue
1555			procs[proc]=$path
1556		done < <(procstat -ab)
1557	fi
1558
1559	for proc in "${!procs[@]}"; do
1560		echo "$proc" "${procs[proc]}"
1561	done
1562}
1563
1564is_exec_file() { [[ -f $1 && $(file "$1") =~ ELF.+executable ]]; }
1565
1566function reap_spdk_processes() {
1567	local bins bin
1568	local misc_bins
1569
1570	while read -r bin; do
1571		is_exec_file "$bin" && misc_bins+=("$bin")
1572	done < <(find "$rootdir"/test/{app,env,event} -type f)
1573
1574	mapfile -t bins < <(readlink -f "$SPDK_BIN_DIR/"* "$SPDK_EXAMPLE_DIR/"* "${misc_bins[@]}")
1575
1576	local spdk_pid spdk_pids path
1577	while read -r spdk_pid path; do
1578		if [[ ${bins[*]/$path/} != "${bins[*]}" ]]; then
1579			echo "$path is still up ($spdk_pid), killing"
1580			spdk_pids[spdk_pid]=$path
1581		fi
1582	done < <(get_proc_paths)
1583
1584	((${#spdk_pids[@]} > 0)) || return 0
1585
1586	kill -SIGTERM "${!spdk_pids[@]}" 2> /dev/null || :
1587	# Wait a bit and then use the stick
1588	sleep 2
1589	kill -SIGKILL "${!spdk_pids[@]}" 2> /dev/null || :
1590
1591	return 1
1592}
1593
1594function is_block_zoned() {
1595	local device=$1
1596
1597	[[ -e /sys/block/$device/queue/zoned ]] || return 1
1598	[[ $(< "/sys/block/$device/queue/zoned") != none ]]
1599}
1600
1601function get_zoned_devs() {
1602	local -gA zoned_devs=()
1603	local nvme bdf
1604
1605	for nvme in /sys/block/nvme*; do
1606		if is_block_zoned "${nvme##*/}"; then
1607			zoned_devs["${nvme##*/}"]=$(< "$nvme/device/address")
1608		fi
1609	done
1610}
1611
1612# Define temp storage for all the tests. Look for 2GB at minimum
1613set_test_storage "${TEST_MIN_STORAGE_SIZE:-$((1 << 31))}"
1614
1615set -o errtrace
1616shopt -s extdebug
1617trap "trap - ERR; print_backtrace >&2" ERR
1618
1619PS4=' \t	-- ${BASH_SOURCE#${BASH_SOURCE%/*/*}/}@${LINENO} -- \$ '
1620if $SPDK_AUTOTEST_X; then
1621	# explicitly enable xtraces, overriding any tracking information.
1622	unset XTRACE_DISABLED
1623	unset XTRACE_NESTING_LEVEL
1624	xtrace_fd
1625	xtrace_enable
1626else
1627	xtrace_restore
1628fi
1629