Skip to main content

3. Technical Summary

In order to more fully understand the workings of the model, a stand-alone simulator kern.c and header file timex.h are included in the kernel.tar.Z distribution mentioned previously. In addition, a complete C program kern_ntptime.c which implements the ntp_gettime() and ntp_adjtime() functions is provided, but with the vendor-specific argument-passing code deleted. Since the distribution is somewhat large, due to copious comments and ornamentation, it is impractical to include a listing of these programs in this memorandum. In any case, implementors may choose to snip portions of the simulator for use in new kernel designs, but, due to formatting conventions, this would be difficult if included in this memorandum.

The kern.c program is an implementation of an adaptive-parameter, first-order, type-II phase-lock loop. The system clock is implemented using a set of variables and algorithms defined in the simulator and driven by explicit offsets generated by a driver program also included in the program. The algorithms include code fragments almost identical to those in the machine-specific kernel implementations and operate in the same way, but the operations can be understood separately from any licensed source code into which these fragments may be integrated. The code fragments themselves are not derived from any licensed code. The following discussion assumes that the simulator code is available for inspection.

3.1. PLL Simulation​

The simulator operates in conformance with the analytical model described in [3]. The main() program operates as a driver for the fragments hardupdate(), hardclock(), second_overflow(), hardpps() and microtime(), although not all functions implemented in these fragments are simulated. The program simulates the PLL at each timer interrupt and prints a summary of critical program variables at each time update.

There are three defined options in the kernel configuration file specific to each implementation. The PPS_SYNC option provides support for a pulse-per-second (PPS) signal, which is used to discipline the frequency of the CPU clock oscillator. The EXT_CLOCK option provides support for an external kernel-readable clock, such as the KSI/Odetics TPRO IRIG interface or HIGHBALL precision oscillator, both for the SBus. The TPRO option provides support for the former, while the HIGHBALL option provides support for the latter. External clocks are implemented as the microtime() clock driver, with the specific source code selected by the kernel configuration file.

3.1.1. The hardupdate() Fragment​

The hardupdate() fragment is called by ntp_adjtime() as each update is computed to adjust the system clock phase and frequency. Note that the time constant is in units of powers of two, so that multiplies can be done by simple shifts. The phase variable is computed as the offset divided by the time constant. Then, the time since the last update is computed and clamped to a maximum (for robustness) and to zero if initializing. The offset is multiplied (sorry about the ugly multiply) by the result and divided by the square of the time constant and then added to the frequency variable. Note that all shifts are assumed to be positive and that a shift of a signed quantity to the right requires a little dance.

With the defines given, the maximum time offset is determined by the size in bits of the long type (32 or 64) less the SHIFT_UPDATE scale factor (12) or at least 20 bits (signed). The scale factor is chosen so that there is no loss of significance in later steps, which may involve a right shift up to SHIFT_UPDATE bits. This results in a time adjustment range over +-512 ms. Since time_constant must be greater than or equal to zero, the maximum frequency offset is determined by the SHIFT_USEC scale factor (16) or at least 16 bits (signed). This results in a frequency adjustment range over +-31,500 ppm.

In the addition step, the value of offset * mtemp is not greater than MAXPHASE * MAXSEC = 31 bits (signed), which will not overflow a long add on a 32-bit machine. There could be a loss of precision due to the right shift of up to 12 bits, since time_constant is bounded at 6. This results in a net worst-case frequency resolution of about .063 ppm, which is not significant for most quartz oscillators. The worst case could be realized only if the NTP peer misbehaves according to the protocol specification.

The time_offset value is clamped upon entry. The time_phase variable is an accumulator, so is clamped to the tolerance on every call. This helps to damp transients before the oscillator frequency has been determined, as well as to satisfy the correctness assertions if the time synchronization protocol or implementation misbehaves.

3.1.2. The hardclock() Fragment​

The hardclock() fragment is inserted in the hardware timer interrupt routine at the point the system clock is to be incremented. Previous to this fragment the time_update variable has been initialized to the value computed by the adjtime() system call in the stock Unix kernel, normally plus/minus the tickadj value, which is usually in the order of 5 us. The time_phase variable, which represents the instantaneous phase of the system clock, is advanced by time_adj, which is calculated in the second_overflow() fragment described below. If the value of time_phase exceeds 1 us in scaled units, time_update is increased by the (signed) excess and time_phase retains the residue.

Except in the case of an external oscillator such as the HIGHBALL interface, the hardclock() fragment advances the system clock by the value of tick plus time_update. However, in the case of an external oscillator, the system clock is obtained directly from the interface and time_update used to

