Kernel Time Overview
====================

This document gives a short overview about the code that handles time
in the Linux kernel in order to make it understandable what all the
NTP stuff is about. The description concentrates on the user's view of
kernel time.

1. Hardware
===========

The kernel uses the timer (programmable periodic interrupt at rate
``HZ'') to increment the kernel clock. The kernel clock consists of
two counters.  The first one (``tv_sec'') counts the seconds since
1970-01-01, while the second one (``tv_nsec'') manages the fraction of
the current second in nanoseconds.  During boot the first value is
derived from the time found in the CMOS clock (also known as ``real
time clock'') which only has a resolution of one second.

During each interrupt a specific amount (the "time_tick",
1000000000/HZ) of nanoseconds is added to the fractional second.  If
a second overflow occurs, it is handled accordingly.  Normally the new
kernel time is not written back to the CMOS clock, but it can be done.

If an application program asks for the current time, it is possible to
get an estimate of the elapsed time since the last timer interrupt, by
extrapolating the time.  This is what  ``do_nanotime()'' is for.

On the Intel 386 architecture the registers in the timer chip can be
read to get a resolution of less than a microsecond.

On a Pentium the CPU's cycle counter can be used to estimate the time
since the last timer interrupt by scaling the cycles elapsed during
two successive timer interrupts. The resolution for fast CPUs is
significantly higher than for the timer's counter register (close to
or even below one microsecond).  Furthermore it can be read much
faster than the hardware registers of the timer chip.  Unfortunately
modern motherboards may vary the CPU frequency to avoid overheating
the processor or to save power (APM features).

Other architectures have similar fast timing facilities, more or less
reliable.

These are the components that determine the "resolution" of the kernel
clock.  Also the "stability" (reliability or predictability) and
precision (the error accumulated during reading the time) is
determined by the hardware.

2. Software
===========

While the hardware is responsible for the resolution and precision of
the clock, the software is responsible for calibrating the clock and
programming the hardware. Linux uses an extended algorithm to manage
system time.  That algorithm is basically the NTP kernel clock model
described in RFC 1589, RFC 1305 and related papers.  The current
implementation is referred to as ``nanokernel'', because it keeps time
in nanoseconds.

As most clocks are not very precise or stable, it is necessary to
correct the kernel clock from time to time. Traditionally it is
possible to overwrite the current kernel counters to make the time
"step" (stime, settimeofday, clock_settime). Also it's possible to
initiate a more gradual change in time by specifying the amount of
time that is to be changed. This is called "slewing" the clock
(adjtime).

When slewing the clock, the value of "time_tick" is modified by a
small amount, called "tickadj" (50000/HZ, s per interrupt). That
way the clock seems to be running faster or slower for some time
(until the desired correction has been applied), and then continues to
run at nominal speed. Obviously "tickadj" does not only affect the
speed in which an adjustment is made, but also the resolution of the
adjustment.  Usually there is no adjustment below "tickadj". One
reason against using the smallest possible value for tickadj is that
the correction must be more than the clock's intrinsic error (Besides
that fact that a correction can take very long). Otherwise you'll
never be able to keep up with the error.

2.1 NTP extensions
==================

Independent on which of the above two methods is used, the process has
to be repeated again and again to keep the deviation of the software
clock within a small interval. When you know the percentage of your
clock error (e.g. 15 seconds to fast within 24 hours), you can also
pass a correction value to the kernel, asking for automatic
correction of the frequency error.

