Search

Search papers and lessons

Virtual Machine

Level 2 · 11 min read

A virtual machine runs a guest operating system on software that imitates a whole computer; most guest instructions run directly on the real chip, and the host steps in only for privileged work.

On this page

  • Colour = topic mix
  • Systems
  • Algorithms
  • Discrete math
  • ReadReady to readNot yet

TL;DR

A virtual machine (VM) is a complete computer that exists only as software. It has its own virtual processor, memory and devices, and it runs its own Operating System, called the guest. The software that creates and runs these machines is the hypervisor, which sits on the real hardware. Most guest instructions run directly on the real processor at full speed, and the hypervisor takes control only when the guest tries to do something it must not do alone.

Builds on: Virtual Memory, because the guest's memory is mapped again by the host, and Instruction Set Architecture, because the guest's instructions must be the ones the real chip runs · Leads to: Linux Containers, which take the opposite trade: fewer layers, one shared kernel

Where it's used

Cloud servers. A cloud provider rents out a slice of a big physical server as a VM. The customer installs whatever operating system it wants, and the provider's hypervisor keeps each customer's machine separate from the others on the same hardware.

Testing on one computer. A developer who builds for Linux on a Mac or a Windows PC often runs a Linux VM beside the main system. A crash or a broken configuration inside the VM does not touch the host, and the VM can be copied or rolled back as one file.

Isolating risky workloads. A company that runs code from outside parties can give each job its own VM. Because each VM has its own guest kernel, a bug (such as a Buffer Overflow) that lets a program escape its guest has to get through a second, separate layer, the hypervisor, to reach the host.

How it works

Take one guest program with three instructions: ADD 2, which adds 2 to a register R0; OUT 7, which writes the byte 7 to a serial port; and HALT, which stops the machine. In this toy design, OUT and HALT are privileged instructions: only the operating system's kernel may run them, and the processor refuses them when a program runs in ordinary user mode. The hypervisor keeps the guest's state in memory: its program counter (PC) and register R0. At the start, PC is 0 and R0 is 0.

  1. Start the guest. The hypervisor copies the guest's saved state into the real processor and switches the processor to user mode, where privileged instructions are refused. Check: the real processor now holds PC = 0 and R0 = 0, and the guest is not in control of the hardware.
  2. Run an ordinary instruction. The real processor executes ADD 2 by itself, and R0 becomes 2. The hypervisor is not involved. Check: this instruction ran at native speed, which is what happens for most guest instructions.
  3. Trap on a privileged instruction. The guest reaches OUT 7. The processor refuses it in user mode and transfers control to the hypervisor. The processor saves the guest's state, a Context Switch from the guest to the hypervisor, and PC is now 1, pointing at the OUT instruction. Check: the hypervisor now holds the guest's state and can act for the guest.
  4. Emulate the device. The hypervisor reads the trapped instruction: write 7 to the serial port. The guest has no real serial port, so the hypervisor appends the byte 7 to a log file the host keeps for this guest. Check: the guest believes the byte left the machine, and it did leave the simulated device.
  5. Advance the guest. The hypervisor sets the guest's PC to the next instruction and leaves R0 at 2, exactly as if OUT had finished on real hardware. Check: the guest sees no gap in its program.
  6. Resume, then stop. The hypervisor loads the guest's state back into the processor and resumes it. The guest reaches HALT, which is privileged, so it traps again. The hypervisor marks this guest as stopped and keeps running any other guests. Check: stopping one guest does not stop the host.
sequenceDiagram
  participant G as Guest program
  participant CPU as Real processor
  participant H as Hypervisor
  G->>CPU: ADD 2 (ordinary)
  CPU-->>G: R0 = 2, no host involved
  G->>CPU: OUT 7 (privileged)
  CPU->>H: trap, save guest state
  H->>H: emulate the serial port
  H->>CPU: resume guest after OUT
  G->>CPU: HALT (privileged)
  CPU->>H: trap, stop this guest

The rule behind all six steps is the same: the guest runs directly whenever it is safe, and it is interrupted only when it touches something the hypervisor must control. This technique is called trap-and-emulate.

The math