discipline that interface instead. However, the system clock must still be disciplined as explained previously, so the value of clock_cpu computed by the second_overflow() fragment is used instead.

3.1.3. The second_overflow() Fragment​

The second_overflow() fragment is inserted at the point where the microseconds field of the system time variable is being checked for overflow. Upon overflow the maximum error time_maxerror is increased by time_tolerance to reflect the maximum time offset due to oscillator frequency error. Then, the increment time_adj to advance the kernel time variable is calculated from the (scaled) time_offset and time_freq variables updated at the last call to the hardclock() fragment.

The phase adjustment is calculated as a (signed) fraction of the time_offset remaining, where the fraction is added to time_adj, then subtracted from time_offset. This technique provides a rapid convergence when offsets are high, together with good resolution when offsets are low. The frequency adjustment is the sum of the (scaled) time_freq variable, an adjustment necessary when the tick interval does not evenly divide one second fixtick and PPS frequency adjustment pps_ybar (if configured).

The scheme of approximating exact multiply/divide operations with shifts produces good results, except when an exact calculation is required, such as when the PPS signal is being used to discipling the CPU clock oscillator frequency, as described below. As long as the actual oscillator frequency is a power of two in seconds, no correction is required. However, in the SunOS kernel the clock frequency is 100 Hz, which results in an error factor of 0.78. In this case the code increases time_adj by a factor of 1.25, which results in an overall error less than three percent.

On rollover of the day, the leap-second state machine described below determines whether a second is to be inserted or deleted in the timescale. The microtime() routine insures that the reported time is always monotonically increasing.

3.1.4. The hardpps() Fragment​

The hardpps() fragment is operative only if the PPS_SYNC option is specified in the kernel configuration file. It is called from the serial port driver or equivalent interface at the on-time transition of the PPS signal. The fragment operates as a

first-order, type-I frequency-lock loop (FLL) controlled by the difference between the frequency represented by the pps_ybar variable and the frequency of the hardware clock oscillator.

In order to avoid calling the microtime() routine more than once for each PPS transition, the interface requires the calling program to capture the system time and hardware counter contents at the on-time transition of the PPS signal and provide a pointer to the timestamp (Unix timeval) and counter contents as arguments to the hardpps() call. The hardware counter contents can be determined by saving the microseconds field of the system time, calling the microtime() routine, and subtracting the saved value. If a counter overflow has occured during the process, the resulting microseconds value will be negative, in which case the caller adds 1000000 to normalize the microseconds field.

The frequency of the hardware oscillator can be determined from the difference in hardware counter readings at the beginning and end of the calibration interval divided by the duration of the interval. However, the oscillator frequency tolerance, as much as 100 ppm, may cause the difference to exceed the tick value, creating an ambiguity. In order to avoid this ambiguity, the hardware counter value at the beginning of the interval is increased by the current pps_ybar value once each second, but computed modulo the tick value. At the end of the interval, the difference between this value and the value computed from the hardware counter is used as a control signal sample for the FLL.

Control signal samples which exceed the frequency tolerance are discarded, as well as samples resulting from excessive interval duration jitter. Surviving samples are then processed by a three-stage median filter. The signal which drives the FLL is derived from the median sample, while the average of differences between the other two samples is used as a measure of dispersion. If the dispersion is below the threshold pps_dispmax, the median is used to correct the pps_ybar value with a weight expressed as a shift PPS_AVG (2). In addition to the averaging function, pps_disp is increased by the amount pps_dispinc once each second. The result is that, should the dispersion be exceptionally high, or if the PPS signal fails for some reason, the pps_disp will eventually exceed pps_dispmax and raise an alarm.

Initially, an approximate value for pps_ybar is not known, so the duration of the calibration interval must be kept small to avoid overflowing the tick. The time difference at the end of

the calibration interval is measured. If greater than a fraction tick/4, the interval is reduced by half. If less than this fraction for four successive calibration intervals, the interval is doubled. This design automatically adapts to nominal jitter in the PPS signal, as well as the value of tick. The duration of the calibration interval is set by the pps_shift variable as a shift in powers of two. The minimum value PPS_SHIFT (2) is chosen so that with the highest CPU oscillator frequency 1024 Hz and frequency tolerance 100 ppm the tick will not overflow. The maximum value PPS_SHIFTMAX (8) is chosen such that the maximum averaging time is about 1000 s as determined by measurements of Allan variance [5].

