#!/bin/sh
#

# PROVIDE: pciptdetach
# REQUIRE: swap
# BEFORE: devd
# KEYWORD: shutdown

. /etc/rc.subr

name=pciptdetach
rcvar=pciptdetach_enable

load_rc_config ${name}

: ${pciptdetach_enable:="YES"}

start_cmd="true"
stop_cmd="${name}"

pciptdetach()
{
	sysctl -n hw.hv_vendor | grep -q bhyve || return 0

	echo "Disabling passthrough adapters:"

        pptcandidate=`pciconf -l | grep -v -E \
	  "^([[:blank:]]|hostb|virtio|isab)[^@]+" | sed -n -E \
	 's/^[[:blank:]]*(^[[:alnum:]]+)@([^[:blank:]]+)(:[[:blank:]]).*$/\2/p'`

	for pcidev in ${pptcandidate}; do

        	drv_class=`pciconf -lv | grep -A 3 "@${pcidev}" | sed -n -E -e \
	 's/^[[:blank:]]*class[[:blank:]]+=[[:blank:]]+([^[:blank:]].*)$/\1/p' \
				-e 's/^([[:alnum:]]+)@.*$/\1/p' | tr '\n' ' '`

		# Don't disable mass storage devices, might be busy for shutdown
		[ X"${drv_class}" = X"${drv_class%mass storage*}" ] || continue

		# Make sure network adapters don't have active vlan(4) clones.
		if [ -z "${netstoped}" ] &&
				[ X"${drv_class}" != X"${drv_class%network*}" ]
		then
			/etc/rc.d/netif stop >/dev/null 2>&1 && netstoped=y
		fi

		# Non-PCIe devices and PCIe devices without FLR support are
		# known to cause RAM corruption.
		if ! pciconf -lc ${pcidev} | grep -A 20 PCI-Express |
							grep -q "[[:blank:]]FLR"
		then
		    devctl disable ${pcidev} >/dev/null 2>&1 ||
			echo " ${drv_class%% *}:FAILED"
		fi

	done
}

run_rc_command "$1"
