# qemu-kvm

description "KVM"
author "Dustin Kirkland <kirkland@canonical.com>"

start on runlevel [2345]

pre-start script
	# Silently exit if the package isn't installed anymore
	if [ ! -e /usr/bin/qemu-system-x86_64 ]; then
		exit 0
	fi
	[ -r /etc/default/qemu-kvm ] && . /etc/default/qemu-kvm
	# Load the appropriate module, respecting blacklists
	if grep -qs "^flags.* vmx" /proc/cpuinfo; then
		modprobe -b kvm_intel "$KVM_NESTED" || true
	elif grep -qs "^flags.* svm" /proc/cpuinfo; then
		modprobe -b kvm_amd || true
	fi
	if running-in-container; then
		mknod /dev/kvm c 10 232 || true
		chown root:kvm /dev/kvm || true
		chmod g+rw /dev/kvm || true
	fi
	# Enable KSM, respecting the default configuration file
	if [ "$KSM_ENABLED" = "1" ]; then
		[ -w /sys/kernel/mm/ksm/run ] && echo 1 > /sys/kernel/mm/ksm/run || true
		if [ -w /sys/kernel/mm/ksm/sleep_millisecs ]; then
			if [ -n "$SLEEP_MILLISECS" ]; then
				echo "$SLEEP_MILLISECS" > /sys/kernel/mm/ksm/sleep_millisecs || true
			fi
		fi
	else
		[ -w /sys/kernel/mm/ksm/run ] && echo 0 > /sys/kernel/mm/ksm/run || true
	fi
	# If /etc/default/qemu-kvm says to, load vhost_net.  Default is not to.
	if [ "$VHOST_NET_ENABLED" = "1" ]; then
		modprobe -b vhost_net || true
	fi
	# mount hugepages if available and requested
	if [ "$KVM_HUGEPAGES" -eq "1" ]; then
		if ! grep -q hugetlbfs /proc/filesystems; then
			logger -t qemu-kvm "Error: hugepages not available in the kernel!"
		elif grep -q /run/hugepages/kvm /proc/mounts; then
			logger -t qemu-kvm "/run/hugepages/kvm already mounted"
		elif ! grep -q kvm /etc/group; then
			logger -t qemu-kvm "Error: group kvm does not exist!"
		else
			kvmgid=`grep kvm /etc/group | cut -d: -f 3`
			mkdir -p /run/hugepages/kvm
			mount -t hugetlbfs hugetlbfs-kvm -o mode=775,gid=$kvmgid /run/hugepages/kvm
		fi
	fi
end script
