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