Step 2 in symbols: the native cost

Let tt be the time the real processor takes for one ordinary guest instruction. If every instruction were ordinary, a guest would run at the native speed tt per instruction.

Step 3 in symbols: the cost of a trap

Let pp be the fraction of guest instructions that trap, and let TT be the time for one trap round trip, from the guest into the hypervisor and back, including the emulation work. The average time per guest instruction is

tˉ=t+p⋅T,\bar t = t + p \cdot T,

because a fraction pp of instructions cost TT instead of tt. The slowdown is

tˉt=1+p Tt.\frac{\bar t}{t} = 1 + \frac{p\,T}{t}.

The formula shows the design goal. Keep pp small, which means guests should do little privileged work, and keep TT small, which means the hypervisor's path must be short.

Beyond the walkthrough: two layers of memory mapping

The guest's page tables map a guest virtual address vv to a guest physical address gg. The guest does not know that gg is not a real address, because the host keeps its own table, which maps gg to a real host physical address hh. A memory access therefore goes through two tables:

v→guest tableg→host tableh.v \xrightarrow{\text{guest table}} g \xrightarrow{\text{host table}} h.

Suppose both tables have 4 levels, as in the Virtual Memory example. Each of the 4 guest table reads needs the guest table's address translated through the host table, which takes 4 reads. That makes 4×4=164 \times 4 = 16 reads. Add the 4 guest reads, and then the 4 host reads that translate the final data page: 16+4+4=2416 + 4 + 4 = 24 memory reads for one access with no caching. The translation cache from Virtual Memory is what makes this affordable in practice.

Worked examples

Example
1. One trap among ten instructions (tiny)

A guest runs 10 instructions. Nine are ordinary, and one is a privileged OUT that traps. Let the native time be t=1t = 1 ns and the trap round trip be T=1000T = 1000 ns.

  1. Nine ordinary instructions cost 9×1=99 \times 1 = 9 ns.
  2. The trapped instruction costs T=1000T = 1000 ns, in place of its native 1 ns.
  3. Total: 9+1000=10099 + 1000 = 1009 ns.
  4. Native time for the same 10 instructions would be 10×1=1010 \times 1 = 10 ns.
  5. Interpretation: the ratio is 1009/10=100.91009 / 10 = 100.9, so this short run is about 100 times slower. One trap dominated the whole run, which is why guests should avoid privileged work.
Example
2. The trap rate in a longer run (standard)

Use the same t=1t = 1 ns and T=1000T = 1000 ns, and compare two guests.

  1. Guest A traps on p=0.001p = 0.001 of its instructions, one in a thousand. Slowdown: 1+0.001×10001=1+1=21 + \dfrac{0.001 \times 1000}{1} = 1 + 1 = 2.
  2. Guest B traps on p=0.0001p = 0.0001, one in ten thousand. Slowdown: 1+0.0001×10001=1+0.1=1.11 + \dfrac{0.0001 \times 1000}{1} = 1 + 0.1 = 1.1.
  3. Guest B runs about 2/1.1≈1.82 / 1.1 \approx 1.8 times faster than guest A for the same work.
  4. Interpretation: the trap rate, not the speed of the processor, decides the cost. Reducing pp by a factor of 10 cut the overhead from 100 percent to 10 percent.
Example
3. Fitting guests into host memory (realistic)

A host has 64 GiB of RAM. Each guest VM is given 8 GiB of guest physical memory. The hypervisor must keep each guest's memory in host RAM for the guest to run at full speed.

  1. Six VMs need 6×8=486 \times 8 = 48 GiB. This fits, with 64−48=1664 - 48 = 16 GiB left for the host and its hypervisor.
  2. Ten VMs need 10×8=8010 \times 8 = 80 GiB. This is 80−64=1680 - 64 = 16 GiB more than the host has.
  3. With ten VMs, the hypervisor must page some guest memory out to disk. A guest page that is out on disk costs a disk read on each access, the same page-fault cost described in Virtual Memory.
  4. Interpretation: a host can promise more memory than it has only if the guests use less than they were given. Once they use it all, the guests slow down sharply.

