Skip to main content

Module ch07_tracing_qemu

Module ch07_tracing_qemu 

Source
Expand description

§Tracing QEMU

Most people who want traces of a full system run QEMU, not their own VMM. This chapter shows how to trace an unmodified QEMU binary running with -accel kvm, how to mark the part of the guest’s execution you want, and what the interposer does on your behalf.

§The idea: stand between QEMU and the kernel

QEMU talks to KVM through ioctl(2) on file descriptors for /dev/kvm, the VM, and each vCPU. libkvmtrace_preload.so defines its own ioctl and is loaded first with LD_PRELOAD, so every call passes through it. It watches a handful of requests and forwards everything unchanged:

RequestWhat the interposer does
KVM_CREATE_VM, KVM_CREATE_VCPUlearns the fds, wraps duplicates in kvm-ioctls types
KVM_SET_USER_MEMORY_REGION(2)records the slot: guest-physical range → address in QEMU’s memory, so the tracer can read guest RAM directly
KVM_SET_CPUID2hides the paravirtual steal-time feature (see below)
KVM_SET_REGS/SREGS/GUEST_DEBUGnotes that QEMU changed the vCPU behind the tracer’s back
KVM_RUNruns the tracing loop: every single-step exit is handled inside the interposer and the vCPU re-entered immediately; QEMU only sees the exits it would have seen anyway

QEMU never learns that it is being traced. We tested with the stock qemu-system-x86_64 10.2.4 from nixpkgs.

§Marking the region of interest

Tracing a whole boot is rarely what you want. The guest opens and closes the trace window by writing to an I/O port, 0x278 by default:

Guest doesMeaning
out dx, eax with EAX = 1START: every vCPU begins tracing
out dx, eax with EAX = 2STOP: every vCPU stops; files are written
in al, dxreturns 'K' if the tracer is present

From a Linux user program:

Listing 7-1: Marking a region in a guest program (C)

#include <sys/io.h>
#define PORT 0x278
static inline void mark(unsigned v) { __asm__ volatile("outl %0, %w1" :: "a"(v), "Nd"(PORT)); }

int main(void) {
    ioperm(PORT, 4, 1);          /* needs root (or CAP_SYS_RAWIO) */
    mark(1);                     /* START */
    do_the_work();
    mark(2);                     /* STOP */
}

The START out is the first record in the trace, and the STOP out is the last: the window closes one step after STOP, once KVM has completed that out.

§Choosing when to trace

Tracing slows the traced guest down by a factor of thousands, so you want it on only while it matters. Between windows the vCPUs run at full KVM speed: the interposer is still in the ioctl path, but it does nothing per instruction. Measured on the busy-loop guest of qemu-tests (matrix rounds completed in 10 s, three runs each):

rounds in 10 s
no interposer188–199 M
interposer loaded, tracing off188–189 M
one 0.5 s window, then off178 M (the 5 % spent in the window)

There are three ways to open and close windows, and they combine:

From the guest, with the markers above. Good when you know in the guest’s code where the interesting part is.

On a timer, with no guest cooperation:

$ KVMTRACE_START=after:30 KVMTRACE_DURATION=2 KVMTRACE_EVERY=60 KVMTRACE_WINDOWS=10 \
  KVMTRACE_OUT=trace LD_PRELOAD=... qemu-system-x86_64 -accel kvm ...

traces 2 seconds starting 30 seconds after the guest starts, then again every 60 seconds, 10 windows in all: a sampled trace of a long run. KVMTRACE_DURATION also closes marker-opened windows after that long.

By hand, from the host, while QEMU runs:

$ KVMTRACE_CONTROL=/tmp/kvmtrace.sock KVMTRACE_OUT=trace LD_PRELOAD=... qemu-system-x86_64 ... &
$ kvmtrace ctl /tmp/kvmtrace.sock start 1.5      # trace for 1.5 s
ok: window 0 -> trace/window-000
$ kvmtrace ctl /tmp/kvmtrace.sock start          # until told to stop
ok: window 1 -> trace/window-001
$ kvmtrace ctl /tmp/kvmtrace.sock stop
ok: window 1 closing
$ kvmtrace ctl /tmp/kvmtrace.sock status
idle; 2 windows written, 146951 instructions; 1 stale traps absorbed

The socket speaks plain text, one command per line (start [SECONDS], stop, status), so socat - UNIX-CONNECT:/tmp/kvmtrace.sock works too.

Each window is a complete trace of its own. When a run can have more than one window (KVMTRACE_EVERY, KVMTRACE_CONTROL, or KVMTRACE_WINDOWS other than 1), window n is written to KVMTRACE_OUT/window-nnn/; with one window, to KVMTRACE_OUT itself, as before. Instruction counts, sequence numbers and MacSim threads start afresh in each window.

Times are wall-clock seconds on the host. Inside a window the guest runs thousands of times slower, so “2 seconds” of tracing is a few hundred thousand instructions, not 2 seconds of guest execution. For a fixed number of instructions, use KVMTRACE_MAX, which applies per window.

§Running it

$ KVMTRACE_OUT=trace LD_PRELOAD=target/release/libkvmtrace_preload.so \
    qemu-system-x86_64 -accel kvm -cpu host -smp 2 -m 512 \
      -kernel bzImage -initrd initramfs.cpio -append "console=ttyS0" -nographic