Should the PPS signal fail, the current frequency estimate pps_ybar continues to be used, so the nominal frequency remains correct subject only to the instability of the undisciplined oscillator. The procedure to save and restore the frequency estimate works as follows. When setting the frequency from a file, the time_freq value is set as the file value minus the pps_ybar value; when retrieving the frequency, the two values are added before saving in the file. This scheme provides a seamless interface should the PPS signal fail or the kernel configuration change. Note that the frequency discipline is active whether or not the synchronization daemon is active. Since all Unix systems take some time after reboot to build a running system, usually by that time the discipline process has already settled down and the initial transients due to frequency discipline have damped out.

3.1.4. External Clock Interface​

The external clock driver interface is implemented with two routines, microtime(), which returns the current clock time, and clock_set(), which furnishes the apparent system time derived from the kernel time variable. The latter routine is called only when the clock is set using the settimeofday() system call, but can be called from within the driver, such as when the year rolls over, for example.

In the stock SunOS kernel and modified Ultrix and OSF/1 kernels, the microtime() routine returns the kernel time variable plus an interpolation between timer interrupts based on the contents of a hardware counter. In the case of an external clock, such as described above, the system clock is read directly from the hardware clock registers. Examples of external clock drivers are in the tprotime.c and hightime.c routines included in the kernel.tar.Z distribution.

The external clock routines return a status code which indicates whether the clock is operating correctly and the nature of the problem, if not. The return code is interpreted by the ntp_gettime() system call, which transitions the status state machine to the TIME_ERR state if an error code is returned. This is the only error checking implemented for the external clock in the present version of the code.

The simulator has been used to check the PLL operation over the design envelope of +-512 ms in time error and +-100 ppm in frequency error. This confirms that no overflows occur and that the loop initially converges in about 15 minutes for timer interrupt rates from 50 Hz to 1024 Hz. The loop has a normal overshoot of a few percent and a final convergence time of several hours, depending on the initial time and frequency error.

3.2. Leap Seconds​

It does not seem generally useful in the user application interface to provide additional details private to the kernel and synchronization protocol, such as stratum, reference identifier, reference timestamp and so forth. It would in principle be possible for the application to independently evaluate the quality of time and project into the future how long this time might be "valid." However, to do that properly would duplicate the functionality of the synchronization protocol and require knowledge of many mundane details of the platform architecture, such as the subnet configuration, reachability status and related variables. For the curious, the ntp_adjtime() system call can be used to reveal some of these mysteries.

However, the user application may need to know whether a leap second is scheduled, since this might affect interval calculations spanning the event. A leap-warning condition is determined by the synchronization protocol (if remotely synchronized), by the timecode receiver (if available), or by the operator (if awake). This condition is set by the synchronization daemon on the day the leap second is to occur (30 June or 31 December, as announced) by specifying in a ntp_adjtime() system call a clock status of either TIME_DEL, if a second is to be deleted, or TIME_INS, if a second is to be inserted. Note that, on all occasions since the inception of the leap-second scheme, there has never been a deletion occasion, nor is there likely to be one in future. If the value is TIME_DEL, the kernel adds one second to the system time immediately following second 23:59:58 and resets the clock status to TIME_OK. If the value is TIME_INS, the kernel subtracts one second from the system time immediately following second 23:59:59 and resets the clock status to TIME_OOP, in effect causing system

time to repeat second 59. Immediately following the repeated second, the kernel resets the clock status to TIME_OK.

Depending upon the system call implementation, the reported time during a leap second may repeat (with the TIME_OOP return code set to advertise that fact) or be monotonically adjusted until system time "catches up" to reported time. With the latter scheme the reported time will be correct before and shortly after the leap second (depending on the number of microtime() calls during the leap second), but freeze or slowly advance during the leap second itself. However, Most programs will probably use the ctime() library routine to convert from timeval (seconds, microseconds) format to tm format (seconds, minutes,...). If this routine is modified to use the ntp_gettime() system call and inspect the return code, it could simply report the leap second as second 60.

3.3. Clock Status State Machine​

