(Emacs: -*- indented-text -*-)


			  Implementation of
	Nanosecond Time and a PPS API for the Linux 2.2 Kernel

	      Copyright (c) 1996 - 1999 by Ulrich Windl
		 <Ulrich.Windl@rz.uni-regensburg.de>
			    11th May 1999

      This file describes ``PPSkit 0.7'', a small collection of
   files to support the ``Kernel Model for Precision Timekeeping''
	 as described in RFC-1589, the technical memorandum,
	  and by the kernel simulator written by Dave Mills.
	  The PPS API is currently (still) a working draft.
		  Mainly this algorithms are used by
	  NTPv3 (Network Time Protocol, RFC1305) and NTPv4.
      Support is added for adjusting the offset and frequency of
    the kernel clock towards an external pulse-per-second signal.


Overview:
--------

This collection contains:

     0) A new kernel that keeps time in nanoseconds (instead of
        microseconds).  These changes come along with several other
        improvements and cleanups.

     1) Extension for adjtimex() to adjust the value of `tickadj'
        (defaults to 500/HZ). This can be useful when the adjtime()
        doesn't work at all or is too slow (1ms on Alpha architecture,
        0.5ms per second by default on i386 architecture).

     2) New code to support PPS (pulse-per-second) clock
        synchronization in the kernel.

     3) Example implementation for the serial driver (implements
        detection of pulse on DCD pin).  The implementation uses the
        new PPS API for portability and nanosecond accuracy.  The
        older microsecond resolution via CIOGETEV is still supported.

     4) Some utilities and documentation files (like this).


A short History of Changes and Plans:
------------------------------------

* In Linux 2.0.30 there was a module-hook for a function ``hardpps''
  to handle the timekeeping stuff.  As the code for timekeeping does
  not depend on the way the signal is fed into the hardware, but only
  on how the signal is detected, it was decided to add the PPS
  timekeeping code to kernel/time.c and to remove that hook.

* The new ``hardpps'' routine expects the time of the pulse to be
  passed as parameters.

* The interrupt routine of the serial driver collects precision
  timestamps that can be retrieved via the PPS API.  They can also be
  automatically passed to a ``hardpps()'' kernel routine to discipline
  the clock.  Care has been taken that the serial driver is still
  usable without PPS applications.

* The xntp package contains code to support a CIOGETEV ioctl that
  reads precision time-stamps of external events on the carrier detect
  line of a serial port.  CIOGETEV has been implemented as a new line
  discipline that fills the structure `ppsclockev'.  That structure
  contains an event count and a ``struct timeval'' of the last event.
  The code has been adapted from a more complete solution made by
  Harald Koenig.

* A former implementation of the FreeBSD-like ``TIOCDCDTIMESTAMP'' has
  been removed again, because it required a change to the
  serial_struct, thus causing incompatibilities for existing binaries.
  Also, the CIOGETEV gets the same data.  H. Peter Anvin had
  implemented that function around Linux 2.1.40.

* The adjtimex() system call has been extended to allow reading and
  modifying of ``tickadj''.  This is not strictly required for
  accurate clock operation, but is rather helpful if the default slew
  rate of 0.5ms per second is too slow for a larger correction made by
  ``adjtime()''.

* The PPSkit (0.4) has been merged into Linux-2.2 shortly before it
  came out.  Thus 2.2.0 has some essential time fixes that older
  versions did not have (these fixes entered 2.0 when 2.1 already
  existed).

* In preparation for exchanging the major part of the NTP code, the
  code has been restructured for PPSkit-0.5.  The next generation will
  have 64bit quantities measuring nanoseconds.  Currently noone in the
  kernel provides nanoseconds, but we'll be prepared.

* In PPSkit-0.6 the kernel was converted to nanoseconds by brute
  force.  Along with the new 64bit time variables came the new kernel
  clock model known as the ``nanokernel'' (because it features
  nanoseconds and ``STA_NANO'').  It is planned to bring some of the
  related fixes back to the stable standard kernel.

* PPSkit-0.7 finally brought the PPS API as well as an important fix
  for the jitter in the time stamps (Many thanks to Reg Clemens)

Notes on Usage:
--------------