Try it: the host has 64 GiB, and each VM is given 6 GiB. How many VMs fit in host RAM at full size, and how much memory is left over?

Answer: 64/6=10.6764 / 6 = 10.67, so 10 VMs fit. They use 10×6=6010 \times 6 = 60 GiB, which leaves 64−60=464 - 60 = 4 GiB.

Common mistakes and tradeoffs

It is tempting to think a virtual machine is just a container with more isolation. In fact a VM boots its own guest kernel and has its own virtual hardware. A container is a process on the host kernel, so the two differ in what they share, not only in how strong the walls are.

It is tempting to think that virtual machines are always emulators, translating Machine Code instructions one by one. In fact most VMs run the guest's instructions directly on the real processor of the same ISA. Emulation is needed only when the guest's ISA differs from the host's, and it is much slower, because each guest instruction must be translated.

It is tempting to think a hypervisor adds no cost. In fact the cost appears at traps, which were covered above, at device work that the hypervisor must emulate, and at memory translation, where two layers of tables make a miss more expensive.

ChoiceWhat is sharedStart-up and memory costIsolation strength
Process on the hostKernel, hardwareLowestWeakest: one kernel for all
ContainerKernelLowMedium: kernel bugs reach all containers
Virtual machineHardware only, through the hypervisorHigher: a full guest kernel per VMStrong: a second kernel stands between guests and host
EmulatorNothingHighest for mixed ISAsStrong, but slow

When to use a VM: run a different operating system, isolate untrusted workloads, or give each customer a machine of their own. When not to use one: when many small services must start in milliseconds, or when the workload is heavily privileged and traps on nearly every step.

History

In the 1960s, IBM ran several copies of an Operating System at once on one large computer, with a control program that gave each user an apparent machine of their own. The approach fell out of use as cheaper machines spread and one operating system per machine became normal. It returned in the 1990s, when x86 computers were powerful enough to run several guests. Chip makers later added hardware features that help a hypervisor, so many guest actions no longer need a trap. Cloud computing then made the VM the standard unit of rented computing.

Recap

  • A VM is a complete computer in software, with a guest operating system and virtual devices.
  • Most guest instructions run directly on the real processor. The hypervisor takes over at privileged instructions, through traps.
  • The cost of a VM is the trap rate times the trap cost, plus the extra work of translating memory through two tables.
  • A VM gives strong isolation because each guest has its own kernel, which costs more memory and start-up time than a container.
  • Next: Linux Containers for the lighter form of isolation that shares one kernel, and Operating System for the kernel that a guest runs on its own.

Check yourself

QuestionRecall: What is a hypervisor, and what does it do with a privileged instruction from a guest?Show answer

A hypervisor is the software that creates and runs virtual machines on the real hardware. When a guest runs a privileged instruction, the processor traps to the hypervisor, which checks the request, emulates its effect on the guest's virtual hardware, and then resumes the guest.

QuestionComputation: A guest runs 100 instructions. Ninety-nine are ordinary, each taking 1 ns, and one traps, taking 4000 ns. What is the average time per instruction, and what is the slowdown compared with 1 ns per instruction?Show answer

Total time is 99×1+4000=409999 \times 1 + 4000 = 4099 ns. The average is 4099/100=40.994099 / 100 = 40.99 ns per instruction. The slowdown is about 40.9940.99 times the native time of 1 ns.

QuestionWhy: Why does a VM need two layers of page tables, and what does the hypervisor's table do?Show answer

The guest builds its own page tables, which map its virtual addresses to what it believes are physical addresses. Those addresses are only guest physical addresses, so the hypervisor keeps a second table that maps them to real host memory. The guest's tables work unchanged, and the hypervisor controls which real memory each guest may use.

QuestionApplied: A team runs an untrusted program in a [[linux-containers|container]] on a shared host. They ask whether a VM would be safer, and what it would cost. Answer both parts.Show answer

A VM is safer for untrusted code, because the program would have to break out of its own guest kernel and then the hypervisor to reach the host, while a container shares the host kernel. The cost is a full guest kernel per VM, which uses more memory and takes longer to start. For jobs that start often, the team may accept that cost or keep containers with stronger sandboxing.

Sources