time: read the clock from the TSC, not from counting interrupts
A timer interrupt that arrives while interrupts are disabled is not delayed,
it is lost -- the LAPIC in periodic mode holds one pending interrupt and drops
the rest. So anything the kernel does with interrupts off for longer than
10 ms makes `ticks` run slow, and it never catches up.
That has now presented twice as "uptime is wrong": once as an interrupt storm
taking 83% of the CPU, once as heavy console output on a display that is
expensive to draw to. Both times the tick was the messenger, and both times it
looked like a timekeeping bug.
monotonic() reads the TSC instead. It is a counter in the silicon that
advances whether or not this kernel is paying attention, it is already
measured against the PIT at boot, and reading it is one instruction and no
lock. wallclock(), /proc/uptime, sysinfo, getrusage and times() all go through
it now.
`ticks` keeps the job it is good at -- the scheduler preempts on it, sleep()
counts it -- where losing one means a slightly longer sleep rather than a
wrong answer about what time it is.
Lost ticks are no longer harmful, which makes them invisible, which is worse.
So /proc/interrupts now says
timer: 3383 ticks taken, 3387 expected
and names the gap when it grows, because a machine dropping timer interrupts
is spending too long with interrupts disabled, and that is worth knowing
before it turns into a clock that lies.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VQ7Qx8E1q1M1bbCq8QLHS2
This commit is contained in:
parent
65906639da
commit
bbc512a51c
7 changed files with 192 additions and 37 deletions
|
|
@ -78,6 +78,7 @@ lapicw(int index, int value)
|
|||
|
||||
uint lapic_timer_hz; // measured LAPIC timer counts per second
|
||||
uint64 tsc_hz; // measured TSC cycles per second
|
||||
uint64 boot_tsc; // the TSC when calibration finished
|
||||
|
||||
static void
|
||||
calibrate_timers(void)
|
||||
|
|
@ -116,6 +117,11 @@ calibrate_timers(void)
|
|||
lapic_timer_hz = (uint)(((uint64)(lap0 - lap1) * 1000000) / us);
|
||||
tsc_hz = ((tsc1 - tsc0) * 1000000) / us;
|
||||
|
||||
// Where the clock starts. Everything the system reports as elapsed time is
|
||||
// measured from here, against the TSC, rather than by counting timer
|
||||
// interrupts -- see kernel/core/time.c.
|
||||
boot_tsc = tsc1;
|
||||
|
||||
// If the measurement came back implausible -- no LAPIC, a hypervisor that
|
||||
// stops the counter, a PIT that never raises its output -- fall back to the
|
||||
// old assumption rather than dividing by zero and taking the machine down.
|
||||
|
|
|
|||
Loading…
Reference in a new issue