#!/bin/sh
#
# qemu-kvm		Load/unload the KVM accelerator kernel modules.
#
# chkconfig: - 90 10
# description:	KVM accelerator kernel modules.
# processname: kvm
# config: /etc/sysconfig/qemu-kvm
# pidfile: /var/run/qemu-kvm.pid

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

SourceIfNotEmpty /etc/sysconfig/qemu-kvm

LOCKFILE=/var/lock/subsys/qemu-kvm
RETVAL=0

VirtType()
{
	local f

	for f in $(sed -n '/^flags[[:blank:]]*:/s/^.*:[[:blank:]]*//p' /proc/cpuinfo | head -1); do
		case $f in
			svm)
				KVM_OPTS="$KVM_OPTS $KVM_AMD_OPTS"
				echo "amd"
				return 0
				;;
			vmx)
				KVM_OPTS="$KVM_OPTS $KVM_INTEL_OPTS"
				echo "intel"
				return 0
				;;
		esac
	done
	return 1
}

start()
{
	local m
	if m=$(VirtType); then
		action "Loading KVM accelerator module (kvm, kvm_$m):" modprobe kvm_$m $KVM_OPTS
		RETVAL=$?
		[ $RETVAL = 0 ] && touch "$LOCKFILE" ||:
	else
		echo "CPU can't support hardware virtualization"'!' >&2
		RETVAL=1
	fi
	return $RETVAL
}

stop()
{
	local m
	if m=$(grep '^kvm_' /proc/modules); then
	    m=${m%% *}
	    action "Unloading KVM accelerator modules (kvm, $m):" modprobe -r $m
	fi
	RETVAL=$?
	[ $RETVAL = 0 ] && rm -f "$LOCKFILE" ||:
	return $RETVAL
}

restart()
{
	stop
	start
}

status()
{
	if grep -qs '^kvm_' /proc/modules; then
		echo "kvm module is loaded"
		return 0
	elif [ -f "$LOCKFILE" ]; then
		echo "kvm module is not loaded, but subsystem is locked"
		return 2
	else
		echo "kvm service is stopped"
		return 3
	fi
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	reload)
		restart
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		# Do nothing on package upgrade
		;;
	condreload)
		if [ -e "$LOCKFILE" ]; then
			reload
		fi
		;;
	status)
		status
		RETVAL=$?
		;;
	check)
		VirtType
		RETVEL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status|check}"
		RETVAL=1
esac

exit $RETVAL
