SchOS/kernel/core/time.c
Nexoniarz 9d4cdb44fc kernel: the clock ran 7x slow because the GPU never acknowledged its interrupt
fastfetch reported 3 seconds of uptime after 15 real ones, `time` claimed
3.12s for a 20-second command, and ping's one-second interval was closer to
six. One cause, not three: `ticks` was advancing at ~14.5 Hz instead of 100.

It was not the timer. virtio-gpu-pci shares IRQ 11 with the e1000 and
registered no interrupt handler at all. PCI INTx is level-triggered, so the
device held the line asserted, the kernel signalled EOI, and it fired again
immediately -- 72,000 interrupts a second, 83% of CPU0, starving the tick.
The e1000's handler read ICR as zero half a million times, correctly
answering "not mine", which is what made it look like a network-free problem.

Reading virtio's ISR byte clears it and drops the line. That is the fix.

irq_dispatch now measures each line's rate against the TSC -- not ticks,
which is the first casualty of a storm -- and names the attached handlers
once above 20000/s. It reproduces the original fault as a single line.

Found along the way, and fixed because they were real:

  - lapicinit loaded TICR with xv6's uncalibrated 10000000, whose own comment
    admitted it was never measured. calibrate_timers() now measures the LAPIC
    and the TSC against the 8254 PIT. (It came back at 999.9 MHz, so this was
    not the bug -- but the next machine is not obliged to be 1 GHz.)
  - microdelay() was an empty function body. Every microdelay(1000) in the
    xHCI reset path and the USB hub power-on sequence returned instantly.
  - HZ is a constant in param.h now, not the literal 100 written out at a
    dozen ticks-to-seconds conversions. USER_HZ is separate and deliberately
    does not follow it: musl answers sysconf(_SC_CLK_TCK) with 100 always, so
    times() and /proc/stat scale at the syscall boundary the way Linux does.
  - TIOCGWINSZ answered a hardcoded 24x80. gfx_cols()/gfx_rows() have known
    the real geometry all along; at 1024x768 the console is 128x48, so every
    program that lays out a screen was formatting for the wrong one.
  - TCFLSH fell through to the catch-all `return 0`, claiming to discard
    input without discarding any.

uptime now advances 5.01 seconds per 5 real seconds. schfs-check passes.

Full investigation, including the two wrong hypotheses and the measurement
flaw that protected them, in docs/history/kernel.md section 13.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VQ7Qx8E1q1M1bbCq8QLHS2
2026-09-12 21:34:36 +02:00

116 lines
4.7 KiB
C

// Wall-clock time.
//
// The kernel has always known how long it had been running -- `ticks`, bumped
// 100 times a second by the timer interrupt -- and has never known what time it
// was. sys_gettimeofday() returned `ticks / 100` as though it were seconds
// since the epoch, so every SchOS machine believed it was the 1st of January
// 1970 and that the date advanced at the rate of its own uptime. `date` printed
// a number that barely moved, which is what it looks like when a clock is
// counting from the wrong place rather than not counting at all.
//
// cmostime() in kernel/arch/x86_64/lapic.c has been able to read the hardware
// clock the whole time. Nothing called it.
//
// The arrangement here is the usual one: read the RTC once at boot, convert it
// to a Unix timestamp, and add uptime to it thereafter. The RTC is slow to read
// (it is polled over two I/O ports and has to be sampled twice to catch it
// mid-update) so reading it on every gettimeofday would be absurd; and `ticks`
// is a perfectly good interval clock once it has something to count from.
#include "types.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "spinlock.h"
extern uint ticks;
// Seconds between the Unix epoch and the moment this machine booted. Zero until
// time_init() runs, which makes the behaviour before that point exactly what it
// used to be -- uptime presented as absolute time -- rather than something new
// and differently wrong.
uint64 boot_epoch;
// Days from 1970-01-01 to the given civil date, proleptic Gregorian.
//
// Howard Hinnant's days_from_civil. It is worth using rather than a loop over
// years because it is branchless, exact for any year, and has no table to get
// wrong; the alternative -- accumulating 365 or 366 days per year since 1970 --
// gets leap centuries wrong unless you remember that 1900 was not a leap year
// and 2000 was, which is precisely the sort of thing that is discovered on a
// February morning years later.
//
// The trick is shifting the year so that March is month 1, which puts the leap
// day at the *end* of the year and makes the leap rule depend only on the year
// number rather than on where in the year you are.
static int64
days_from_civil(int64 y, unsigned m, unsigned d)
{
y -= m <= 2;
const int64 era = (y >= 0 ? y : y - 399) / 400;
const unsigned yoe = (unsigned)(y - era * 400); // [0, 399]
const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
return era * 146097 + (int64)doe - 719468;
}
// Read the hardware clock and work out when we booted.
//
// The RTC is read in UTC. That is not universally true on a PC -- a machine
// that has had Windows installed on it usually keeps the RTC in local time --
// but there is nowhere to store a timezone yet and no way to ask, and UTC is
// the honest default for a system with no configuration. When there is a
// settings store, this is where the offset goes.
void
time_init(void)
{
struct rtcdate r;
cmostime(&r);
// cmostime() returns a two-digit year on hardware that only stores one.
// 2000-2099 is the right guess now and stays right for a lifetime; a machine
// reporting 70 means the battery is flat, and the epoch is as good an answer
// as any for that.
int64 year = r.year;
if (year < 100)
year += 2000;
// A wildly implausible reading means the CMOS is not telling us anything.
// Leaving boot_epoch at zero keeps the old behaviour, which is wrong but
// predictable, rather than putting the machine somewhere in the Bronze Age.
if (r.month < 1 || r.month > 12 || r.day < 1 || r.day > 31 ||
r.hour > 23 || r.minute > 59 || r.second > 60 || year < 1970) {
cprintf("time: CMOS clock is not plausible, staying at the epoch\n");
return;
}
int64 days = days_from_civil(year, r.month, r.day);
uint64 now = (uint64)(days * 86400) + r.hour * 3600 + r.minute * 60 + r.second;
// Subtract the uptime so far, so boot_epoch is the moment of boot rather than
// the moment this function ran. It is only a fraction of a second, but it
// keeps boot_epoch meaning exactly what its name says.
uint64 up = ticks / HZ;
boot_epoch = now > up ? now - up : now;
cprintf("time: %d-%d-%d %d:%d:%d UTC from the hardware clock\n",
(int)year, r.month, r.day, r.hour, r.minute, r.second);
}
// Seconds and microseconds since the epoch. One place, so gettimeofday,
// clock_gettime and anything added later cannot disagree about what time it is.
void
wallclock(uint64 *sec, uint64 *usec)
{
uint xticks;
acquire(&tickslock);
xticks = ticks;
release(&tickslock);
if (sec)
*sec = boot_epoch + xticks / HZ;
if (usec)
*usec = (uint64)(xticks % HZ) * (1000000 / HZ);
}