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