How to use QEMU + KVM

2020-02-12

(last time edited: 2021-04-15)

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.

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 -aG kvm YOURUSER

Create a virtual disk space. I opted for 15G size.

$ qemu-img create virtdisk.qcow2 -f qcow2 15G

Download some .iso Linux distribution you wanna try. Or any OpenBSD / FreeBSD .iso. Or any .img such as Pwnagotchi images.

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.

$ qemu-system-x86_64 -nographic -name some_name -enable-kvm -cpu host -m 3G -cdrom /path/to/image.iso -boot d -hdd /path/to/virtdisk.qcow2 -nic model=virtio

The -nographic argument makes QEMU display stdio in terminal.

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/virtdisk.qcow2 finds your formatted virtual disk.

The -nic model=virtio argument to pass host network to QEMU.

Other arguments are self explanatory.

If you want to test enabling UEFI install OVMF and add this argument to the previous command.

-bios /path/to/ovmf/OVMF.fd

For GTK GUI add:

-display gtk

If the UEFI firmware was loaded correctly you should see TianoCore at the start.