...
kvmtrace: trace written to trace (1497833 instructions, 30 events, 0 gaps)

§Configuration

Everything is set through environment variables:

VariableDefaultMeaning
KVMTRACE_OUTkvmtrace-outoutput directory
KVMTRACE_STARTmarkernow: from the first instruction; after:SECONDS: that long after the guest starts
KVMTRACE_DURATIONnoneclose each window after this many seconds (2, 0.5, 500ms, 1m)
KVMTRACE_EVERYnoneopen a new window this many seconds after the previous one opened
KVMTRACE_WINDOWS1 (unlimited with EVERY or CONTROL)at most this many windows; 0: unlimited
KVMTRACE_CONTROLnonepath of a Unix socket for kvmtrace ctl
KVMTRACE_TF_GUARD1absorb stale single-step traps between windows (below)
KVMTRACE_PORT0x278marker port
KVMTRACE_ORDERserializedconcurrent for per-vCPU order only (chapter 6)
KVMTRACE_FETCH1record instruction fetches in .kvt
KVMTRACE_PHYS1translate to guest-physical addresses
KVMTRACE_FOLLOW_HANDLERS1entry breakpoints (chapter 5)
KVMTRACE_BLOCKIRQ1hold interrupts while stepping…
KVMTRACE_IRQ_EVERY50000…and let them in every this many instructions (0: never)
KVMTRACE_MACSIM / KVMTRACE_SIDE / KVMTRACE_KVT1 / 1 / 1which files to write: MacSim .raw, its sideband .side (CS, CPL, CR3, physical addresses, bytes), extended .kvt
KVMTRACE_MAXnoneclose the window after this many instructions
KVMTRACE_KEEP_STEAL_TIME0do not hide steal time from the guest
KVMTRACE_VERBOSE0progress messages on stderr

§Three things a real kernel needs

A test VM like MiniVm behaves; Linux needed three adjustments, found by watching the tracer get stuck or the guest crash.

Steal time. With KVM’s paravirtual steal-time feature, the guest reads a record that the host updates, in a loop that retries until the record’s version number is the same before and after the read. KVM bumps that version every time it loads the vCPU, which is every KVM_RUN call, which under single-stepping is every instruction. The two reads never agree and the guest spins forever in kvm_steal_clock. The interposer therefore clears the KVM_FEATURE_STEAL_TIME bit when QEMU sets the vCPU’s CPUID. The guest loses its steal-time statistics, nothing else. This is a guest-visible change, so it is switchable.

Interrupt pacing. Single-stepping slows the guest down by a factor of thousands, but its timers keep running on host time. Delivered as they fall due, timer interrupts arrive faster than the slowed guest can handle them, and Linux soft-locks in its interrupt handlers. By default the interposer asks KVM to hold interrupts while stepping (KVM_GUESTDBG_BLOCKIRQ) and opens a short window every 50 000 instructions. Interrupts are delayed, never dropped, and the handlers that do run are traced like everything else. The trade-off, interrupt timing that is not the guest’s natural timing, is discussed in chapter 10.

Stale trap flags. While KVM single-steps a vCPU, the hardware trap flag (TF) is on. KVM hides it from register reads, but not from the copies of RFLAGS that the guest saves itself: every interrupt frame, every pushf. If a window closes while such a copy is still live (here: inside a paced timer interrupt that had interrupted a user program), the handler’s iret later restores TF, the CPU traps after the next instruction, and Linux kills the program with SIGTRAP. We first saw it as a kernel panic when timed windows killed init. Marker-closed windows rarely hit it, because they close in user mode after handlers have returned. Rarely is not never.

The interposer therefore leaves each vCPU in a guard state after a window: no stepping and no breakpoints, but a debug exception exits to the interposer instead of going to the guest. A single-step trap with TF set is a stale one. The guard clears TF and lets the guest continue, which is what the guest would have done had the copy never had it (absorb_stale_single_step). In the tests above, one such trap was absorbed per window; the guest ran to completion every time; and the guard costs nothing measurable. Its price is inside the guest: while it is on, the guest’s own hardware breakpoints (DR0–DR7) do not fire, and a debugger in the guest that single-steps has its traps absorbed. Set KVMTRACE_TF_GUARD=0 if you debug inside the guest and accept the risk above.

§Several vCPUs

QEMU runs each vCPU in its own thread, and the interposer does all per-vCPU work on that thread. Two cross-vCPU actions need care:

  • Telling the others. When one vCPU hits START or STOP, the interposer kicks the other vCPU threads with SIGUSR1, the same signal QEMU uses for this, so their KVM_RUN returns and they notice the change.
  • The breakpoint rendezvous from chapter 5. Each vCPU prearms and waits for all the others before planting starts; at STOP, all wait until the breakpoints are gone before any switches debugging off. The waits are bounded: after 100 ms a waiting vCPU returns EINTR to QEMU (exactly what a kick does) so that QEMU can do any cross-vCPU work it needs, and then comes back and keeps waiting.

§Kernel ASLR and reproducibility

If you plan to compare runs (as chapter 9 does), boot the guest with nokaslr norandmaps so that kernel and user addresses are the same every time.