1#!/bin/sh
2#
3# $NetBSD: swap1,v 1.14 2022/04/16 18:15:20 andvar Exp $
4#
5
6# PROVIDE: localswap
7# REQUIRE: DISKS root
8# KEYWORD: shutdown
9
10$_rc_subr_loaded . /etc/rc.subr
11
12name="swap1"
13start_cmd="swap1_start"
14stop_cmd="swap1_stop"
15
16dev_free_tmpfs()
17{
18	# Generate a list of tmpfs filesystems that contain no device nodes,
19	# which can presumably be unmounted safely at shutdown time.
20	# Filenames are quoted and the list contains no unquoted newlines,
21	# so that the output can be reparsed as a single argument list.
22	mount -t tmpfs | while read -r line
23	do
24		fs=${line#tmpfs on }
25		fs=${fs% type tmpfs*}
26		find -x "${fs}" \( -type b -or -type c \) -exit 1 &&
27			echo -n "'${fs}' "
28	done
29}
30
31umount_vm_consumers()
32{
33	case ${swapoff_umount} in
34		auto)
35			swapoff_umount_fs="$(dev_free_tmpfs)"
36			;;
37		manual)
38			# swapoff_umount_fs set manually
39			;;
40	esac
41	# eval so that quotes within $swapoff_umount_fs are parsed properly
42	eval set -- "${swapoff_umount_fs}"
43	for fs in "$@"
44	do
45		echo "Forcibly unmounting ${fs}"
46		umount -ft tmpfs "${fs}"
47	done
48}
49
50#		Add all block-type swap devices; these might be necessary
51#		during disk checks.
52#
53swap1_start()
54{
55	# Treat exit status 2 from swapctl(8) as successful; it means
56	# "no error, but no suitable swap devices were configured".
57	#
58	if ! checkyesno no_swap; then
59		swapctl -A -t blk || [ $? = 2 ]
60	fi
61}
62
63#		Remove all block-type swap devices
64#
65swap1_stop()
66{
67	if checkyesno swapoff || [ -n "$rc_force" ]; then
68		umount_vm_consumers
69		echo "Removing block-type swap devices"
70		swapctl -U -t blk || [ $? = 2 ]
71	fi
72}
73
74load_rc_config swap
75run_rc_command "$1"
76