Such a correction value can be expressed in PPM (parts per million,
0.0001%) of the clock's "frequency". Additionally the enhanced clock
model can be told to learn from periodic adjustments to the time
offset, such that the virtual frequency of the kernel clock is
modified (you can't tune the hardware).  Alternatively the frequency
can be set directly. As these corrections are limited by ``tickadj''
(max <= HZ*tickadj), it's sometimes necessary to change the value of
``time_tick'' (if you want to keep tickadj small).

Unfortunately specifying the frequency alone is not sufficient to make
a stable clock, because the frequency varies over time. These
variations in frequency are usually influenced by the environmental
temperature and are commonly named "drift". When the clock algorithm
learns from periodic adjustments, it also gets an estimate for the
drift. Thus at each timer interrupt a small "tolerance" (uncertainty)
is added to the clock's error. If the initial error is set when
synchronizing, the kernel maintains an estimate of the current maximum
error.

The idea is to "synchronize" the kernel clock to a reference clock and
let it run free for a while, until the estimated error is too big to
be tolerated (Here a few milliseconds is considered "big" already, and
typical update intervals are between one minute and one hour).

To make the automatic correction work, the basic algorithm is modified
in a way that can deal with fractions of nanoseconds, and time_tick is
temporarily modified to yield a value that results in an error of less
than one nanosecond per timer interrupt.

Besides that regulation and error propagating machinery, the kernel
clock also handles insertion and deletion of leap seconds (if it is
told to do so).

Managing a precise and stable kernel time requires periodic updates to
the clock offset and estimated error (tolerance) of the kernel clock.
Depending on the clock's stability there is an optimal update
frequency, derived from the so-called Allan variance.  The xntpd
daemon is a program to do that (see http://www.eecis.udel.edu/~ntp),
but there's also a way to calibrate the kernel clock by external
hardware.  One of these methods is called the PPS (Pulse Per Second)
code.

2.1.1 PPS calibration
=====================

PPS calibration works very similar to time calibration, but only on a
smaller scale.  The code assumes the clock initially is closer than
0.5 seconds to some reference time.  As the PPS can only calibrate the
frequency and the offset relative to the second, the absolute time
(epoch) must be set by other means.

Basically the code automatically compares the current clock offset for
each second with a high precision external pulse (e.g. derived from a
GPS receiver, allowing a maximum relative error of 500PPM) and learns
whether the clock frequency is too slow or fast. The code can be told
to adjust only the time offset, or to adjust the frequency of the
kernel.  The precision achievable with PPS synchronization is
significantly higher than with usual adjustments.  With a Celeron-500
system with little load it is possible to get the clock as close as a
few hundred nanoseconds relative to the PPS on average.

PPS API
-------

There's a new RFC (2783) on how to implement a common programming
interface for the PPS stuff.  Linux includes an example implementation
for the serial port.  You can capture changes of the carrier detect
status line.  These events can be used to calibrate the system clock
if the pulses are stable enough.  See <linux/timepps.h>.

2.2 The new Linux implementation
================================

In the Linux implementation the CMOS clock is updated periodically
(every 11 minutes) from the kernel time when the clock is synchronized
(flag STA_UNSYNC is cleared). The flag STA_UNSYNC will automatically
be set, once the maximum error is above a fixed limit
(NTP_PHASE_LIMIT, currently about 2s).  Unfortunately the maximum
error increases with a worst-case estimate (in reality the increase of
the error depends mostly on the frequency change of the system
clock(s).  A busy system board gets warmer, and the frequency of the
clock decreases).

Linux uses one function, adjtimex, to implement the functions for
classical adjtime() and the new ntp_gettime() and ntp_adjtime()
functions.  In order to achieve that, the function uses one rather big
"struct kernel_timex" (Currently just named ``timex'' to confuse
people) that contains a "modes" field and several state variables.  By
setting individual bits in the "modes" field the specific function of
the adjtimex system call is selected while the remaining fields of the
structure are written or read as needed.

struct kernel_timex {
	unsigned int modes;	/* clock mode bits (wo) */
	long	offset;		/* time offset (ns/us) (rw) */
	long	freq;		/* frequency offset (scaled PPM) (rw) */
	long	maxerror;	/* maximum error (us) (rw) */
	long	esterror;	/* estimated error (us) (rw) */
	int	status;		/* clock status bits (rw) */
	long	constant;	/* poll interval (log2 s) (rw) */
	long	precision;	/* clock precision (ns/us) (ro) */
	long	tolerance;	/* clock frequency tolerance (scaled
				 * PPM) (ro) */
	/*----BEGIN Linux extensions (part 1) */
	/* Depending on whether ``NANO'' is defined when including
	 * this file, the same memory location can be accessed under
	 * two different names.  ``STA_NANO'' at runtime should
	 * correspond with ``NANO'' at compilation time.
	 */
#ifdef NANO
	struct timespec time;	/* current time (ns) (ro) */
#else
	struct timeval time;	/* current time (us) (ro) */
#endif /* NANO */
	long	time_tick;	/* time increment per tick (?) (rw) */
	/*----END Linux extensions (part 1) */
	/*
	 * The following read-only structure members are implemented
	 * only if the PPS signal discipline is configured in the
	 * kernel. They are included in all configurations to insure
	 * portability.
	 */
	long	ppsfreq;	/* PPS frequency (scaled PPM) (ro) */
	long	jitter;		/* PPS jitter (ns/us) (ro) */
	int	shift;		/* interval duration (s) (shift) (ro) */
	long	stabil;		/* PPS stability (scaled PPM) (ro) */
	long	jitcnt;		/* jitter limit exceeded (ro) */
	long	calcnt;		/* calibration intervals (ro) */
	long	errcnt;		/* calibration errors (ro) */
	long	stbcnt;		/* stability limit exceeded (ro) */
	/*----BEGIN Linux extensions (part 2) */
	/* first we reserve some space, then we add our new stuff */
	/* Yes, it's ugly, but it's binary compatible */
	int  :32; int  :32; int  :32; int  :32;
	int tickadj;		/* tickadj (us) (rw) -- extension by UW */
	int  :32; int  :32; int  :32;
	int  :32; int  :32; int  :32; int  :32;
	/*----END Linux extensions (part 2) */
};

The official ntp_gettime() function only returns these data:

struct ntptimeval {
	struct timeval	time;	/* current time (ro) */
	long maxerror;		/* maximum error (us) (ro) */
	long esterror;		/* estimated error (us) (ro) */
};

The official ntp_adjtime() function contains these data (note the lack
of `time'!):

struct timex {
	unsigned int modes;	/* mode selector */
	long offset;		/* time offset (usec) */
	long freq;		/* frequency offset (scaled ppm) */
	long maxerror;		/* maximum error (usec) */
	long esterror;		/* estimated error (usec) */
	int status;		/* clock command/status */
	long constant;		/* pll time constant */
	long precision;		/* clock precision (usec) (read only) */
	long tolerance;		/* clock frequency tolerance (ppm)
				 * (read only)
				 */

	long ppsfreq;           /* pps frequency (scaled ppm) (ro) */
	long jitter;            /* pps jitter (us) (ro) */
	int shift;              /* interval duration (s) (shift) (ro) */
	long stabil;            /* pps stability (scaled ppm) (ro) */
	long jitcnt;            /* jitter limit exceeded (ro) */
	long calcnt;            /* calibration intervals (ro) */
	long errcnt;            /* calibration errors (ro) */
	long stbcnt;            /* stability limit exceeded (ro) */
};

The symbolic names of the bits used to select the NTP compatible
operating modes all start with "MOD_"; extensions start with "ADJ_".
The specific status of the kernel clock (`status') is also expressed
by a set of bits, all starting with "STA_".

Thus the classical function "adjtime" can be implemented as follows
(please note that "struct timeval" is reduced to a single "long",
causing severe restrictions):

/* This is a simple-minded implementation! */
inline	int adjtime (const struct timeval *delta, struct timeval *olddelta)
{
	struct timex	tntx;
	int		result;
	if (delta) {
		struct timeval tmp;

		/* We enforce some arbitrary (2000s) limit here. */
		tmp.tv_sec = delta->tv_sec + delta->tv_usec / 1000000L;
		tmp.tv_usec = delta->tv_usec % 1000000L;
		if (tmp.tv_sec > 2000 || tmp.tv_sec < -2000) {
			return -1;
		}
		tntx.offset = tmp.tv_usec + tmp.tv_sec * 1000000L;
		tntx.modes = ADJ_ADJTIME;
	}
	else
		tntx.modes = 0;
	result = __adjtimex (&tntx);
	if (result >= 0 && olddelta) {
		if (tntx.offset < 0) {
			olddelta->tv_usec = -(-tntx.offset % 1000000);
			olddelta->tv_sec  = -(-tntx.offset / 1000000);
		} else {
			olddelta->tv_usec = tntx.offset % 1000000;
			olddelta->tv_sec  = tntx.offset / 1000000;
		}
	}
	return result;
}

The "ntp_gettime" and "ntp_adjtime" functions can be implemented as
follows:

int ntp_gettime(struct ntptimeval *tptr)
{
	struct kernel_timex tx;
	int result;

	tx.modes = 0;
	result = adjtimex(&tx);
	tptr->time = tx.time;
	tptr->maxerror = tx.maxerror;
	tptr->esterror = tx.esterror;
	return(result);
}

inline	int adjtime (const struct timeval *delta, struct timeval *olddelta)
{
	struct timex	tntx;
	int		result;
	if (delta) {
		struct timeval tmp;

		/* We enforce some arbitrary (2000s) limit here. */
		tmp.tv_sec = delta->tv_sec + delta->tv_usec / 1000000L;
		tmp.tv_usec = delta->tv_usec % 1000000L;
		if (tmp.tv_sec > 2000 || tmp.tv_sec < -2000) {
			return -1;
		}
		tntx.offset = tmp.tv_usec + tmp.tv_sec * 1000000L;
		tntx.modes = ADJ_ADJTIME;
	}
	else
		tntx.modes = 0;
	result = __adjtimex (&tntx);
	if (result >= 0 && olddelta) {
		if (tntx.offset < 0) {
			olddelta->tv_usec = -(-tntx.offset % 1000000);
			olddelta->tv_sec  = -(-tntx.offset / 1000000);
		} else {
			olddelta->tv_usec = tntx.offset % 1000000;
			olddelta->tv_sec  = tntx.offset / 1000000;
		}
	}
	return result;
}

2.3 Problems
============

The kernel's ``struct timex'' is an equivalent superset of NTP's timex
structure.

Ulrich Windl
2003-03-21
