CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

Trap and emulate

Think of a bank clerk who is allowed to count cash but must ask a manager to open the vault. A guest clerk who tries to open the vault alone would break the rules of the whole branch, so the manager is called each time. The analogy stops in one place. A manager is slow because of the walk, and a trap is slow because the processor must save a great deal of state first.

In plain words: A kernel assumes that it runs in the most privileged mode and may run any instruction: change the page table, disable interrupts, talk to devices (Level 0). A guest kernel cannot be given that power, because it would take over the machine. So the guest runs in a less privileged mode. When it tries a privileged instruction, the processor raises an exception and control passes to the hypervisor. The hypervisor looks at what the guest wanted, does the equivalent safe action on the guest's virtual state, and then resumes the guest after the instruction. This is trap and emulate. It works only if every instruction that can harm the machine is caught. The classic condition (Popek and Goldberg, 1974) says that the instructions which read or change privileged state, the sensitive instructions, must be a subset of the privileged ones, which trap. The old x86 processors broke the rule: some sensitive instructions did not trap, so early hypervisors used binary translation (rewriting the guest's code) or paravirtualisation (changing the guest to call the hypervisor). Intel VT-x and AMD-V (2005 and 2006) added a new mode in which the hardware traps what is needed.

A worked example. The guest runs cli (disable interrupts). On bare hardware it would stop all interrupts and freeze the machine for everyone. In a VM the instruction traps, and the hypervisor only clears a flag in the guest's virtual processor state, so that the virtual interrupts of this guest are held back. Other guests, and the host, keep receiving real interrupts. The guest believes it turned interrupts off, and it did, in its own world.

The key lines. A trap makes a privileged instruction safe and slow. The design problem of virtualisation is to trap as little as possible.

Trap and emulate

Trap and emulate is a way to run a guest kernel in a less privileged mode: when the guest runs an instruction that would change shared machine state, the processor traps to the hypervisor, which performs the safe equivalent on the guest's virtual state and resumes the guest.

Example: a guest's cli traps, and the hypervisor blocks only that guest's virtual interrupts.

Check yourself: 1. Why can a guest kernel not run privileged instructions directly? 2. What did the old x86 break in the Popek and Goldberg rule? 3. Name two ways that early hypervisors worked around it.