* The old code to activate PPS event processing has been replaced with
  the PPS API.  The old code was: like the following:

	struct serial_struct ss;
	ioctl(fd, TIOCGSERIAL, &ss);	/* enable pulse detection on DCD */
	ss.flags |= ASYNC_PPS_CD_POS;	/* or ``ASYNC_PPS_CD_NEG'' */
	ioctl(fd, TIOCSSERIAL, &ss);

  The new code uses the functions ``time_pps_create'' and
  ``time_pps_set_param'' to activate capturing of events.  The
  following code is from ``draft-mogul-pps-api-03.txt'' (comments
  added):

      #include <sys/timepps.h>
      int fd;
      pps_handle_t handle;	/* handle for PPS sources */
      pps_params_t params;	/* selection of events, options */
      pps_info_t infobuf;	/* status of events */

      /* Open a file descriptor and enable PPS on rising edges */
      fd = open(PPSfilename, O_RDWR, 0);
      time_pps_create(fd, &handle);
      params.mode = PPS_CAPTUREASSERT;	/* ASSERT == rising edge */
      time_pps_setparams(handle, &params);

      /* loop, printing the most recent timestamp every second or so */
      while (1) {
          sleep(1);
          time_pps_fetch(handle, &infobuf);
          printf("Assert timestamp: %d.%09d, sequence: %ld\n",
	         infobuf.assert_timestamp.tv_sec,
                 infobuf.assert_timestamp.tv_nsec,
                 infobuf.assert_sequence);
      }


  With ntp-4.0.92h the PPS event processing code has to be activated
  once ntpd is up and running. Here is an example what ntptime may
  report:

ntp_gettime() returns code 0 (OK)
  time bae31ee2.77cddd40  Tue, May 11 1999 23:25:54.467, (.467985441),
  maximum error 48163 us, estimated error 13 us.
ntp_adjtime() returns code 0 (OK)
  modes 0x0 (),
  offset 0.070 us, frequency 16.824 ppm, interval 256 s,
  maximum error 48163 us, estimated error 13 us,
  status 0x2107 (PLL,PPSFREQ,PPSTIME,PPSSIGNAL,NANO),
  time constant 6, precision 3.120 us, tolerance 496 ppm,
  pps frequency 16.824 ppm, stability 0.076 ppm, jitter 2.038 us,
  intervals 80, jitter exceeded 28, stability exceeded 0, errors 4.

  ``ntpq -p'' says something like:

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
+GENERIC(1)      .GPS.            0 -   59   64  377    0.000    0.001   0.001
oPPS(1)          .PPS.            0 -   47   64  377    0.000    0.001   0.000


* The current implementation still leaves room for improvement, but it
  is working fine at several places.  As the additional code is
  usually inactive, only a few additional CPU cycles are needed.
  Still, nanoseconds don't come for nothing.  Measurements on my
  Pentium 100MHz have shown that the `hardware_pps' routine takes
  between 250 and 11000 CPU cycles per call (with debugging messages
  enabled, of course).

* I wrote the test program `gen_pps.c' that uses the RTC driver (see
  /proc/rtc) to create a PPS pulse on the UART's RTS pin (pin 4 on
  "COM2" (25 pins)).  The program needs the device name for the port
  to use (e.g. /dev/cua0). I made a very simple cable between the BD9
  and DB25 connector:

  (input)	(output)
  DB9:		DB25:
  ---		----
  1 -----------	4	(CD, RTS)
  5 -----------	7	(GND, GND)

  Unfortunately the RTC driver seems to have some problems (last seen
  in 2.0.36): From time to time the kernel says: ``rtc: lost some
  interrupts at 2Hz.'' (This is because updating the RTC will reset
  the divider for the periodic interrupt)
  [You should get a real PPS source, not this cheap trick]

* Yet another program (enable_pps.c) can be used to enable detection
  of the PPS signal on the CD pin and exercise the kernel clock
  machinery.  That program expects standard input to be redirected
  from the desired port, and event processing will still be enabled
  until the parameters are changed, or until the port is closed.

* The programs are just my test programs to validate the code; don't
  expect them to synchronize your time!  Even worse, they may
  de-adjust your kernel clock badly.  Use xntp3-5.93 for nice and
  stable NTP support.  Beginning with ntp-4.0.92h things also look
  good.

* Usually you need some level converter to connect the TTL level
  output of a clock to the CD input of the serial port.  A friend of
  mine and I have developed a simple converter that is powered from
  the serial port's status lines.  There's also some information about
  a sample device (`gadget box') on the NTP home page
  http://www.eecis.udel.edu/~ntp/.

* To get a quick start with xntp configuration and PPS read the
  documentation (that comes with xntp) on ``PPS'' (pps.html) and
  ``enable pps'' (prefer.html) and ``refclock ATOM'' (driver22.html).
  You are kindly advised to read ``debug.html'' before reporting
  problems to the xntp developers or to the newsgroup
  comp.protocols.time.ntp.  There's also a FAQ, but slighly
  old... (mostly composed from comp.protocols.time.ntp)
