From cff3b3e511c27d378b07df38802fc463fc8e84b3 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Mon, 23 Nov 2026 14:38:13 -0300 Subject: [PATCH 1/2] lab: the ledger's kernel_zero on the kernel's sched clock, not CLOCK_MONOTONIC (#644) The trace and the journal are on CLOCK_MONOTONIC, which runs on jiffies from timekeeping_init until the switch to kvm-clock and loses the ticks it misses: 18-21 ms nested, 11-14 on metal. The ledger took its 0 for the kernel's, so kernel_zero and qemu_start read that much late. The kernel prints both clocks at one tick ("sched_clock: Marking stable"); the ledger moves the trace and the journal forward by their difference, and refuses a journal without the line. Co-Authored-By: Claude Opus 5.5 --- internal/lab/ledger.go | 70 +++++++++++++++++++++++++++--------- internal/lab/ledger_test.go | 72 +++++++++++++++++++++---------------- internal/lab/ledgerprobe.go | 2 ++ 3 files changed, 97 insertions(+), 47 deletions(-) diff --git a/internal/lab/ledger.go b/internal/lab/ledger.go index aa323d9d..f51b76ca 100644 --- a/internal/lab/ledger.go +++ b/internal/lab/ledger.go @@ -19,11 +19,12 @@ import ( // boot and the login change hands. It is a diagnostic and never a goal number (docs/measuring.md, // "The ledger"). // -// One clock carries all of it: the kernel's CLOCK_MONOTONIC, which the trace is put on -// (trace_clock=mono), the journal stamps its lines with, and /proc/uptime reads. The host's clock -// meets it through markers the guest writes into the trace on the host's request (Trip): the -// kernel's 0 lies between each request's send, less the marker's time, and its answer's arrival, -// less the same. +// One clock carries all of it: the kernel's sched clock, kvm-clock less what it read in +// kvm_sched_clock_init, whose 0 is the kernel's 0. The trace (trace_clock=mono) and the journal are +// on CLOCK_MONOTONIC, which runs behind it by MonotonicLag, and the ledger moves both forward by +// that. The host's clock meets the sched clock through markers the guest writes into the trace on +// the host's request (Trip): the kernel's 0 lies between each request's send, less the marker's +// time, and its answer's arrival, less the same. // Ledger is what ledger.json holds, in ms. Times on the kernel's clock are from its 0; FirstLogin // and KernelZero are from the moment before QEMU is exec'd. @@ -35,14 +36,20 @@ type Ledger struct { // kernel's decompression, which no clock in the guest sees. KernelZero float64 `json:"kernel_zero"` KernelZeroError float64 `json:"kernel_zero_error"` + // MonotonicLag is how far CLOCK_MONOTONIC runs behind the kernel's clock once both run on + // kvm-clock: what it did not count while it ran on jiffies, from timekeeping_init until the + // switch to kvm-clock at fs_initcall. It is 18-21 ms nested and 11-14 on metal, and without it + // the kernel's 0 read that much late (#644). + MonotonicLag float64 `json:"monotonic_lag"` // QEMUExec is where spin-machine exec'd QEMU, and QEMUExecError half the bracket the host's // polling put it in: before it is spin-machine's own start. QEMUExec float64 `json:"qemu_exec"` QEMUExecError float64 `json:"qemu_exec_error"` - // Running is where the machine went to running and its vCPU ran the guest's first instruction: - // KernelZero less the kvm-clock the kernel read as it made kvm-clock the scheduler's clock, which - // QEMU zeroed at that moment (schedOffset). From QEMUExec to Running is QEMU's start and the held - // start's monitor; from Running to KernelZero, the firmware, the bzImage's decompression and the + // Running is kvm-clock's 0: KernelZero less the kvm-clock the kernel read as it made kvm-clock + // the scheduler's clock (schedOffset). QEMU zeroes kvm-clock as the machine goes to running, but + // KVM bases that 0 on its master clock's last update, so Running lies 2-5 ms before QEMU's + // KVM_SET_CLOCK (#611, #665). From QEMUExec to Running is QEMU's start and the held start's + // monitor; from Running to KernelZero, the firmware, the bzImage's decompression and the // kernel's setup until its clock runs. Running float64 `json:"running"` // LoginEnd is the login's command's exit on the kernel's clock: where the trace's account ends. @@ -136,6 +143,13 @@ func newLedger(in ledgerInput) (Ledger, error) { if err != nil { return Ledger{}, err } + lag, err := monotonicLag(in.Journal) + if err != nil { + return Ledger{}, err + } + for i := range events { + events[i].at += lag + } b := replay(events) zero, zeroErr, err := b.kernelZero(in.Trips) if err != nil { @@ -154,9 +168,9 @@ func newLedger(in ledgerInput) (Ledger, error) { return Ledger{}, err } owner := b.owners(parseUnits(in.Units)) - l := Ledger{FirstLogin: in.FirstLogin, KernelZero: zero, KernelZeroError: zeroErr, + l := Ledger{FirstLogin: in.FirstLogin, KernelZero: zero, KernelZeroError: zeroErr, MonotonicLag: lag, QEMUExec: exec, QEMUExecError: execErr, Running: running, LoginEnd: end, - Residue: in.FirstLogin - zero - end, Breaks: b.breaks, Marks: loginMarks(in.Journal)} + Residue: in.FirstLogin - zero - end, Breaks: b.breaks, Marks: loginMarks(in.Journal, lag)} for i, c := range cuts { to := end if i+1 < len(cuts) { @@ -395,9 +409,9 @@ func (b *boot) kernelZero(trips []Trip) (zero, halfWidth float64, err error) { // schedOffset is the kvm-clock the kernel read as it made kvm-clock the scheduler's clock, in ms: // QEMU zeroes kvm-clock as the machine goes to running (hw/i386/kvm/clock.c, // kvmclock_vm_state_change, KVM_SET_CLOCK with the 0 a machine never run has), and the kernel's -// clock, CLOCK_MONOTONIC's 0 included, starts from that reading (arch/x86/kernel/kvmclock.c, -// kvm_sched_clock_init, which prints it in ns despite the word; timekeeping_init's boot offset is -// local_clock()). boot:firmware-stages places the kernel's clock on QEMU's trace by the same line. +// sched clock starts from that reading (arch/x86/kernel/kvmclock.c, kvm_sched_clock_init, which +// prints it in ns despite the word). boot:firmware-stages places the kernel's clock on QEMU's +// trace by the same line. func schedOffset(journal string) (float64, error) { m := reSchedOffset.FindStringSubmatch(journal) if m == nil { @@ -409,6 +423,27 @@ func schedOffset(journal string) (float64, error) { var reSchedOffset = regexp.MustCompile(`kvm-clock: using sched offset of (\d+) cycles`) +// monotonicLag is how far CLOCK_MONOTONIC is behind the kernel's sched clock once both run on +// kvm-clock, in ms. CLOCK_MONOTONIC starts at the sched clock in timekeeping_init, then runs on +// jiffies until the switch to kvm-clock at fs_initcall, and the ticks it misses are lost for good. +// At late_initcall the kernel prints both clocks as one tick read them (kernel/sched/clock.c, +// __set_sched_clock_stable: "Marking stable (ktime_get_ns, __gtod_offset)->(sched_clock, +// __sched_clock_offset)"). With it, the ledger's kernel_zero lands 0.02-0.15 ms after a port +// write at the sched clock's 0, against 11.6-20.9 ms without (labs 45177818419, 45177817516, #644). +// dmesg's own clock is neither: from that line on it is the sched clock plus +// __sched_clock_offset. +func monotonicLag(journal string) (float64, error) { + m := reSchedStable.FindStringSubmatch(journal) + if m == nil { + return 0, fmt.Errorf("the journal has no \"sched_clock: Marking stable\" line: without it nothing says how far CLOCK_MONOTONIC, the trace's clock, is behind the kernel's sched clock") + } + gtod, _ := strconv.ParseFloat(m[1], 64) // mutate-exempt: ParseFloat reads any bitSize but 32 as 64 + raw, _ := strconv.ParseFloat(m[2], 64) // mutate-exempt: ParseFloat reads any bitSize but 32 as 64 + return (raw - gtod) / 1e6, nil +} + +var reSchedStable = regexp.MustCompile(`sched_clock: Marking stable \((\d+), -?\d+\)->\((\d+), -?\d+\)`) + // The windows the ledger probe records by name. const ( windowHandoff = "spin's handoff, to PID 1's exec of systemd" @@ -659,15 +694,16 @@ var loginPhases = []struct{ name, text string }{ {"the command started", "Starting session: command"}, } -// loginMarks are the first journal line of each login phase, in the order they came. -func loginMarks(journal string) []Mark { +// loginMarks are the first journal line of each login phase, in the order they came, moved by lag +// from the journal's CLOCK_MONOTONIC to the kernel's clock. +func loginMarks(journal string, lag float64) []Mark { var marks []Mark for _, p := range loginPhases { for line := range strings.Lines(journal) { m := journalLine.FindStringSubmatch(strings.TrimRight(line, "\n")) if m != nil && strings.Contains(m[2], p.text) { s, _ := strconv.ParseFloat(m[1], 64) // mutate-exempt: ParseFloat reads any bitSize but 32 as 64 - marks = append(marks, Mark{p.name, s * 1000, m[2]}) + marks = append(marks, Mark{p.name, s*1000 + lag, m[2]}) break } } diff --git a/internal/lab/ledger_test.go b/internal/lab/ledger_test.go index 40c858af..0622ed70 100644 --- a/internal/lab/ledger_test.go +++ b/internal/lab/ledger_test.go @@ -104,13 +104,16 @@ func ledgerFixture(t *testing.T) ledgerInput { t.Fatal(err) } return ledgerInput{ - // The run's journal kept only the login's lines; the kernel's kvm-clock line is as its - // kernel prints it, with an offset that puts the machine's running at 70.0215. - Trace: string(trace), Journal: "[ 0.000000] localhost kernel: kvm-clock: using sched offset of 30000000 cycles\n" + string(journal), + // The run's journal kept only the login's lines; the kernel's two lines are as its kernel + // prints them, with an offset that puts the machine's running at 50.0215, and + // CLOCK_MONOTONIC 20 ms behind the sched clock. + Trace: string(trace), Journal: "[ 0.000000] localhost kernel: kvm-clock: using sched offset of 30000000 cycles\n" + + "[ 0.000000] localhost kernel: sched_clock: Marking stable (60000000, 5000000)->(80000000, -15000000)\n" + string(journal), // sshd (ssh.service), logind, journald, PID 1 and root's manager, as ledger-units prints them. Units: "1 /init.scope\n61 /system.slice/systemd-journald.service\n68 /system.slice/systemd-logind.service\n77 /system.slice/ssh.service\n97 /user.slice/user-0.slice/user@0.service/init.scope\n", - // The markers are at 357.045, 357.297 and 357.412 ms on the kernel's clock: these put its 0 - // in [99.955, 100.055], [99.953, 100.103] and [99.988, 100.088] on the host's. + // The markers are at 357.045, 357.297 and 357.412 ms on CLOCK_MONOTONIC, 20 more on the + // kernel's clock: these put its 0 in [79.955, 80.055], [79.953, 80.103] and [79.988, 80.088] + // on the host's. Trips: []Trip{{1, 457.000, 457.100}, {2, 457.250, 457.400}, {3, 457.400, 457.500}}, FirstLogin: 420, QEMUExecLo: 17.9, QEMUExecHi: 18.1, @@ -120,9 +123,9 @@ func ledgerFixture(t *testing.T) ledgerInput { func near(a, b float64) bool { return math.Abs(a-b) < 1e-6 } // A real boot's ledger: its windows tile the kernel's clock from 0 to the command's exit, cut -// where the trace shows the boot and the login change hands; on its one vCPU each window's CPU -// adds up to its length; and the host's clock, the kernel's and the residue add up to the first -// login the host measured. +// where the trace shows the boot and the login change hands, each the trace's time moved forward +// by CLOCK_MONOTONIC's lag; on its one vCPU each window's CPU adds up to its length; and the +// host's clock, the kernel's and the residue add up to the first login the host measured. func TestARealBootsLedgerAddsUp(t *testing.T) { l, err := newLedger(ledgerFixture(t)) if err != nil { @@ -131,12 +134,12 @@ func TestARealBootsLedgerAddsUp(t *testing.T) { // The cuts, read from the trace by hand: PID 1's exec of /sbin/init, sshd-session's exec, // sshd-auth's exec and exit, the fork of the login's process, its exec of bash and of // /usr/bin/true, and true's exit. - want := []float64{0, 83.224, 252.151, 266.672, 296.796, 310.239, 312.642, 318.157} + want := []float64{0, 103.224, 272.151, 286.672, 316.796, 330.239, 332.642, 338.157} if len(l.Windows) != len(want) { t.Fatalf("%d windows; want %d: %+v", len(l.Windows), len(want), l.Windows) } for i, w := range l.Windows { - end := 318.820 + end := 338.820 if i+1 < len(want) { end = want[i+1] } @@ -151,13 +154,13 @@ func TestARealBootsLedgerAddsUp(t *testing.T) { t.Errorf("window %q: its CPU adds up to %v of its %v", w.Name, sum, w.End-w.Start) } } - if !near(l.KernelZero, 100.0215) || !near(l.KernelZeroError, 0.0335) || !near(l.LoginEnd, 318.82) || !near(l.Residue, 420-100.0215-318.82) || l.Breaks != 0 { - t.Errorf("kernel's 0 %v ± %v, login end %v, residue %v, breaks %d", l.KernelZero, l.KernelZeroError, l.LoginEnd, l.Residue, l.Breaks) + if !near(l.KernelZero, 80.0215) || !near(l.KernelZeroError, 0.0335) || !near(l.MonotonicLag, 20) || !near(l.LoginEnd, 338.82) || !near(l.Residue, 420-80.0215-338.82) || l.Breaks != 0 { + t.Errorf("kernel's 0 %v ± %v, lag %v, login end %v, residue %v, breaks %d", l.KernelZero, l.KernelZeroError, l.MonotonicLag, l.LoginEnd, l.Residue, l.Breaks) } // The span before the kernel's clock splits at QEMU's exec, the host's bracket's middle, and at // the machine's running, the kernel's 0 less its sched offset; the three parts add up to it. before, qemu, guest := l.QEMUExec, l.Running-l.QEMUExec, l.KernelZero-l.Running - if !near(before, 18) || !near(l.QEMUExecError, 0.1) || !near(qemu, 52.0215) || !near(guest, 30) { + if !near(before, 18) || !near(l.QEMUExecError, 0.1) || !near(qemu, 32.0215) || !near(guest, 30) { t.Errorf("before QEMU %v ± %v, QEMU to the guest %v, the guest to the kernel's 0 %v", before, l.QEMUExecError, qemu, guest) } if sum := before + qemu + guest; math.Abs(sum-l.KernelZero) > 0.15 { @@ -210,15 +213,15 @@ func TestARealBootsLedgerAddsUp(t *testing.T) { for _, m := range l.Marks { marks[m.Name] = m.At } - if !near(marks["logind's session"], 299.931) || !near(marks["connection"], 264.765) || len(marks) != len(loginPhases) { + if !near(marks["logind's session"], 319.931) || !near(marks["connection"], 284.765) || len(marks) != len(loginPhases) { t.Errorf("marks: %+v", l.Marks) } text := l.Text("release, boot 1") for _, line := range []string{ - " 318.2 318.8 0.7 the login's command, to its exit\n", - "100.0 before the kernel's clock + 318.8 to the command's exit + 1.2 residue = 420.0, the first login the host measured", + " 338.2 338.8 0.7 the login's command, to its exit\n", + "80.0 before the kernel's clock + 338.8 to the command's exit + 1.2 residue = 420.0, the first login the host measured", "others under 0.5 ms each", - " 299.9 logind's session: systemd-logind[68]: New session '2'", + " 319.9 logind's session: systemd-logind[68]: New session '2'", } { if !strings.Contains(text, line) { t.Errorf("the ledger's text has no %q:\n%s", line, text) @@ -390,8 +393,8 @@ func TestSpinsHandoffHasAWindowOfItsOwn(t *testing.T) { if err != nil { t.Fatal(err) } - if len(l.Windows) != len(lane.Windows)+1 || l.Windows[1].Name != windowHandoff || !near(l.Windows[1].Start, 83.224) || - !near(l.Windows[2].Start, 83.972) || !near(l.Windows[1].End, 83.972) { + if len(l.Windows) != len(lane.Windows)+1 || l.Windows[1].Name != windowHandoff || !near(l.Windows[1].Start, 103.224) || + !near(l.Windows[2].Start, 103.972) || !near(l.Windows[1].End, 103.972) { t.Fatalf("windows: %+v", l.Windows[:3]) } if h := l.window(windowHandoff); !near(h.End-h.Start, 0.748) { @@ -409,7 +412,7 @@ func TestSpinsHandoffHasAWindowOfItsOwn(t *testing.T) { if h := other.window(windowHandoff); len(other.Windows) != len(lane.Windows) || h.End-h.Start != 0 { t.Errorf("another init read as the handoff: %+v", other.Windows[:2]) } - if !near(l.window(windowConnection).Start, 252.151) || !near(lane.window(windowConnection).Start, 252.151) { + if !near(l.window(windowConnection).Start, 272.151) || !near(lane.window(windowConnection).Start, 272.151) { t.Errorf("the connection: %v and %v", l.window(windowConnection), lane.window(windowConnection)) } } @@ -468,22 +471,31 @@ func TestPIDZeroIsTheKernelUntilTheFirstSwitch(t *testing.T) { } } -// A journal with no kvm-clock line has nothing to place the machine's running by, and an offset -// that puts it before QEMU's exec is an alignment that is wrong: both refuse the ledger. +// A journal with no kvm-clock line has nothing to place the machine's running by, one with no +// "Marking stable" line nothing to put the trace's clock on the kernel's by, and an offset that +// puts the running before QEMU's exec is an alignment that is wrong: each refuses the ledger. func TestTheSplitBeforeTheKernelsClockIsRefusedWhenItCannotHold(t *testing.T) { - in := ledgerFixture(t) - in.Journal = in.Journal[strings.Index(in.Journal, "\n")+1:] - if _, err := newLedger(in); err == nil || !strings.Contains(err.Error(), "sched offset") { - t.Errorf("no kvm-clock line: %v", err) + for _, line := range []string{"sched offset", "Marking stable"} { + in := ledgerFixture(t) + var kept []string + for l := range strings.Lines(in.Journal) { + if !strings.Contains(l, line) { + kept = append(kept, l) + } + } + in.Journal = strings.Join(kept, "") + if _, err := newLedger(in); err == nil || !strings.Contains(err.Error(), line) { + t.Errorf("no %q line: %v", line, err) + } } - // The machine ran at 70.0215 ± 0.0335: a bracket of QEMU's exec that starts inside that is + // The machine ran at 50.0215 ± 0.0335: a bracket of QEMU's exec that starts inside that is // taken, and one that starts after it is refused. - in = ledgerFixture(t) - in.QEMUExecLo, in.QEMUExecHi = 70.05, 70.2 + in := ledgerFixture(t) + in.QEMUExecLo, in.QEMUExecHi = 50.05, 50.2 if _, err := newLedger(in); err != nil { t.Errorf("QEMU exec'd within the kernel's 0's uncertainty of the machine's running: %v", err) } - in.QEMUExecLo = 70.06 + in.QEMUExecLo = 50.06 if _, err := newLedger(in); err == nil || !strings.Contains(err.Error(), "before QEMU's exec") { t.Errorf("QEMU exec'd after the machine ran: %v", err) } diff --git a/internal/lab/ledgerprobe.go b/internal/lab/ledgerprobe.go index 61fe6dcd..f9a85ffd 100644 --- a/internal/lab/ledgerprobe.go +++ b/internal/lab/ledgerprobe.go @@ -134,6 +134,7 @@ func (ledgerProbe) Metrics() []Metric { {"first_login", "ms", "the first login, /usr/bin/true, from the moment before QEMU is exec'd, with the trace running"}, {"kernel_zero", "ms", "where the kernel's clock read 0, from the same moment: QEMU, the firmware and the kernel's decompression"}, {"kernel_zero_error", "ms", "kernel_zero's uncertainty, half its narrowest bracket"}, + {"monotonic_lag", "ms", "CLOCK_MONOTONIC, the trace's and the journal's clock, behind the kernel's sched clock: what it lost on jiffies"}, {"before_qemu", "ms", "kernel_zero's first part: spin-machine, from the same moment to its exec of QEMU"}, {"qemu_start", "ms", "kernel_zero's second part: QEMU's start and the held start, from its exec to the guest's first instruction"}, {"guest_to_zero", "ms", "kernel_zero's third part: the firmware, the bzImage's decompression and the kernel's setup, to the kernel's clock"}, @@ -256,6 +257,7 @@ func (ledgerProbe) Measure(_ context.Context, m *Measurement) error { m.RecordMs("first_login", login) m.Record("kernel_zero", l.KernelZero) m.Record("kernel_zero_error", l.KernelZeroError) + m.Record("monotonic_lag", l.MonotonicLag) m.Record("before_qemu", l.QEMUExec) m.Record("qemu_start", l.Running-l.QEMUExec) m.Record("guest_to_zero", l.KernelZero-l.Running) From 9ce1e19ffd289551a3b161fc7f6c4f093987a862 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Mon, 23 Nov 2026 15:23:07 -0300 Subject: [PATCH 2/2] docs: the numbers the ledger's late kernel_zero gave, corrected (#644) measuring.md's split of lab 45110630795 recomputed with the lag, the ledger section says what the trace's clock is against the kernel's, the two cold-budget rows on clocks of their own note #665 and #666, and log.md has the entry. Co-Authored-By: Claude Opus 5.5 --- docs/boot-time.md | 12 +++++------ docs/image.md | 2 +- docs/log.md | 2 ++ docs/measuring.md | 48 ++++++++++++++++++++++++++++-------------- internal/lab/ledger.go | 7 +++--- 5 files changed, 45 insertions(+), 26 deletions(-) diff --git a/docs/boot-time.md b/docs/boot-time.md index 369c5f07..73646785 100644 --- a/docs/boot-time.md +++ b/docs/boot-time.md @@ -33,7 +33,7 @@ rule 3). **The restore is under 100 ms when QEMU is started ahead, and the cold boot is not close.** A cold boot cannot reach 100 ms by userspace work alone: QEMU, the firmware and the kernel take -~140 ms before PID 1 runs (budget below). Without systemd, sshd accepted at 189 ms in spin's shape +~140 ms before PID 1 runs (budget below), ~150 once two of its clocks are corrected (#665, #666). Without systemd, sshd accepted at 189 ms in spin's shape (lab 44750322384, 2026-11-20). Every phase before PID 1 has to shrink as well. ### What spin runs, and what the probes boot @@ -130,9 +130,9 @@ not a measurement: it says how far each phase has to move. |---|---|---|---|---| | QEMU's exec to a guest ready to run | ~28 | cold 456 less the boot into a QEMU started ahead, 428 (report 44811347183) | by difference, one run | 0, started ahead | | … of it, QMP: QEMU's main loop free to `cont` answered, 14 commands | 6.2 | `transport` `cold_qmp`, lab 44912471522 (v20261121.01); 4.5 of it QEMU waiting on spin-machine's next command | measured | | -| qboot and the bzImage's decompression, to the kernel's clock | 33.6 | `boot:firmware-stages`, lab 44787491631 (v20261120.02's kernel); ~21 of it is the decompression KASLR needs | measured, another run | 5 | -| The kernel's clock to "Freeing unused kernel image" | 79.9 | report 44811347183 | measured | 25 | -| PID 1 to sshd accepting | ~255 | sshd accepts 396 (lab 44841266997) less the three rows above | by difference, across runs | 35 | +| qboot and the bzImage's decompression, to the kernel's clock | 33.6 | `boot:firmware-stages`, lab 44787491631 (v20261120.02's kernel); ~21 of it is the decompression KASLR needs. Its end, KVM_SET_CLOCK plus the sched offset, is 2.8 ms after the kernel's 0 on bench, so ~31 (#665) | measured, another run; its anchor late | 5 | +| The kernel's clock to "Freeing unused kernel image" | 79.9 | report 44811347183, on dmesg's clock, which from late_initcall on is 13-15 ms behind the kernel's on bench, so ~93 (#666) | measured on a clock that reads short | 25 | +| PID 1 to sshd accepting | ~255 | sshd accepts 396 (lab 44841266997) less the three rows above; ~244 with the two corrections above | by difference, across runs | 35 | | sshd's accept to the first login | 68.4 | `ssh-first` `accept_to_login`, lab 44841266997 | measured | 35 | | … of it, what any login costs (a second login) | 35.9 | `ssh-first` `second_login`, the same | measured | | | … of a login, vsock: 10 round trips of 57.5 µs through the forwarder | 0.6 | `transport` `login_turns`, `forward_rtt`, lab 44912471522 | measured | | @@ -141,7 +141,7 @@ not a measurement: it says how far each phase has to move. **PID 1 to sshd is more than half the cold boot.** On one vCPU, everything systemd starts before sshd accepts is on the login's path. The groups in "What the machine carries" show how much masks, generators and the coldplug filter took off it. The no-systemd floor accepted at 189 ms in -spin's shape. Before PID 1, ~140 ms of QEMU, firmware and kernel remain, ~113 of them with QEMU +spin's shape. Before PID 1, ~140 ms of QEMU, firmware and kernel remain (~150 corrected, #665, #666), ~113 of them with QEMU started ahead. Each phase from the first row to the fourth has to shrink to reach 100 ms. ### Restore, QEMU started ahead @@ -485,7 +485,7 @@ The rows are ranked by ceiling. A row stays here until it is decided, and then m | A workspace's cgroup at a higher `cpu.weight` while it boots or restores, on a busy host (spin's runner owns the cgroup) | restore, as a busy host sees it | with 16 workspaces keeping the 16 CPUs busy, the restored first login is 306 ms against 115 idle, and QEMU's threads wait 282 ms for a CPU (lab 44925573288). The same weight ratio as QEMU at nice −10, set as the crowd at nice 10: restored −79.3 [−93.5, −71.0], cold −104.7 [−258.3, +150.9], within noise (lab 44927312303) | spin's `restore-together` or a crowd on its runner, with the weight raised through the workspace's cgroup and set back after the login, against without it | a proposal for spin. Measured in one cgroup, where each thread competes alone. In spin each workspace is a cgroup, and the weight is shared by its threads. The idle host has nothing to win (Measured and rejected, "Memory and the host") | | journald's, logind's and `user@`'s seccomp and sandbox settings emptied: `SystemCallFilter=`, `Restrict*=`, `Protect*=`, `MemoryDenyWriteExecute=`, `LockPersonality=` (#574, experiment 4, a bound) | cold | the executors' CPU before the login: journald 6.0, logind 10.3, `user@0` 2.8 ms, p50 of 5 ledgers (lab 45120692382) | the bound read first login −14.1 [−18.5, −11.5], sshd accepting −13.2 [−16.0, −10.9] at 60 a side (lab 45121038332). Next: split it into its seccomp and namespace halves, then one seccomp filter per unit in systemd, which keeps the function (#637) | open, #637. A bound and never a candidate: the settings are function | | The restore with more than 2 GiB of RAM | restore | unmeasured (#242's checklist) | `restore-first` with `plugged` above 2048 | open | -| A workspace's 2048 MiB at boot (`memory=2048 plugged=0`) instead of 128 plugged to 2048 through virtio-mem during the boot (#561) | cold | the plug and the onlining of 2048 MiB on the one vCPU while the boot runs; separate runs read −15 nested and −8 metal (v20261122.06, labs 45074465204, 45074579100, 45074680619, 45078339515), so the ceiling is ~15 ms. Prior art: the kernel onlines hotplugged memory strictly in sequence, one memory block after another, and deferred struct page init, which spreads the boot's own memory over threads, does not apply to it (David Hildenbrand on linux-mm, [lore](https://lore.kernel.org/linux-mm/87v9disj2s.fsf@oracle.com/T/)). Squeezy (arXiv 2411.12893, 2024) measured virtio-mem's operations in seconds at GiB sizes and found init_on_free slows a plug. Neither measured a boot. The kernel has init_on_alloc and init_on_free off | `ssh-first`, the two shapes as two trees of one run (`--opt` on a tree), 40 a side on bench and on bench-metal, `restore-first` beside them; 3 ledgers of each shape for the onlining's CPU | a proposal for spin, spin-stack/spin#1660. Measured as two trees of one run (v20261123.04, spin's login): cold first login −5.5 [−10.9, −0.7] nested at 80 a side (lab 45111507862; −2.5 [−7.3, +2.0] at 40, lab 45110554589), −7.0 [−11.4, −3.4] on metal at 40 (lab 45110570912); restored login −2.5 [−3.7, −1.0], the state −17.6 MiB, QEMU's RSS −26 MiB (labs 45110562994, 45111507862). The ledger (lab 45110580480, 3 boots each) shows `kworker/0:1` on the vCPU ~8 ms before PID 1 when plugged and not at all when the memory is at boot, which costs the kernel's own setup ~4.5 ms more: PID 1 −3.4 ms. The probes keep spin's shape until spin changes it | +| A workspace's 2048 MiB at boot (`memory=2048 plugged=0`) instead of 128 plugged to 2048 through virtio-mem during the boot (#561) | cold | the plug and the onlining of 2048 MiB on the one vCPU while the boot runs; separate runs read −15 nested and −8 metal (v20261122.06, labs 45074465204, 45074579100, 45074680619, 45078339515), so the ceiling is ~15 ms. Prior art: the kernel onlines hotplugged memory strictly in sequence, one memory block after another, and deferred struct page init, which spreads the boot's own memory over threads, does not apply to it (David Hildenbrand on linux-mm, [lore](https://lore.kernel.org/linux-mm/87v9disj2s.fsf@oracle.com/T/)). Squeezy (arXiv 2411.12893, 2024) measured virtio-mem's operations in seconds at GiB sizes and found init_on_free slows a plug. Neither measured a boot. The kernel has init_on_alloc and init_on_free off | `ssh-first`, the two shapes as two trees of one run (`--opt` on a tree), 40 a side on bench and on bench-metal, `restore-first` beside them; 3 ledgers of each shape for the onlining's CPU | a proposal for spin, spin-stack/spin#1660. Measured as two trees of one run (v20261123.04, spin's login): cold first login −5.5 [−10.9, −0.7] nested at 80 a side (lab 45111507862; −2.5 [−7.3, +2.0] at 40, lab 45110554589), −7.0 [−11.4, −3.4] on metal at 40 (lab 45110570912); restored login −2.5 [−3.7, −1.0], the state −17.6 MiB, QEMU's RSS −26 MiB (labs 45110562994, 45111507862). The ledger (lab 45110580480, 3 boots each) shows `kworker/0:1` on the vCPU ~8 ms before PID 1 when plugged and not at all when the memory is at boot, which costs the kernel's own setup ~4.5 ms more: PID 1 −4.0 ms on the kernel's clock (−3.4 on CLOCK_MONOTONIC, before #644). The probes keep spin's shape until spin changes it | The floor is a bound and never a candidate: systemd stays (AGENTS.md, "What must not break"). diff --git a/docs/image.md b/docs/image.md index 6b5e85b9..53b6a724 100644 --- a/docs/image.md +++ b/docs/image.md @@ -878,7 +878,7 @@ idle CPU and IO classes), since it reports on a guest whose CPU may be what is s because a trigger with a window under 2 s is root's alone. Out of the OOM killer's way (`OOMScoreAdjust=-900`), which otherwise took it in the OOM it was reporting (`task boot:pressure`, 2026-11-21); it holds a few MiB. Started with `multi-user.target`, which `spin-machine-boot-rest.service` starts -once the first login's units are up (#581): in a ledger of spin's shape it started at 0.37-0.38 s +once the first login's units are up (#581): in a ledger of spin's shape it started at 0.39-0.40 s on the kernel's clock, after the login (lab 45120692382, 5 boots). Moving it there from a timer 10 s after the boot moved neither number: bench, spin's shape and login, 20 a side against v20261123.04, first login −0.8 [−7.8, +4.8] (lab 45120950183), restored −0.8 [−2.9, +2.1] evicted and −0.4 diff --git a/docs/log.md b/docs/log.md index c0b97495..414df67d 100644 --- a/docs/log.md +++ b/docs/log.md @@ -665,6 +665,8 @@ Checked against the probe it replaced on the bench fleet, `lab dispatch ssh-firs **11-23 · image · the dynamic linker's share of PID 1, journald, logind and `user@0` is ~1 ms (labs 45180400607, 45180856158, #638, this change).** #574's runner-up: the four map and relocate `libsystemd-shared` (PID 1 and `user@0` also `libsystemd-core`), and nobody had measured ld.so's share before porting to v262's multicall build (#42304) or a static one (#42820). *Instrument* (branch `exp-ldso`, tagged `archive/exp-ldso`, its `ldso` edit): `LD_DEBUG=statistics` for PID 1 from spin's handoff, which execs it (`systemd.setenv=` does not reach PID 1), and for journald, logind and `user@0` from a drop-in each. PID 1 and journald report on `/dev/kmsg` with `printk.devkmsg=on`, logind and `user@0` on their stderr, the journal: the first run had logind's on `/dev/kmsg` too, its `DevicePolicy=` refused the executor the open, and logind failed at STDERR (lab 45180400607, discarded). glibc 2.43 counts in TSC cycles, 2700 MHz in every boot. *Measured* (bench, nested, spin's shape and login, v20261123.05 on its traceable kernel, the ledger with and without the edit, 8 a side, lab 45180856158), ld.so's total start-up, p50 [range]: PID 1 0.48 [0.46, 0.56] ms, of it loading objects 0.32 and relocation 0.08; journald 0.20 [0.14, 0.31]; logind 0.20 [0.11, 0.31]; `user@0` 0.21 [0.15, 0.36]. Relocations: PID 1 and `user@0` 2,522 symbol (911 from cache) and 16,589 relative; journald 1,157 and 10,518; logind 1,238 and 11,297. Objects at start, from the release's image (`ldd`): 7 for PID 1 and `user@0` (the binary, libsystemd-core, libsystemd-shared, libc, libm, libcrypt, ld.so), 6 for journald and logind, all `BIND_NOW`. The four come to ~1.1 ms, under #638's ~5 ms, so no build was made. *The instrument:* against the ledger alone in the same run, first login +3.4 [−23.0, +11.9], PID 1's CPU −1.1 [−5.1, +0.6], unattributed +0.3 [−0.1, +1.1]; each ld.so total is well inside the trace's wall time from the process's exec to its first sleep. It does not see the kernel's execve before ld.so runs, nor the libraries' pages faulted in later by `main`, which a static build would partly pay too (not measured). `user@0`'s environment generator inherits the variable and reports 0.13 ms more. *Inferred:* the multicall build would not reach even that: it keeps libsystemd-core and libsystemd-shared dynamic, leaves journald and logind alone and makes the executor, static here, dynamic. *Status:* measured and rejected; #638 closed. **11-23 · qemu · a bzImage mapped, not read into QEMU's heap (#646, labs 45182382388, 45182382864, 45183618987, this change).** `x86_load_linux` read the whole 16.7 MB bzImage into a buffer that only fw_cfg reads, 6.2-6.9 ms of QEMU's init traced (labs 45177818419, 45177817516, #611), and qboot copies the same bytes again by fw_cfg DMA. `qemu/patches/0007` maps the file read-only (`g_mapped_file_new_from_fd`), as upstream has mapped the initrd since 4.2; a kernel with a dtb appended keeps its buffer. The setup header QEMU patches is already a copy of its own, so nothing writes to the mapping. The QEMU build asserts that a held TCG machine's maps name a stub bzImage given to it; the published QEMU fails that check. *Prior art* is in docs/boot-time.md's row: Garzarella's 2019 series mapped the ELF kernel and the initrd but not the bzImage. *Measured* (bench, nested, spin's shape and login, v20261123.05 against the same release with the patched QEMU, parts run 45180746171, 40 a side, interleaved): first login 380 → 367, −13.4 [−16.9, −7.3], sshd accepting −13.3 [−18.7, −7.5], the console prompt −10.6 [−14.2, −6.3]; QEMU's anonymous RSS −15.9 MiB and its file RSS +16.1, total unmoved (lab 45182382388). Restored, 40 a side: login −9.3 [−11.2, −6.1] evicted and −7.7 [−8.9, −5.1] cached, `running` −8.8 and −7.9, the state unmoved (lab 45182382864): a restore starts QEMU, which loads the kernel into fw_cfg there too. The gain is twice the traced read; what else the anonymous buffer cost nested (its page faults, presumably) was not measured. *A lead, not a decision:* an uncompressed payload (#326's kernel patch, renumbered, branch `exp/646-uncompressed`, parts run 45180892535) against LZ4, both on the patched QEMU: first login −4.0 [−7.9, +0.3], within noise at 40, QEMU's RSS +32 MiB (lab 45183618987). The mapping removes the "+6-7 in QEMU's start" half of #326's rejection; whether the rest is a gain needs more boots, which is #645's. *Status:* in place; the record does not move, as the kernel reaches the guest through fw_cfg. +**11-23 · lab · the ledger's kernel_zero on the kernel's sched clock (#644, labs 45229897350, 45230233764, this change).** The ledger's `kernel_zero` landed 19.5 ms (bench) and 12.6 ms (metal) after a port write at the sched clock's 0 (#611). *Found:* the ledger took CLOCK_MONOTONIC's 0, the trace's clock, for the kernel's. CLOCK_MONOTONIC runs on jiffies from timekeeping_init until the switch to kvm-clock and loses the ticks it misses. The kernel prints both clocks at one tick at late_initcall ("sched_clock: Marking stable"), and their difference was the whole error in all 24 boots of labs 45177818419 and 45177817516, to within 0.15 ms. *Changed:* the ledger moves the trace and the journal forward by that lag (`monotonic_lag`, 18-25 ms nested, 11-14 metal) and refuses a journal without the line. *Checked:* with the marker kernel, `kernel_zero` lands 0.03 to 0.14 ms before QEMU's trace stamps the marker, 10 boots on bench and 10 on metal (spin's shape, v20261123.04). *What moved*, recomputed from the runs' kept journals: docs/measuring.md's split of lab 45110630795, `kernel_zero` 97-114 → 77-95 and `qemu_start` 49.4 → 29.3 (`before_qemu` and `guest_to_zero` do not move); QEMU's exec to the kernel's clock untraced on the workspace's machine is 73.4 ms on bench and 68.7 on metal (labs 45177818419, 45177817516), against firmware-stages' 73.7; PID 1 in #561's ledgers −3.4 → −4.0 ms; the pressure sender's start 0.37-0.38 → 0.39-0.40 s (docs/image.md). #611's comment is corrected. No cold-budget row used the ledger's anchor. Two of its rows use clocks with errors of their own, now noted beside them: firmware-stages' anchor is ~2.8 ms late on bench (#665), and dmesg's clock reads the kernel 13-15 ms short from late_initcall on (#666). *Status:* in place. + ## 2. Rework cycles Each cycle: the sequence, what each step measured, and the lesson. diff --git a/docs/measuring.md b/docs/measuring.md index 8bd018f5..d6fd888f 100644 --- a/docs/measuring.md +++ b/docs/measuring.md @@ -265,16 +265,32 @@ trace lost events. A switch away from a task the CPU was not running counts as a - *The kernel's 0 on the host's clock.* The host asks the guest for 20 markers in the trace, 50 ms apart. Each marker was written after its request left and before its answer arrived, so each puts the kernel's 0 in a bracket. The brackets agree only if the two clocks run at one rate. - Spread over a second they met within ±0.15 ms (lab 45062836688). `kernel_zero` is that 0. + Spread over a second they met within ±0.15 ms (lab 45062836688). +- *The trace's clock against the kernel's.* The trace and the journal are on CLOCK_MONOTONIC, + and the kernel's 0 is its sched clock's, read from kvm-clock in `kvm_sched_clock_init`. + CLOCK_MONOTONIC starts level with the sched clock, then runs on jiffies until the switch to + kvm-clock at fs_initcall, and every tick it misses is lost for good. At late_initcall the + kernel prints both clocks as one tick read them ("sched_clock: Marking stable (MONO, + …)->(SCHED, …)", in ns). Their difference is `monotonic_lag`, 18-25 ms nested and 11-14 on + metal. The ledger moves the trace and the journal forward by it, and refuses a journal without + the line. `kernel_zero` is the markers' 0 less the lag. A kernel that writes a port at the + sched clock's 0 checked it: `kernel_zero` lands 0.03 to 0.14 ms before QEMU's trace stamps that + write, in 10 boots on bench and 10 on metal (labs 45229897350 and 45230233764), and 11.6 to + 20.9 ms after it without the lag (labs 45177818419 and 45177817516; all v20261123.04 with the + marker kernel, spin's shape, #644). The first window, the kernel to PID 1's exec, is the one the lag lands + in, and the ledger gives it to the kernel. dmesg is on neither clock: from that line on, + printk's clock is the sched clock less 11-15 ms (#666). - *QEMU's exec on the host's clock.* No clock in the guest sees it, and /proc stamps a process's start in 10 ms ticks, so the host watches spin-machine's children from its own exec until one is QEMU. The exec is between the last look that did not see it and the first that did: `qemu_exec_error` is half that bracket, 0.11 to 0.14 ms in six boots. - *The guest's first instruction.* QEMU zeroes kvm-clock as the machine goes to running, and the kernel prints the kvm-clock it read as it made it the scheduler's clock ("kvm-clock: using - sched offset of N cycles", in ns). The kernel's clock, CLOCK_MONOTONIC's 0 included, starts from - that reading, so the machine ran at `kernel_zero` less N. `boot:firmware-stages` places the - kernel's clock on QEMU's trace by the same line. + sched offset of N cycles", in ns). The kernel's sched clock starts from that reading, so + kvm-clock read 0 at `kernel_zero` less N. That 0 lies 2.1-3.8 ms (bench) and 4.4-5.0 ms (metal) + before QEMU's KVM_SET_CLOCK, because KVM bases it on its master clock's last update. So + `qemu_start` reads that much short and `guest_to_zero` as much long (#665). `boot:firmware-stages` + places the kernel's clock on QEMU's trace at KVM_SET_CLOCK plus N, which is late by the same. - *The residue.* That is `first_login` less `kernel_zero` and the command's exit on the kernel's clock: sshd's answer crossing vsock and the client reading it. It read 0.4 to 1.2 ms in six boots. A residue that is negative or large says the alignment is wrong. @@ -284,21 +300,21 @@ construction: `before_qemu`, spin-machine to its exec of QEMU; `qemu_start`, QEM held start's monitor to the guest's first instruction; and `guest_to_zero`, the firmware, the bzImage's decompression and the kernel's setup until its clock runs. A sched offset that puts the machine's running before QEMU's exec refuses the ledger, as a journal without the line does. -`kernel_zero` read 97 to 114 ms in six boots, the first the longest (lab 45110630795, bench, -spin's shape, v20261123.04, 2026-11-23): +`kernel_zero` read 77 to 95 ms in six boots, the first the longest (lab 45110630795, bench, +spin's shape, v20261123.04, 2026-11-23, recomputed from the run's journals with the lag): | part | p50 | range | |---|---|---| -| `before_qemu`, spin-machine to QEMU's exec | 2.1 | 1.9 to 2.5 | -| `qemu_start`, QEMU's exec to the guest's first instruction | 49.4 | 48.3 to 50.8 | -| `guest_to_zero`, the guest's first instruction to the kernel's clock | 47.4 | 46.4 to 63.2 | - -The first boot's extra ~15 ms is all in `guest_to_zero`. `boot:firmware-stages` read 73.7 ms from -QEMU's exec to the kernel's clock (lab 45062836494), ~23 less than the ledger's ~97. The ~20 ms -the ledger had over it were read as spin-machine's start and the held start before QEMU. Measured, -spin-machine is 2 ms of them, and the rest is after QEMU's exec. firmware-stages boots a machine -of its own, without the disks, the vsock and the hotplug ports a workspace's machine carries, -and with no held start (#611). +| `before_qemu`, spin-machine to QEMU's exec | 2.1 | 1.9 to 2.4 | +| `qemu_start`, QEMU's exec to kvm-clock's 0 | 29.3 | 28.2 to 31.1 | +| `guest_to_zero`, kvm-clock's 0 to the kernel's clock | 47.4 | 46.4 to 63.2 | + +The first boot's extra ~15 ms is all in `guest_to_zero`. Without the lag the run read +`kernel_zero` 97 to 114 and `qemu_start` 49.4. QEMU's exec to the kernel's clock is 78.4 here, and +73.4 [72.2, 81.1] in 12 untraced boots of lab 45177818419 (68.7 on metal, lab 45177817516). +`boot:firmware-stages` read 73.7 (lab 45062836494) on a machine of its own, without the disks, +the vsock and the hotplug ports a workspace's machine carries, and with no held start. Its anchor +is ~2.8 ms late on bench (#665), so its own number is ~71. **What it costs.** The trace and sshd's DEBUG1 run on the guest's vCPU beside the boot they record. In spin's shape, 20 a side, interleaved (lab 45063070048, bench, v20261122.05): diff --git a/internal/lab/ledger.go b/internal/lab/ledger.go index f51b76ca..bb730f75 100644 --- a/internal/lab/ledger.go +++ b/internal/lab/ledger.go @@ -38,7 +38,7 @@ type Ledger struct { KernelZeroError float64 `json:"kernel_zero_error"` // MonotonicLag is how far CLOCK_MONOTONIC runs behind the kernel's clock once both run on // kvm-clock: what it did not count while it ran on jiffies, from timekeeping_init until the - // switch to kvm-clock at fs_initcall. It is 18-21 ms nested and 11-14 on metal, and without it + // switch to kvm-clock at fs_initcall. It is 18-25 ms nested and 11-14 on metal, and without it // the kernel's 0 read that much late (#644). MonotonicLag float64 `json:"monotonic_lag"` // QEMUExec is where spin-machine exec'd QEMU, and QEMUExecError half the bracket the host's @@ -428,8 +428,9 @@ var reSchedOffset = regexp.MustCompile(`kvm-clock: using sched offset of (\d+) c // jiffies until the switch to kvm-clock at fs_initcall, and the ticks it misses are lost for good. // At late_initcall the kernel prints both clocks as one tick read them (kernel/sched/clock.c, // __set_sched_clock_stable: "Marking stable (ktime_get_ns, __gtod_offset)->(sched_clock, -// __sched_clock_offset)"). With it, the ledger's kernel_zero lands 0.02-0.15 ms after a port -// write at the sched clock's 0, against 11.6-20.9 ms without (labs 45177818419, 45177817516, #644). +// __sched_clock_offset)"). With it, the ledger's kernel_zero lands 0.03-0.14 ms before QEMU's +// trace stamps a port write at the sched clock's 0, against 11.6-20.9 ms after it without (labs +// 45229897350 and 45230233764 against 45177818419 and 45177817516, #644). // dmesg's own clock is neither: from that line on it is the sched clock plus // __sched_clock_offset. func monotonicLag(journal string) (float64, error) {