30 January 2011

Real hackweek, protected hackweek and long hackweek

I have been using KVM a lot, but never took time to understand how kvm works. I used some time from this hackweek to get rid of that regret.

Virtual Machine eXtensions instructions allow trap-and-emulate virtualization. And KVM exposes VMX in a convenient way to userspace in Linux. Virtual Machine Monitors(VMM) like qemu-kvm use the KVM API exposed by linux to emulate virtualize software.

x86_64 processors boot in real-mode. In this mode it can use only 16-bit addresses, ie., upto 1MByte RAM. The execution would begin at physical address 0xFFFFFFF0. Then the software has to switch to protected mode where protection and paging is possible. Paging is optional, but almost all OSes use demand paging extensively. Now 4 GBytes of linear address space is used. And then CPU can be switched to long mode i.e., 64-bit mode. Paging should be disabled in 32-bit mode, before switching to long mode. There are also other modes of operation like virtual-8086 mode to allow executing legacy real-mode software from protected mode, SMM for OS transparent execution of OEM specific code.

I had limited time and very very limited skill at hand. So aiming for the sky was not an option. Hence wrote a very simple VMM that directly starts the guest at address 0H, in 32-bit protected mode with paging disabled. And supports only insb and outsb as the only form of interaction possible for the guest. The guest is a simple static linked 32-bit program that doesn't use any library, and linked to start from 0x0. The guest simply reads a byte using insb and sends byte+1 back via outsb. The guest would halt, when it gets the, "Answer to the Ultimate Question of Life, the Universe, and Everything". The VMM reads the byte value to pass to the guest from stdin and prints its response in stdout.

The KVM API is really very easy to understand and use. But some knowledge of the processor was required to make use of it. Intel manuals helped there. I don't have good understanding of things yet, but something is better than nothing.

I was occupied by quite a lot of things in life and work in the recent past. So I wasn't really planning to participate and make this a real hackweek. Also a National holiday for Republic day of India, bang in the middle of the week prevents this hackweek from being a long hackweek! But seeing videos of my colleagues from various parts of world having fun, I couldn't resist and decided to go for the virtual hackweek. I thank my employer for giving me this protected hackweek, and let me learn/do things protected from everyday work.