The various options possible with the system clock model described in this memorandum require a careful examination of the state transitions, status indications and recovery procedures should a crucial signal or interface fail. In this section is presented a prototype state machine designed to support leap second insertion and deletion, as well as reveal various kinds of errors in the synchronization process. The states of this machine are decoded as follows:

      TIME_OK   If an external clock is present, it is working properly
                and the system clock is derived from it. If no external
                clock is present, the synchronization daemon is working
                properly and the system clock is synchronized to a radio
                clock or one or more peers.

      TIME_INS  An insertion of one second in the system clock has been
                declared following the last second of the current day,
                but has not yet been executed.

      TIME_DEL  A deletion of the last second of the current day has
                been declared, but not yet executed.

      TIME_OOP  An insertion of one second in the system clock has been
                declared following the last second of the current day.
                The second is in progress, but not yet completed.
                Library conversion routines should interpret this second
                as 23:59:60.

      TIME_BAD  Either (a) the synchronization daemon has declared the
                protocol is not working properly, (b) all sources of
                outside synchronization have been lost or (c) an
                external clock is present and it has just become
                operational following a non-operational condition.

      TIME_ERR  An external clock is present, but is in a non-
                operational condition.

      In all except the TIME_ERR state the system clock is derived from
      either an external clock, if present, or the kernel time variable,
      if not. In the TIME_ERR state the external clock is present, but
      not working properly, so the system clock may be derived from the
      kernel time variable. The following diagram indicates the normal
      transitions of the state machine. Not all valid transitions are
      shown.

          +--------+     +--------+     +--------+     +--------+
          |        |     |        |     |        |     |        |
          |TIME_BAD|---->|TIME_OK |<----|TIME_OOP|<----|TIME_INS|
          |        |     |        |     |        |     |        |
          +--------+     +--------+     +--------+     +--------+
               A              A
               |              |
               |              |
          +--------+     +--------+
          |        |     |        |
          |TIME_ERR|     |TIME_DEL|
          |        |     |        |
          +--------+     +--------+

      The state machine makes a transition once each second at an
      instant where the microseconds field of the kernel time variable
      overflows and one second is added to the seconds field. However,
      this condition is checked at each timer interrupt, which may not
      exactly coincide with the actual instant of overflow. This may
      lead to some interesting anomalies, such as a status indication of
      a leap second in progress (TIME_OOP) when actually the leap second
      had already expired.

      The following state transitions are executed automatically by the
      kernel:

      any state -> TIME_ERR   This transition occurs when an external
                              clock is present and an attempt is made to
                              read it when in a non-operational
                              condition.

      TIME_INS -> TIME_OOP    This transition occurs immediately
                              following second 86,400 of the current day
                              when an insert-second event has been
                              declared.

      TIME_OOP -> TIME_OK     This transition occurs immediately
                              following second 86,401 of the current
                              day; that is, one second after entry to
                              the TIME_OOP state.

      TIME_DEL -> TIME_OK     This transition occurs immediately
                              following second 86,399 of the current day
                              when a delete-second event has been
                              declared.

      The following state transitions are executed by specific
      ntp_adjtime() system calls:

      TIME_OK -> TIME_INS     This transition occurs as the result of a
                              ntp_adjtime() system call to declare an
                              insert-second event.

      TIME_OK -> TIME_DEL     This transition occurs as the result of a
                              ntp_adjtime() system call to declare a
                              delete-second event.

      any state -> TIME_BAD   This transition occurs as the result of a
                              ntp_adjtime() system call to declare loss
                              of all sources of synchronization or in
                              other cases of error.

      The following table summarizes the actions just before, during and
      just after a leap-second event. Each line in the table shows the
      UTC and NTP times at the beginning of the second. The left column
      shows the behavior when no leap event is to occur. In the middle
      column the state machine is in TIME_INS at the end of UTC second
      23:59:59 and the NTP time has just reached 400. The NTP time is
      set back one second to 399 and the machine enters TIME_OOP. At the
      end of the repeated second the machine enters TIME_OK and the UTC
      and NTP times are again in correspondence. In the right column the
      state machine is in TIME_DEL at the end of UTC second 23:59:58 and
      the NTP time has just reached 399. The NTP time is incremented,
      the machine enters TIME_OK and both UTC and NTP times are again in
      correspondence.

                   No Leap       Leap Insert    Leap Delete
                   UTC NTP         UTC NTP        UTC NTP
              ---------------------------------------------
              23:59:58|398    23:59:58|398   23:59:58|398
                      |               |              |
              23:59:59|399    23:59:59|399   00:00:00|400
                      |               |              |
              00:00:00|400    23:59:60|399   00:00:01|401
                      |               |              |
              00:00:01|401    00:00:00|400   00:00:02|402
                      |               |              |
              00:00:02|402    00:00:01|401   00:00:03|403
                      |               |              |

      To determine local midnight without fuss, the kernel code simply
      finds the residue of the time.tv_sec (or time.tv_sec + 1) value
      mod 86,400, but this requires a messy divide. Probably a better
      way to do this is to initialize an auxiliary counter in the
      settimeofday() routine using an ugly divide and increment the
      counter at the same time the time.tv_sec is incremented in the
      timer interrupt routine. For future embellishment.