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