How to use QEMU + KVM

2020-02-12

(last time edited: 2021-11-23)

tags: virtualization

QEMU (Quick Emulator) is a generic, open source hardware emulator and virtualization suite. Often it is used in conjunction with acceleration in the form of a Type-I hypervisor such as KVM (Kernel-based Virtual Machine) or Xen. If no accelerator is used, QEMU will run entirely in user-space using its built in binary translator TCG (Tiny Code Generator). Using QEMU without an accelerator is relatively inefficient and slow.

If you wanna test Linux distribution iso files you must first need to know if your current Linux kernel was compiled with KVM support. Most binary Linux distributions are compiled with KVM support by default so no need to worry. If you're using Gentoo you probably know how to activate and compile this built-in option manually.

In most distributions QEMU comes in different separated packages.

qemu
qemu-img
qemu-system-x86_64
qemu-ui-gtk
qemu-ui-curses

Make sure KVM is activated in your BIOS.

In order to check if your KVM kernel module was loaded run this command.

$ lsmod | grep kvm

If it wasnt loaded you can try running this command.

# modprobe kvm

Also add your user to the 'kvm' group.

# usermod -G kvm -a <user>

# addgroup <user> kvm

Create a raw formatted virtual disk space. I opted for 60G size.

$ qemu-img create distro.img 60G

Download some .iso Linux distribution you wanna try. Could be any Linux distribution. Or any OpenBSD / FreeBSD .iso.

Run QEMU virtualizing your same CPU specs and 3G for RAM. Make sure you have enough RAM.

Since my current CPU architecture is x86_64 I will run qemu-system-x86_64. The binary for QEMU varies between distributions.

$ qemu-system-x86_64 -name <distro_name> -enable-kvm -cpu host -nic user -m 3G -cdrom /path/to/distro.iso -boot d -hdd /path/to/distro.img

You can add -display gtk for a nice graphical GTK UI, or -nographic or -display curses instead. Both are similar ways to get video output in terminal or console rather than using a graphical GTK user interface.

The -cpu host argument option mirrors your CPU.

The -boot d argument refers to the first CD-ROM virtualized drive found by QEMU.

The -hdd /path/to/image.img finds your formatted virtual disk.

-nic none to disable network.

If your system was installed you can boot the a partition and do not load any .iso file in the -cdrom parameter.

$ qemu-system-x86_64 -name <distro_name> -enable-kvm -cpu host -nic user -m 3G -boot a -hdd /path/to/distro.img

Other arguments are self explanatory.