xref: /linux/tools/testing/selftests/vsock/vmtest.sh (revision 4e870ac81df7e9628bdc08ff6f957a42e80582ee)
1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3#
4# Copyright (c) 2025 Meta Platforms, Inc. and affiliates
5#
6# Dependencies:
7#		* virtme-ng
8#		* busybox-static (used by virtme-ng)
9#		* qemu	(used by virtme-ng)
10#
11# shellcheck disable=SC2317,SC2119
12
13readonly SCRIPT_DIR="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
14readonly KERNEL_CHECKOUT=$(realpath "${SCRIPT_DIR}"/../../../../)
15
16source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
17
18readonly VSOCK_TEST="${SCRIPT_DIR}"/vsock_test
19readonly TEST_GUEST_PORT=51000
20readonly TEST_HOST_PORT=50000
21readonly TEST_HOST_PORT_LISTENER=50001
22readonly SSH_GUEST_PORT=22
23readonly SSH_HOST_PORT=2222
24readonly VSOCK_CID=1234
25readonly WAIT_PERIOD=3
26readonly WAIT_PERIOD_MAX=60
27readonly WAIT_QEMU=5
28readonly PIDFILE_TEMPLATE=/tmp/vsock_vmtest_XXXX.pid
29declare -A PIDFILES
30
31# virtme-ng offers a netdev for ssh when using "--ssh", but we also need a
32# control port forwarded for vsock_test.  Because virtme-ng doesn't support
33# adding an additional port to forward to the device created from "--ssh" and
34# virtme-init mistakenly sets identical IPs to the ssh device and additional
35# devices, we instead opt out of using --ssh, add the device manually, and also
36# add the kernel cmdline options that virtme-init uses to setup the interface.
37readonly QEMU_TEST_PORT_FWD="hostfwd=tcp::${TEST_HOST_PORT}-:${TEST_GUEST_PORT}"
38readonly QEMU_SSH_PORT_FWD="hostfwd=tcp::${SSH_HOST_PORT}-:${SSH_GUEST_PORT}"
39readonly KERNEL_CMDLINE="\
40	virtme.dhcp net.ifnames=0 biosdevname=0 \
41	virtme.ssh virtme_ssh_channel=tcp virtme_ssh_user=$USER \
42"
43readonly LOG=$(mktemp /tmp/vsock_vmtest_XXXX.log)
44readonly TEST_NAMES=(vm_server_host_client vm_client_host_server vm_loopback)
45readonly TEST_DESCS=(
46	"Run vsock_test in server mode on the VM and in client mode on the host."
47	"Run vsock_test in client mode on the VM and in server mode on the host."
48	"Run vsock_test using the loopback transport in the VM."
49)
50
51readonly USE_SHARED_VM=(vm_server_host_client vm_client_host_server vm_loopback)
52readonly NS_MODES=("local" "global")
53
54VERBOSE=0
55
56usage() {
57	local name
58	local desc
59	local i
60
61	echo
62	echo "$0 [OPTIONS] [TEST]..."
63	echo "If no TEST argument is given, all tests will be run."
64	echo
65	echo "Options"
66	echo "  -b: build the kernel from the current source tree and use it for guest VMs"
67	echo "  -q: set the path to or name of qemu binary"
68	echo "  -v: verbose output"
69	echo
70	echo "Available tests"
71
72	for ((i = 0; i < ${#TEST_NAMES[@]}; i++)); do
73		name=${TEST_NAMES[${i}]}
74		desc=${TEST_DESCS[${i}]}
75		printf "\t%-35s%-35s\n" "${name}" "${desc}"
76	done
77	echo
78
79	exit 1
80}
81
82die() {
83	echo "$*" >&2
84	exit "${KSFT_FAIL}"
85}
86
87check_result() {
88	local rc arg
89
90	rc=$1
91	arg=$2
92
93	cnt_total=$(( cnt_total + 1 ))
94
95	if [[ ${rc} -eq ${KSFT_PASS} ]]; then
96		cnt_pass=$(( cnt_pass + 1 ))
97		echo "ok ${cnt_total} ${arg}"
98	elif [[ ${rc} -eq ${KSFT_SKIP} ]]; then
99		cnt_skip=$(( cnt_skip + 1 ))
100		echo "ok ${cnt_total} ${arg} # SKIP"
101	elif [[ ${rc} -eq ${KSFT_FAIL} ]]; then
102		cnt_fail=$(( cnt_fail + 1 ))
103		echo "not ok ${cnt_total} ${arg} # exit=${rc}"
104	fi
105}
106
107add_namespaces() {
108	local orig_mode
109	orig_mode=$(cat /proc/sys/net/vsock/child_ns_mode)
110
111	for mode in "${NS_MODES[@]}"; do
112		echo "${mode}" > /proc/sys/net/vsock/child_ns_mode
113		ip netns add "${mode}0" 2>/dev/null
114		ip netns add "${mode}1" 2>/dev/null
115	done
116
117	echo "${orig_mode}" > /proc/sys/net/vsock/child_ns_mode
118}
119
120init_namespaces() {
121	for mode in "${NS_MODES[@]}"; do
122		# we need lo for qemu port forwarding
123		ip netns exec "${mode}0" ip link set dev lo up
124		ip netns exec "${mode}1" ip link set dev lo up
125	done
126}
127
128del_namespaces() {
129	for mode in "${NS_MODES[@]}"; do
130		ip netns del "${mode}0" &>/dev/null
131		ip netns del "${mode}1" &>/dev/null
132		log_host "removed ns ${mode}0"
133		log_host "removed ns ${mode}1"
134	done
135}
136
137vm_ssh() {
138	local ns_exec
139
140	if [[ "${1}" == init_ns ]]; then
141		ns_exec=""
142	else
143		ns_exec="ip netns exec ${1}"
144	fi
145
146	shift
147
148	${ns_exec} ssh -q -o UserKnownHostsFile=/dev/null -p "${SSH_HOST_PORT}" localhost "$@"
149
150	return $?
151}
152
153cleanup() {
154	terminate_pidfiles "${!PIDFILES[@]}"
155	del_namespaces
156}
157
158check_args() {
159	local found
160
161	for arg in "$@"; do
162		found=0
163		for name in "${TEST_NAMES[@]}"; do
164			if [[ "${name}" = "${arg}" ]]; then
165				found=1
166				break
167			fi
168		done
169
170		if [[ "${found}" -eq 0 ]]; then
171			echo "${arg} is not an available test" >&2
172			usage
173		fi
174	done
175
176	for arg in "$@"; do
177		if ! command -v > /dev/null "test_${arg}"; then
178			echo "Test ${arg} not found" >&2
179			usage
180		fi
181	done
182}
183
184check_deps() {
185	for dep in vng ${QEMU} busybox pkill ssh; do
186		if [[ ! -x $(command -v "${dep}") ]]; then
187			echo -e "skip:    dependency ${dep} not found!\n"
188			exit "${KSFT_SKIP}"
189		fi
190	done
191
192	if [[ ! -x $(command -v "${VSOCK_TEST}") ]]; then
193		printf "skip:    %s not found!" "${VSOCK_TEST}"
194		printf " Please build the kselftest vsock target.\n"
195		exit "${KSFT_SKIP}"
196	fi
197}
198
199check_vng() {
200	local tested_versions
201	local version
202	local ok
203
204	tested_versions=("1.33" "1.36" "1.37")
205	version="$(vng --version)"
206
207	ok=0
208	for tv in "${tested_versions[@]}"; do
209		if [[ "${version}" == *"${tv}"* ]]; then
210			ok=1
211			break
212		fi
213	done
214
215	if [[ ! "${ok}" -eq 1 ]]; then
216		printf "warning: vng version '%s' has not been tested and may " "${version}" >&2
217		printf "not function properly.\n\tThe following versions have been tested: " >&2
218		echo "${tested_versions[@]}" >&2
219	fi
220}
221
222handle_build() {
223	if [[ ! "${BUILD}" -eq 1 ]]; then
224		return
225	fi
226
227	if [[ ! -d "${KERNEL_CHECKOUT}" ]]; then
228		echo "-b requires vmtest.sh called from the kernel source tree" >&2
229		exit 1
230	fi
231
232	pushd "${KERNEL_CHECKOUT}" &>/dev/null
233
234	if ! vng --kconfig --config "${SCRIPT_DIR}"/config; then
235		die "failed to generate .config for kernel source tree (${KERNEL_CHECKOUT})"
236	fi
237
238	if ! make -j$(nproc); then
239		die "failed to build kernel from source tree (${KERNEL_CHECKOUT})"
240	fi
241
242	popd &>/dev/null
243}
244
245create_pidfile() {
246	local pidfile
247
248	pidfile=$(mktemp "${PIDFILE_TEMPLATE}")
249	PIDFILES["${pidfile}"]=1
250
251	echo "${pidfile}"
252}
253
254terminate_pidfiles() {
255	local pidfile
256
257	for pidfile in "$@"; do
258		if [[ -s "${pidfile}" ]]; then
259			pkill -SIGTERM -F "${pidfile}" > /dev/null 2>&1
260		fi
261
262		if [[ -e "${pidfile}" ]]; then
263			rm -f "${pidfile}"
264		fi
265
266		unset "PIDFILES[${pidfile}]"
267	done
268}
269
270vm_start() {
271	local pidfile=$1
272	local ns=$2
273	local logfile=/dev/null
274	local verbose_opt=""
275	local kernel_opt=""
276	local qemu_opts=""
277	local ns_exec=""
278	local qemu
279
280	qemu=$(command -v "${QEMU}")
281
282	if [[ "${VERBOSE}" -eq 1 ]]; then
283		verbose_opt="--verbose"
284		logfile=/dev/stdout
285	fi
286
287	qemu_opts="\
288		 -netdev user,id=n0,${QEMU_TEST_PORT_FWD},${QEMU_SSH_PORT_FWD} \
289		 -device virtio-net-pci,netdev=n0 \
290		 -device vhost-vsock-pci,guest-cid=${VSOCK_CID} \
291		--pidfile ${pidfile}
292	"
293
294	if [[ "${BUILD}" -eq 1 ]]; then
295		kernel_opt="${KERNEL_CHECKOUT}"
296	fi
297
298	if [[ "${ns}" != "init_ns" ]]; then
299		ns_exec="ip netns exec ${ns}"
300	fi
301
302	${ns_exec} vng \
303		--run \
304		${kernel_opt} \
305		${verbose_opt} \
306		--qemu-opts="${qemu_opts}" \
307		--qemu="${qemu}" \
308		--user root \
309		--append "${KERNEL_CMDLINE}" \
310		--rw  &> ${logfile} &
311
312	timeout "${WAIT_QEMU}" \
313		bash -c 'while [[ ! -s '"${pidfile}"' ]]; do sleep 1; done; exit 0'
314}
315
316vm_wait_for_ssh() {
317	local ns=$1
318	local i
319
320	i=0
321	while true; do
322		if [[ ${i} -gt ${WAIT_PERIOD_MAX} ]]; then
323			die "Timed out waiting for guest ssh"
324		fi
325
326		if vm_ssh "${ns}" -- true; then
327			break
328		fi
329		i=$(( i + 1 ))
330		sleep ${WAIT_PERIOD}
331	done
332}
333
334# derived from selftests/net/net_helper.sh
335wait_for_listener()
336{
337	local port=$1
338	local interval=$2
339	local max_intervals=$3
340	local protocol=tcp
341	local pattern
342	local i
343
344	pattern=":$(printf "%04X" "${port}") "
345
346	# for tcp protocol additionally check the socket state
347	[ "${protocol}" = "tcp" ] && pattern="${pattern}0A"
348
349	for i in $(seq "${max_intervals}"); do
350		if awk -v pattern="${pattern}" \
351			'BEGIN {rc=1} $2" "$4 ~ pattern {rc=0} END {exit rc}' \
352			/proc/net/"${protocol}"*; then
353			break
354		fi
355		sleep "${interval}"
356	done
357}
358
359vm_wait_for_listener() {
360	local ns=$1
361	local port=$2
362
363	vm_ssh "${ns}" <<EOF
364$(declare -f wait_for_listener)
365wait_for_listener ${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX}
366EOF
367}
368
369host_wait_for_listener() {
370	local ns=$1
371	local port=$2
372
373	if [[ "${ns}" == "init_ns" ]]; then
374		wait_for_listener "${port}" "${WAIT_PERIOD}" "${WAIT_PERIOD_MAX}"
375	else
376		ip netns exec "${ns}" bash <<-EOF
377			$(declare -f wait_for_listener)
378			wait_for_listener ${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX}
379		EOF
380	fi
381}
382
383vm_dmesg_oops_count() {
384	local ns=$1
385
386	vm_ssh "${ns}" -- dmesg 2>/dev/null | grep -c -i 'Oops'
387}
388
389vm_dmesg_warn_count() {
390	local ns=$1
391
392	vm_ssh "${ns}" -- dmesg --level=warn 2>/dev/null | grep -c -i 'vsock'
393}
394
395vm_vsock_test() {
396	local ns=$1
397	local host=$2
398	local cid=$3
399	local port=$4
400	local rc
401
402	# log output and use pipefail to respect vsock_test errors
403	set -o pipefail
404	if [[ "${host}" != server ]]; then
405		vm_ssh "${ns}" -- "${VSOCK_TEST}" \
406			--mode=client \
407			--control-host="${host}" \
408			--peer-cid="${cid}" \
409			--control-port="${port}" \
410			2>&1 | log_guest
411		rc=$?
412	else
413		vm_ssh "${ns}" -- "${VSOCK_TEST}" \
414			--mode=server \
415			--peer-cid="${cid}" \
416			--control-port="${port}" \
417			2>&1 | log_guest &
418		rc=$?
419
420		if [[ $rc -ne 0 ]]; then
421			set +o pipefail
422			return $rc
423		fi
424
425		vm_wait_for_listener "${ns}" "${port}"
426		rc=$?
427	fi
428	set +o pipefail
429
430	return $rc
431}
432
433host_vsock_test() {
434	local ns=$1
435	local host=$2
436	local cid=$3
437	local port=$4
438	local rc
439
440	local cmd="${VSOCK_TEST}"
441	if [[ "${ns}" != "init_ns" ]]; then
442		cmd="ip netns exec ${ns} ${cmd}"
443	fi
444
445	# log output and use pipefail to respect vsock_test errors
446	set -o pipefail
447	if [[ "${host}" != server ]]; then
448		${cmd} \
449			--mode=client \
450			--peer-cid="${cid}" \
451			--control-host="${host}" \
452			--control-port="${port}" 2>&1 | log_host
453		rc=$?
454	else
455		${cmd} \
456			--mode=server \
457			--peer-cid="${cid}" \
458			--control-port="${port}" 2>&1 | log_host &
459		rc=$?
460
461		if [[ $rc -ne 0 ]]; then
462			set +o pipefail
463			return $rc
464		fi
465
466		host_wait_for_listener "${ns}" "${port}"
467		rc=$?
468	fi
469	set +o pipefail
470
471	return $rc
472}
473
474log() {
475	local redirect
476	local prefix
477
478	if [[ ${VERBOSE} -eq 0 ]]; then
479		redirect=/dev/null
480	else
481		redirect=/dev/stdout
482	fi
483
484	prefix="${LOG_PREFIX:-}"
485
486	if [[ "$#" -eq 0 ]]; then
487		if [[ -n "${prefix}" ]]; then
488			awk -v prefix="${prefix}" '{printf "%s: %s\n", prefix, $0}'
489		else
490			cat
491		fi
492	else
493		if [[ -n "${prefix}" ]]; then
494			echo "${prefix}: " "$@"
495		else
496			echo "$@"
497		fi
498	fi | tee -a "${LOG}" > "${redirect}"
499}
500
501log_host() {
502	LOG_PREFIX=host log "$@"
503}
504
505log_guest() {
506	LOG_PREFIX=guest log "$@"
507}
508
509test_vm_server_host_client() {
510	if ! vm_vsock_test "init_ns" "server" 2 "${TEST_GUEST_PORT}"; then
511		return "${KSFT_FAIL}"
512	fi
513
514	if ! host_vsock_test "init_ns" "127.0.0.1" "${VSOCK_CID}" "${TEST_HOST_PORT}"; then
515		return "${KSFT_FAIL}"
516	fi
517
518	return "${KSFT_PASS}"
519}
520
521test_vm_client_host_server() {
522	if ! host_vsock_test "init_ns" "server" "${VSOCK_CID}" "${TEST_HOST_PORT_LISTENER}"; then
523		return "${KSFT_FAIL}"
524	fi
525
526	if ! vm_vsock_test "init_ns" "10.0.2.2" 2 "${TEST_HOST_PORT_LISTENER}"; then
527		return "${KSFT_FAIL}"
528	fi
529
530	return "${KSFT_PASS}"
531}
532
533test_vm_loopback() {
534	local port=60000 # non-forwarded local port
535
536	vm_ssh "init_ns" -- modprobe vsock_loopback &> /dev/null || :
537
538	if ! vm_vsock_test "init_ns" "server" 1 "${port}"; then
539		return "${KSFT_FAIL}"
540	fi
541
542
543	if ! vm_vsock_test "init_ns" "127.0.0.1" 1 "${port}"; then
544		return "${KSFT_FAIL}"
545	fi
546
547	return "${KSFT_PASS}"
548}
549
550shared_vm_test() {
551	local tname
552
553	tname="${1}"
554
555	for testname in "${USE_SHARED_VM[@]}"; do
556		if [[ "${tname}" == "${testname}" ]]; then
557			return 0
558		fi
559	done
560
561	return 1
562}
563
564shared_vm_tests_requested() {
565	for arg in "$@"; do
566		if shared_vm_test "${arg}"; then
567			return 0
568		fi
569	done
570
571	return 1
572}
573
574run_shared_vm_tests() {
575	local arg
576
577	for arg in "$@"; do
578		if ! shared_vm_test "${arg}"; then
579			continue
580		fi
581
582		run_shared_vm_test "${arg}"
583		check_result "$?" "${arg}"
584	done
585}
586
587run_shared_vm_test() {
588	local host_oops_cnt_before
589	local host_warn_cnt_before
590	local vm_oops_cnt_before
591	local vm_warn_cnt_before
592	local host_oops_cnt_after
593	local host_warn_cnt_after
594	local vm_oops_cnt_after
595	local vm_warn_cnt_after
596	local name
597	local rc
598
599	host_oops_cnt_before=$(dmesg | grep -c -i 'Oops')
600	host_warn_cnt_before=$(dmesg --level=warn | grep -c -i 'vsock')
601	vm_oops_cnt_before=$(vm_dmesg_oops_count "init_ns")
602	vm_warn_cnt_before=$(vm_dmesg_warn_count "init_ns")
603
604	name=$(echo "${1}" | awk '{ print $1 }')
605	eval test_"${name}"
606	rc=$?
607
608	host_oops_cnt_after=$(dmesg | grep -i 'Oops' | wc -l)
609	if [[ ${host_oops_cnt_after} -gt ${host_oops_cnt_before} ]]; then
610		echo "FAIL: kernel oops detected on host" | log_host
611		rc=$KSFT_FAIL
612	fi
613
614	host_warn_cnt_after=$(dmesg --level=warn | grep -c -i 'vsock')
615	if [[ ${host_warn_cnt_after} -gt ${host_warn_cnt_before} ]]; then
616		echo "FAIL: kernel warning detected on host" | log_host
617		rc=$KSFT_FAIL
618	fi
619
620	vm_oops_cnt_after=$(vm_dmesg_oops_count "init_ns")
621	if [[ ${vm_oops_cnt_after} -gt ${vm_oops_cnt_before} ]]; then
622		echo "FAIL: kernel oops detected on vm" | log_host
623		rc=$KSFT_FAIL
624	fi
625
626	vm_warn_cnt_after=$(vm_dmesg_warn_count "init_ns")
627	if [[ ${vm_warn_cnt_after} -gt ${vm_warn_cnt_before} ]]; then
628		echo "FAIL: kernel warning detected on vm" | log_host
629		rc=$KSFT_FAIL
630	fi
631
632	return "${rc}"
633}
634
635BUILD=0
636QEMU="qemu-system-$(uname -m)"
637
638while getopts :hvsq:b o
639do
640	case $o in
641	v) VERBOSE=1;;
642	b) BUILD=1;;
643	q) QEMU=$OPTARG;;
644	h|*) usage;;
645	esac
646done
647shift $((OPTIND-1))
648
649trap cleanup EXIT
650
651if [[ ${#} -eq 0 ]]; then
652	ARGS=("${TEST_NAMES[@]}")
653else
654	ARGS=("$@")
655fi
656
657check_args "${ARGS[@]}"
658check_deps
659check_vng
660handle_build
661
662echo "1..${#ARGS[@]}"
663
664cnt_pass=0
665cnt_fail=0
666cnt_skip=0
667cnt_total=0
668
669if shared_vm_tests_requested "${ARGS[@]}"; then
670	log_host "Booting up VM"
671	pidfile="$(create_pidfile)"
672	vm_start "${pidfile}" "init_ns"
673	vm_wait_for_ssh "init_ns"
674	log_host "VM booted up"
675
676	run_shared_vm_tests "${ARGS[@]}"
677	terminate_pidfiles "${pidfile}"
678fi
679
680echo "SUMMARY: PASS=${cnt_pass} SKIP=${cnt_skip} FAIL=${cnt_fail}"
681echo "Log: ${LOG}"
682
683if [ $((cnt_pass + cnt_skip)) -eq ${cnt_total} ]; then
684	exit "$KSFT_PASS"
685else
686	exit "$KSFT_FAIL"
687fi
688