Network Working Group Jeffrey Mogul, DECWRL Internet-Draft David Mills, UDel Expires: 15 December 1998 Jan Brittenson, Sun Jonathan Stone, Stanford Poul-Henning Kamp, FreeBSD Ulrich Windl, Universitaet Regensburg 10 June 1998 Pulse-Per-Second API for UNIX-like Operating Systems, Version 1.0 draft-mogul-pps-api-02.txt STATUS OF THIS MEMO This document is an Internet-Draft. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF), its areas, and its working groups. Note that other groups may also distribute working documents as Internet-Drafts. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." To view the entire list of current Internet-Drafts, please check the "1id-abstracts.txt" listing contained in the Internet-Drafts Shadow Directories on ftp.is.co.za (Africa), ftp.nordu.net (Northern Europe), ftp.nis.garr.it (Southern Europe), munnari.oz.au (Pacific Rim), ftp.ietf.org (US East Coast), or ftp.isi.edu (US West Coast). Distribution of this document is unlimited. Please send comments to the authors. ABSTRACT RFC1589 describes a UNIX kernel implementation model for high-precision time-keeping. This model is meant for use in conjunction with the Network Time Protocol (NTP, RFC1305), or similar time synchronization protocols. One aspect of this model is an accurate interface to the high-accuracy, one pulse-per-second (PPS) output typically available from precise time sources (such as a GPS or GOES receiver). RFC1589 did not define an API for managing the PPS facility, leaving implementors without a portable means for using PPS sources. This document specifies such an API. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 1] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 TABLE OF CONTENTS 1 Introduction 2 2 Data types for representing timestamps 4 2.1 Resolution 4 2.2 Time scale 5 3 API 5 3.1 PPS abstraction 5 3.2 New data structures 6 3.3 Mode bit definitions 9 3.4 New functions 11 3.4.1 New functions: obtaining PPS sources 11 3.4.2 New functions: setting PPS parameters 13 3.4.3 New functions: access to PPS timestamps 14 3.4.4 New functions: disciplining the kernel timebase 15 3.4.5 New functions: waiting for an event 15 3.5 Compliance rules 17 3.5.1 Functions 17 3.5.2 Mode bits 17 3.6 Examples 18 4 Security Considerations 19 5 Acknowledgements 20 6 References 20 7 Authors' addresses 21 A. Extensions Related APIs 21 A.1 Extension: Parameters for the ``echo'' mechanism 22 A.2 Extension: Obtaining information about external clocks 22 A.3 Extension: Finding a PPS source 23 B. Example implementation: PPSDISC Line discipline 23 B.1 Example 24 C. Available implementations 24 C.1 FreeBSD 25 C.2 NetBSD 25 1 Introduction RFC1589 [4] describes a model and programming interface for generic operating system software that manages the system clock and timer functions. The model provides improved accuracy and stability for most workstations and servers using the Network Time Protocol (NTP) [3] or similar time synchronization protocol. The model supports the use of external timing sources, such as the precision pulse-per-second (PPS) signals typically available from precise time sources (such as a GPS or GOES receiver). However, RFC1589 did not define an application programming interface (API) for the PPS facility. This document specifies such an Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 2] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 interface, for use with UNIX (or UNIX-like) operating systems. Such systems often conform to the ``Single UNIX Specification'' [5], sometimes known as POSIX. One convenient means to provide a PPS signal to a computer system is to connect that signal to a modem-control pin on a serial-line interface to the computer. The Data Carrier Detect (DCD) pin is frequently used for this purpose. Typically, the time-code output of the time source is transmitted to the computer over the same serial line. The computer detects a signal transition on the DCD pin, usually by receiving an interrupt, and records a timestamp as immediately as possible. Although existing practice has focussed on the use of serial lines and DCD transitions, PPS signals might also be delivered by other kinds of devices. The API specified in this document does not require the use of a serial line, although it may be somewhat biased in that direction. The typical use of this facility is for the operating system to record a high-resolution timestamp as soon as possible after it detects a PPS signal transition (usually indicated by an interrupt). This timestamp can then be made available, with less stringent delay constraints, to timekeeping software. The software can compare the captured timestamp to the received time-code to accurately determine the absolute offset between the system clock and the precise time source. The operating system may also deliver the PPS event immediately to a procedure used to discipline its internal timebase, such as the ``hardpps()'' procedure described in RFC1589. The API specified in this document allows for one or more signal sources attached to a computer system to provide PPS inputs, at the option of user-level software. User-level software may obtain signal-transition timestamps for any of these PPS sources. User-level software may optionally specify that at most one of these PPS sources be used to discipline the system's internal timebase. Although the primary purpose of this API is for capturing true pulse-per-second events, the API may also be used for accurately timestamping events of other periods, or even aperiodic events, when these can be expressed as signal transitions. This document does not define how the API must be implemented, and does not specify constraints on the accuracy, resolution, or latency of the PPS feature. However, the utility of this feature is inversely proportional to the delay (and variance of delay), and implementors are encouraged to take this seriously. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 3] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 In principle, the rate of events to be captured, or the frequency of the signals, can range from once per day (or less often) to several thousand per second. However, since in most implementations the timestamping function will be implemented as a processor interrupt at a relatively high priority, it is prudent to limit the rate of such events. This may be done either by mechanisms in the hardware that generates the signals, or by the operating system. 2 Data types for representing timestamps Computer systems use various representations of time. Because this API is concerned with the provision of high-accuracy, high-resolution time information, the choice of representation is significant. (Here we consider only binary representations, not human-format representations.) The two interesting questions are: 1. what is the resolution of the representation? 2. what time scale is represented? These questions often lead to contentious arguments. Since this API is intended for use with NTP and POSIX-compliant systems, however, we can limit the choices to representations compatible with existing NTP and POSIX practice, even if that practice is considered ``wrong'' in some quarters. 2.1 Resolution In the NTP protocol, ``timestamps are represented as a 64-bit unsigned fixed-point number, in seconds relative to 0h on 1 January 1900. The integer part is in the first 32 bits and the fraction part in the last 32 bits [...] The precision of this representation is about 200 picoseconds'' [3]. However, most computer systems cannot measure time to this resolution (this represents a clock rate of 5 GHz). The POSIX gettimeofday() function returns a ``struct timeval'' value, with a resolution of 1 microsecond. The POSIX clock_gettime() function returns a ``struct timespec'' value, with a resolution of 1 nanosecond. This API uses an extensible representation, but defaults to the ``struct timespec'' representation, since in a general-purpose computer system it is just barely feasible to measure time to a resolution of a few microseconds. It might become possible to improve this resolution within the next few years. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 4] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 2.2 Time scale Several different time scales have been proposed for use in computer systems. UTC and TAI are the two obvious candidates. Some people would prefer the use of TAI, which is identical to UTC except that it does not correct for leap seconds. Their preference for TAI stems from the difficulty of computing precise time differences when leap seconds are involved, especially when using times in the future (for which the exact number of leap seconds is, in general, unknowable). However, POSIX and NTP both use UTC, albeit with different base dates. Given that support for TAI would, in general, require other changes to the POSIX specification, This API uses the POSIX base date of midnight January 1, 1970. 3 API A PPS facility can be used in two different ways: 1. An application can obtain a timestamp, using the system's internal timebase, for the most recent PPS event. 2. A kernel may directly utilize PPS events to discipline its internal timebase, thereby providing highly accurate time to all applications. This API supports both uses, individually or in combination. The timestamping feature may be used on any number of PPS sources simultaneously; the timebase-disciplining feature may be used with at most one PPS source. Although the proper implementation of this API requires support from the kernel of a UNIX system, this document defines the API in terms of a set of library routines. This gives the implementor some freedom to divide the effort between kernel code and library code (different divisions might be appropriate on microkernels and monolithic kernels, for example). 3.1 PPS abstraction A PPS signal consists of a series of pulses, each with an ``asserted'' (logical true) phase, and a ``clear'' (logical false) phase. The two phases may be of different lengths. The API may capture an ``assert timestamp'' at the moment of the transition into the asserted phase, and a ``clear timestamp'' at the moment of the transition into the clear phase. The specific assignment of the logical values ``true'' and ``false'' with specific voltages of a PPS signal, if applicable, is outside the scope of this specification. Implementors of PPS sources SHOULD document these assignments. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 5] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 The API supports the direct provision of PPS events (and timestamps) to a kernel function known as ``hardpps()'', as described in RFC1589 [4]. (although the API does not require the kernel implementation to use that symbol internally). The API optionally supports an ``echo'' feature, in which events on the incoming PPS signal may be reflected through software, after the capture of the corresponding timestamp, to an output signal pin. This feature may be used to determine an upper bound on the actual delay between the edges of the PPS signal and the capture of the timestamps; such information may be useful in precise calibration of the system. The designation of an output pin for the echo signal, and sense and shape of the output transition, is outside the scope of this specification, but SHOULD be documented for each implementation. The output pin MAY also undergo transitions at other times besides those caused by PPS input events. --------- Note: this allows an implementation of the echo feature to generate an output pulse per input pulse, or an output edge per input pulse, or an output pulse per input edge. It also allows the same signal pin to be used for several purposes simultaneously. --------- 3.2 New data structures The data structure declarations and symbol definitions for this API will appear in the header file . The API includes several implementation-specific types: typedef ... pps_handle_t; /* represents a PPS source */ typedef unsigned ... pps_seq_t; /* sequence number */ The ``pps_handle_t'' type is an opaque scalar type used to represent a PPS source within the API. The ``pps_seq_t'' type is an unsigned integer data type of at least 32 bits. The precise declaration of this type is system-dependent. The API imports the standard POSIX definition for this data type: typedef struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ } timespec_t; Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 6] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 The API defines this structure as an internal (not ``on the wire'') representation of the NTP ``64-bit unsigned fixed-point'' timestamp format [3]: typedef struct ntp_fp { unsigned int integral; unsigned int fractional; } ntp_fp_t; The two fields in this structure may be declared as any unsigned integral type, each of at least 32 bits. The API defines this new union as an extensible type for representing times: typedef union pps_timeu { timespec_t tspec; ntp_fp_t ntpfp; unsigned long longpair[2]; } pps_timeu_t; Future revisions of this specification may add more fields to this union. Section 3.4.2 describes how an application selects the appropriate representation for timestamps. --------- Note: adding a field to this union that is larger than 2*sizeof(long) will break binary compatibility. --------- The API defines these new data structures: typedef struct { pps_seq_t assert_sequence; /* assert event seq # */ pps_seq_t clear_sequence; /* clear event seq # */ pps_timeu_t assert_tu; pps_timeu_t clear_tu; int current_mode; /* current mode bits */ } pps_info_t; #define assert_timestamp assert_tu.tspec #define clear_timestamp clear_tu.tspec #define assert_timestamp_ntpfp assert_tu.ntpfp #define clear_timestamp_ntpfp clear_tu.ntpfp typedef struct { int mode; /* mode bits */ pps_timeu_t assert_off_tu; pps_timeu_t clear_off_tu; Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 7] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 } pps_params_t; #define assert_offset assert_off_tu.tspec #define clear_offset clear_off_tu.tspec #define assert_offset_ntpfp assert_off_tu.ntpfp #define clear_offset_ntpfp clear_off_tu.ntpfp The ``pps_info_t'' type is returned on an inquiry to PPS source. It contains the timestamps for the most recent assert event, and the most recent clear event. The order in which these events were actually received is defined by the timetamps, not by any other aspect of the specification. Each timestamp field represents the value of the operating system's internal timebase when the timestamped event occurred, or as close as possible to that time (perhaps with the addition of a specified offset). The current_mode field contains the value of the mode bits (see section 3.3) at time of the most recent transition for this PPS source. The assert_sequence number increases once per captured assert timestamp. Its initial value is undefined. If incremented past the largest unsigned long value, the next value is zero. The clear_sequence number increases once per captured clear timestamp. Its initial value is undefined, and may be different from the initial value of assert_sequence. If incremented past the largest unsigned long value, the next value is zero. --------- Note that these sequence numbers are most useful in applications where events other than PPS transitions are to be captured, which might be involved in a precision stopwatch application, for example. In such cases, the sequence numbers may be used to detect overruns, where the application has missed one or more events. They may also be used to detect an excessive event rate, or to detect that an event has failed to occur between two calls to the time_pps_fetch() function (defined later). In order to obtain an uninterrupted series of sequence numbers (and hence of event timestamps), it may be necessary to sample the pps_info_t values at a rate somewhat faster than the underlying event rate. For example, an application interested in both assert and clear timestamps may need to sample at least twice per second. Proper use of the sequence numbers allows an application to discover if it has missed any event timestamps due to an insufficient sampling rate. --------- As an OPTIONAL feature of the API, the implementation MAY support adding offsets to the timestamps that are captured. (Values of type ``struct timespec'' can represent negative offsets.) The Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 8] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 assert_offset field of a pps_params_t value specifies a value to be added to generate a captured assert_timestamp. The clear_offset of a pps_params_t value field specifies a value to be added to generate a captured clear_timestamp. 3.3 Mode bit definitions A set of mode bits is associated with each PPS source. The meaning of the bits in the mode field of the pps_params_t type are: #define PPS_CAPTUREASSERT 0x01 #define PPS_CAPTURECLEAR 0x02 #define PPS_CAPTUREBOTH 0x03 #define PPS_OFFSETASSERT 0x10 #define PPS_OFFSETCLEAR 0x20 #define PPS_HARDPPSONASSERT 0x04 #define PPS_HARDPPSONCLEAR 0x08 #define PPS_ECHOASSERT 0x40 #define PPS_ECHOCLEAR 0x80 #define PPS_CANWAIT 0x100 whose meanings are: PPS_CAPTUREASSERT If this bit is set, the assert timestamp for the associated PPS source will be captured. PPS_CAPTURECLEAR If this bit is set, the clear timestamp for the associated PPS source will be captured. PPS_CAPTUREBOTH Defined as the union of PPS_CAPTUREASSERT and PPS_CAPTURECLEAR, for convenience. PPS_OFFSETASSERT If set, the assert_offset value is added to the current value of the operating system's internal timebase in order to generate the captured assert_timestamp. Has no meaning if the PPS_CAPTUREASSERT mode bit is clear. PPS_OFFSETCLEAR If set, the clear_offset value is added to the current value of the operating system's internal timebase in order to generate the captured clear_timestamp. Has no meaning if the PPS_CAPTURECLEAR mode bit is clear. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 9] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 PPS_HARDPPSONASSERT If set, an assert event causes the assert timestamp to be communicated to the operating system module that disciplines the system's internal timebase. PPS_HARDPPSONCLEAR If set, a clear event causes the clear timestamp to be communicated to the operating system module that disciplines the system's internal timebase. PPS_ECHOASSERT If set, after the capture of an assert timestamp, the implementation generates a signal transition as rapidly as possible on an output signal pin. This MUST NOT affect the delay between the PPS source's transition to the asserted phase and the capture of the assert timestamp. PPS_ECHOCLEAR If set, after the capture of a clear timestamp, the implementation generates a signal transition as rapidly as possible on an output signal pin. This MUST NOT affect the delay between the PPS source's transition to the clear phase and the capture of the clear timestamp. PPS_CANWAIT If set, the time_pps_wait() function (see section 3.4.5) is available for use with this PPS source. Otherwise, the time_pps_wait() function is a no-op. Note: this mode bit cannot be set by an application; it can only be read. If neither PPS_CAPTUREASSERT nor PPS_CAPTURECLEAR is set, no valid timestamp will be available via the API. If neither PPS_HARDPPSONASSERT nor PPS_HARDPPSONCLEAR is set, no calls will be made to discipline the operating system's internal timebase. The interpretation of the PPS_HARDPPSONASSERT and PPS_HARDPPSONCLEAR bits is independent of the PPS_CAPTUREASSERT and PPS_CAPTURECLEAR bits. The operating system will enforce two restrictions on the use of the PPS_HARDPPSONASSERT and PPS_HARDPPSONCLEAR bits 1. They may be applied to at most one signal source at any given time. 2. They may only be set by a process with sufficient privileges to modify the system's internal timebase. (On UNIX systems, such modification is normally done using settimeofday() and/or adjtime(), and is restricted to users with superuser privilege.) The operating system may implement all of these mode bits, or just a subset of them. If an attempt is made to set an unsupported mode bit, the API will return an error. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 10] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 In addition, the following mode bits are defined in order to select an appropriate representation for timestamps and offsets: #define PPS_TSFMT_TSPEC 0x1000 #define PPS_TSFMT_NTPFP 0x2000 Exactly one of these bits MUST be set at any time. Their meanings are: PPS_TSFMT_TSPEC Timestamps and offsets are represented as values of type ``timespec_t''. All implementations MUST support this format, and this format is the default unless an application specifies otherwise. PPS_TSFMT_NTPFP Timestamps and offsets are represented as values of type ``ntp_fp_t'', which corresponds to the NTP ``64-bit unsigned fixed-point'' timestamp format [3]. Other such bits may be defined as fields are added to the ``pps_timeu_t'' union. Support for this format is OPTIONAL. 3.4 New functions In the description of functions that follows, we use the following function parameters: filedes A file descriptor (type: int), for a serial line or other source of PPS events. ppshandle A variable of type ``pps_handle_t'', as defined in section 3.2. ppsinfobuf A record of type ``pps_info_t'', as defined in section 3.2. ppsparams A record of type ``pps_params_t'', as defined in section 3.2. 3.4.1 New functions: obtaining PPS sources The API includes a functions to create and destroy PPS source ``handles''. SYNOPSIS int time_pps_create(int filedes, pps_handle_t *handle); int time_pps_destroy(pps_handle_t handle); Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 11] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 DESCRIPTION All of the other functions in the PPS API operate on PPS handles (type: pps_handle_t). The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle. The definition of what special files are appropriate for use with the PPS API is outside the scope of this specification, and may vary based on both operating system implementation, and local system configuration. One typical case is a serial line, whose DCD pin is connected to a source of PPS events. The time_pps_destroy() function makes the PPS handle unusable, and frees any storage that might have been allocated for it. It does not close the associated file descriptor, nor does it change any of the parameter settings for the PPS source. If, for example, the application wishes to disable the use of this PPS source for disciplining the system's internal timebase, it must do so using time_pps_setparams() before calling time_pps_destroy(). --------- Note: On operating systems that do not follow UNIX conventions for representing an accessible PPS source as an integer file descriptor, the time_pps_create() function may take different parameters from those shown here. --------- RETURN VALUES On successful completion, the time_pps_create() function returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error. If called with a valid handle parameter, the time_pps_destroy() function returns 0. Otherwise, it returns -1. ERRORS If the time_pps_create() function fails, errno may be set to one of the following values: [EBADF] The filedes parameter is not a valid file descriptor. [EOPNOTSUPP] The use of the PPS API is not supported for the file descriptor. [EPERM] The process's effective user ID does not have the required privileges to use the PPS API. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 12] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 3.4.2 New functions: setting PPS parameters The API includes several functions use to set or obtain the parameters of a PPS source. SYNOPSIS int time_pps_setparams(pps_handle_t handle, const pps_params_t *ppsparams); int time_pps_getparams(pps_handle_t handle, pps_params_t *ppsparams); int time_pps_getcap(pps_handle_t handle, int *mode); DESCRIPTION An application may use time_pps_setparams() to set the parameters (mode bits and timestamp offsets) for a PPS source. The pps_params_t type is defined in section 3.2; mode bits are defined in section 3.3. An application may use time_pps_getparams() to discover the current settings of the PPS parameters. An application that needs to change only a subset of the existing parameters must first call time_pps_getparams() to obtain the current parameter values, then set the new values using time_pps_setparams(). If an application changes the timestamp format by setting one of the corresponding mode bits (e.g., PPS_TSFMT_TSPEC) using time_pps_setparams(), and the format is supported by the implementation, the offset fields in the ppsparams argument are interpreted using that representation. Also, all subsequent values of type ``pps_info_t'' returned for the corresponding handle use that representation. If the requested timestamp format is not supported, the time_pps_setparams() function has no effect and returns an error value. An application wishing to discover which mode bits it may set, with its current effective user ID, may call time_pps_getcap(). This function returns the set of mode bits that may be set by the application, without generating an EINVAL or EPERM error, for the specified PPS source handle. It does not return the current values for the mode bits. Note that time_pps_getcap() may return several mode bits corresponding to timestamp formats, even though exactly one such mode bit may be enabled at any given time. The mode bits returned by time_pps_getcap() for distinct PPS handles may differ, reflecting the specific capabilities of the underlying hardware connection to the PPS source, or of the source itself. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 13] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 RETURN VALUES On successful completion, the time_pps_setparams(), time_pps_getparams(), and time_pps_getcap() functions return 0. Otherwise, a value of -1 is returned and errno is set to indicate the error. ERRORS If the time_pps_setparams(), time_pps_getparams(), or time_pps_getcap() function fails, errno may be set to one of the following values: [EBADF] The handle parameter is not associated with a valid file descriptor. [EFAULT] A parameter points to an invalid address. [EOPNOTSUPP] The use of the PPS API is not supported for the associated file descriptor. [EINVAL] The operating system does not support all of the requested mode bits. [EPERM] The process's effective user ID does not have the required privileges to use the PPS API, or to set the given mode bits. 3.4.3 New functions: access to PPS timestamps The API includes one function that gives applications access to PPS timestamps. SYNOPSIS int time_pps_fetch(pps_handle_t handle, pps_info_t *ppsinfobuf); DESCRIPTION An application may use time_pps_fetch() to obtain the most recent timestamps captured for the PPS source specified by the handle parameter. The result is stored in the ppsinfobuf parameter, whose fields are defined in section 3.2. If this function is invoked before the system has captured a timestamp for the signal source, the ppsinfobuf returned will have Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 14] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 its timestamp fields set to the POSIX base date (i.e., both the tv_sec and tv_nsec fields will be zero). RETURN VALUES On successful completion, the time_pps_fetch() function returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error. ERRORS If the time_pps_fetch() function fails, errno may be set to one of the following values: [EBADF] The handle parameter is not associated with a valid file descriptor. [EFAULT] A parameter points to an invalid address. [EOPNOTSUPP] The use of the PPS API is not supported for the associated file descriptor. 3.4.4 New functions: disciplining the kernel timebase The API does not include an explicit function for configuring the use of a PPS signal to discipline the operating system timebase. This is done using time_pps_setparams() and time_pps_getparams(). --------- Warning: If this feature is configured for a PPS source that does not have an accurate 1-pulse-per-second signal, or is otherwise inappropriately configured, use of this feature may result in seriously incorrect timekeeping for the entire system. For best results, the 1-PPS signal should have much better frequency stability than the system's internal clock source (usually a crystal-controlled oscillator), and should have jitter (variation in interarrival time) much less than the system's clock-tick interval. --------- See RFC1589 [4] for more information about how the system's timebase is disciplined using a PPS signal. 3.4.5 New functions: waiting for an event The API includes a function that allows an application to block until the next timestamp is captured. (It does not directly support the use of the select() system call to wait for PPS events.) This is an OPTIONAL feature of the API, and may be implemented as a stub that always returns zero. An application can determine whether Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 15] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 the feature is implemented by using time_pps_getcap() to see if the PPS_CANWAIT mode bit is set. SYNOPSIS int time_pps_wait(pps_handle_t handle, const struct timespec *timeout, pps_info_t *ppsinfobuf); DESCRIPTION This function blocks until either a timestamp is captured from the PPS source, or until the specified timeout duration has expired. If the timeout parameter is a NULL pointer, the function simply blocks until a timestamp is captured. If the timeout parameter specifies a delay of zero, this function is effectively identical to time_pps_fetch(). If the function returns as the result of a timeout or error, the contents of the ppsinfobuf are undefined. If the function returns because a timestamp has been captured, the contents of the ppsinfobuf are exactly as would have been returned by the time_pps_fetch() function, had it been called immediately after the timestamp was captured. If the PPS_CANWAIT mode bit is clear, then this function is a no-op, and always returns 0. RETURN VALUES On successful completion, the time_pps_wait() function returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error. ERRORS If the time_pps_wait() function fails, errno may be set to one of the following values: [EBADF] The handle parameter is not associated with a valid file descriptor. [EFAULT] A parameter points to an invalid address. [EOPNOTSUPP] The use of the PPS API is not supported for the associated file descriptor, or this OPTIONAL function is not supported. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 16] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 [ETIMEDOUT] The timeout duration has expired. [EINTR] A signal was delivered before the time limit specified by the timeout parameter expired and before a timestamp has been captured. 3.5 Compliance rules The key words "MUST", "MUST NOT", "REQUIRED","SHOULD", SHOULD NOT", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC2119 [1]. Some features of this specification are OPTIONAL, but others are REQUIRED. 3.5.1 Functions An implementation MUST provide these functions: - time_pps_create() - time_pps_destroy() - time_pps_setparams() - time_pps_getparams() - time_pps_getcap() - time_pps_fetch() An implementation MUST provide these functions, but they may be implementation as ``no-operation'' functions, possibly on a per-source basis: - time_pps_wait() 3.5.2 Mode bits An implementation MUST support at least one of these mode bits for each PPS source: - PPS_CAPTUREASSERT - PPS_CAPTURECLEAR and MAY support both of them. If an implementation supports both of these bits for a PPS source, it MUST allow them to be set simultaneously. An implementation MUST support these mode bits: - PPS_TSFMT_TSPEC An implementation MAY support these mode bits: - PPS_HARDPPSONASSERT - PPS_HARDPPSONCLEAR - PPS_ECHO - PPS_ECHOINVERT - PPS_OFFSETASSERT - PPS_OFFSETCLEAR - PPS_TSFMT_NTPFP An implementation that supports PPS_HARDPPSONASSERT for a PPS source MUST support PPS_OFFSETASSERT for that PPS source. An implementation Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 17] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 that supports PPS_HARDPPSONCLEAR for a PPS source MUST support PPS_OFFSETCLEAR for that PPS source. 3.6 Examples A very simple use of this API might be: int fd; pps_handle_t handle; pps_params_t params; pps_info_t infobuf; /* Open a file descriptor and enable PPS on rising edges */ fd = open(PPSfilename, O_RDONLY, 0); time_pps_create(fd, &handle); params.mode = PPS_CAPTUREASSERT; time_pps_setparams(handle, ¶ms); /* 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); } Note that this example omits all of the error-checking that would be expected in a reliable program. Also note that, on a system that supports time_pps_wait(), the function of these lines: sleep(1); time_pps_fetch(handle, &infobuf); might be more reliably accomplished using: timeout.tv_sec = 100; timeout.tv_nsec = 0; time_pps_wait(handle, &timeout, &infobuf); The (arbitrary) timeout value is used to protect against the possibility that another application might disable PPS timestamps, or that the hardware generating the timestamps might fail. A slightly more elaborate use of this API might be: int fd; pps_handle_t handle; Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 18] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 pps_params_t params; pps_info_t infobuf; int avail_mode; /* Open a file descriptor and enable PPS on rising edges */ fd = open(PPSfilename, O_RDONLY, 0); time_pps_create(fd, &handle); /* * Find out what features are supported */ time_pps_getcap(handle, &avail_mode); if ((avail_mode & PPS_CAPTUREASSERT) == 0) { fprintf(stderr, "%s cannot CAPTUREASSERT\n", PPSfilename); exit(1); } /* * Capture assert timestamps, and * compensate for a 675 nsec propagation delay */ params.assert_offset.tv_sec = 0; params.assert_offset.tv_nsec = 675; params.mode = PPS_CAPTUREASSERT | PPS_OFFSETASSERT; time_pps_setparams(handle, ¶ms); /* loop, printing the most recent timestamp every second or so */ while (1) { if (avail_mode & PPS_CANWAIT) { time_pps_wait(handle, NULL, &infobuf); } else { 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); } Again, most of the necessary error-checking has been omitted from this example. 4 Security Considerations This API gives applications three capabilities: - Causing the system to capture timestamps on certain events. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 19] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 - Obtaining timestamps for certain events. - Affecting the system's internal timebase. The first capability should not affect security directly, but might cause a slight increase in interrupt latency and interrupt-handling overhead. The second capability might be useful in implementing certain kinds of covert communication channels. In most cases, neither of these first two issues is a significant security threat, because the traditional UNIX file protection facility may be used to to limit access to the relevant special files. Provision of the PPS API adds minimal additional risk. The final capability is reserved to highly privileged users. In UNIX systems, this means those with superuser privilege. Such users can evade protections based on file permissions; however, such users can in general cause unbounded havoc, and can set the internal timebase (and its rate of change), so this API creates no new vulnerabilities. 5 Acknowledgements The API in this document draws some of its inspiration from the LBL ``ppsclock'' distribution [2], originally implemented in 1993 by Steve McCanne, Craig Leres, and Van Jacobson. We also thank Craig Leres and Judah Levine for helpful comments they contributed during the drafting of this document. 6 References 1. Scott Bradner. Key words for use in RFCs to Indicate Requirement Levels. RFC 2119, Harvard University, March, 1997. 2. Steve McCanne, Craig Leres, and Van Jacobson. PPSCLOCK. ftp://ftp.ee.lbl.gov/ppsclock.tar.Z. 3. David L. Mills. Network Time Protocol (Version 3): Specification, Implementation and Analysis. RFC 1305, IETF, March, 1992. 4. David L. Mills. A Kernel Model for Precision Timekeeping. RFC 1589, IETF, March, 1994. 5. The Open Group. The Single UNIX Specification, Version 2 - 6 Vol Set for UNIX 98. Document number T912, The Open Group, February, 1997. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 20] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 7 Authors' addresses Jeffrey C. Mogul Western Research Laboratory Digital Equipment Corporation 250 University Avenue Palo Alto, California, 94305, U.S.A. Email: mogul@wrl.dec.com Phone: 1 650 617 3304 (email preferred) David L. Mills Electrical Engineering Department University of Delaware Newark, DE 19716 Phone: (302) 831-8247 EMail: mills@udel.edu Jan Brittenson Sun Microsystems, Inc. 901 San Antonio Rd M/S MPK17-202 Palo Alto, CA 94303 Email: Jan.Brittenson@Eng.Sun.COM Jonathan Stone Stanford Distributed Systems Group Stanford, CA 94305 Phone: (650) 723-2513 Email: jonathan@dsg.stanford.edu Poul-Henning Kamp The FreeBSD Project Valbygaardsvej 8 DK-4200 Slagelse Denmark Phone: +45 58 56 10 59 Email: phk@FreeBSD.org Ulrich Windl Universitaet Regensburg, Klinikum Email: ulrich.windl@rz.uni-regensburg.de A. Extensions Related APIs The API specified in the main body of this document could be more useful with the provision of several extensions or companion APIs. At present, the interfaces listed in this appendix are not part of the formal specification in this document. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 21] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 A.1 Extension: Parameters for the ``echo'' mechanism The ``echo'' mechanism described in the body of this specification leaves most of the details to the implementor, especially the designation of one or more output pins. It might be useful to extend this API to provide either or both of these features: - A means by which the application can discover which output pin is echoing the input pin. - A means by which the application can select which output pin is echoing the input pin. A.2 Extension: Obtaining information about external clocks The PPS API may be useful with a wide variety of reference clocks, connected via several different interface technologies (including serial lines, parallel interfaces, and bus-level interfaces). These reference clocks can have many features and parameters, some of which might not even have been invented yet. We believe that it would be useful to have a mechanism by which an application can discover arbitrary features and parameters of a reference clock. These might include: - Clock manufacturer, model number, and revision level - Whether the clock is synchronized to an absolute standard - For synchronized clocks, * The specific standard * The accuracy of the standard * The path used (direct connection, shortwave, longwave, satellite, etc.) * The distance (offset) and variability of this path - For PPS sources, * The pulse rate * The pulse shape * Which edge of the pulse corresponds to the epoch - The time representation format This information might best be provided by an API analogous to the standard ``curses'' API, with a database analogous to the standard ``terminfo'' database. That is, a ``clockinfo'' database would contain a set of (attribute, value) pairs for each type of clock, and the API would provide a means to query this database. Additional mechanisms would allow an application to discover the clock or clocks connected to the local system, and to discover the clockinfo type of a specific clock device. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 22] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 A.3 Extension: Finding a PPS source Although the clockinfo database described in section A.2, together with the discover mechanisms described there, would allow an application to discover the PPS source (or sources) connected to a system, it might be more complex than necessary. A simpler approach would be to support a single function that provides the identity of one or more PPS sources. For example, the function might be declared as int time_pps_findsource(int index, char *path, int pathlen, char *idstring, int idlen); The index argument implicitly sets up an ordering on the PPS sources attached to the system. An application would use this function to inquire about the Nth source. The function would return -1 if no such source exists; otherwise, it would return 0, and would place the pathname of the associated special file in the path argument. It would also place an identification string in the idstring argument. The identification string could include the clock make, model, version, etc., which could then be used by the application to control its behavior. This function might simply read the Nth line from a simple database, containing lines such as: /dev/tty00 "TrueTime 468-DC" /dev/pps1 "Homebrew rubidium frequency standard" allowing the system administrator to describe the configuration of PPS sources. B. Example implementation: PPSDISC Line discipline One possible implementation of the PPS API might be to define a new ``line discipline'' and then map the API onto a set of ioctl() commands. Here we sketch such an implementation; note that this is not part of the specification of the API, and applications should not expect this low-level interface to be available. In this approach, the set of line disciplines is augmented with one new line discipline, PPSDISC. This discipline will act exactly the same as the TTYDISC discipline, except for its handling of modem DCD interrupts. Once the TIOCSETD ioctl() has been used to select this line discipline, PPS-related operations on the serial line may be invoked Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 23] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 using new ioctl() commands. For example (values used only for illustration): #define PPSFETCH _IOR('t', 75, pps_info_t) #define PPSSETPARAM _IOW('t', 76, pps_params_t) #define PPSGETPARAM _IOR('t', 77, pps_params_t) #define PPSGETCAP _IOR('t', 78, int) B.1 Example A typical use might be: int ldisc = PPSDISC; pps_params_t params; pps_info_t infobuf; ioctl(fd, TIOCSETD, &ldisc); /* set discipline */ /* * Check the capabilities of this PPS source to see * if it supports what we need. */ ioctl(fd, PPSGETCAP, ¶ms); if ((params.mode & PPS_CAPTUREASSERT) == 0 || (params.mode & PPS_HARDPPSONASSERT) == 0) { fprintf(stderr, "PPS source is not suitable\n"); exit(1); } /* * Set this line to timestamp on a rising-edge interrupt, * and assign this line for the kernel hardpps() input */ params.mode = PPS_CAPTUREASSERT | PPS_HARDPPSONASSERT; ioctl(fd, PPSSETPARAMS, ¶ms); sleep(2); /* allow time for the PPS pulse to happen */ /* obtain most recent timestamp and sequence # for this line */ ioctl(fd, PPSFETCH, &infobuf); Again, this example imprudently omits any error-checking. C. Available implementations This appendix lists known publicly-available implementations of the API described in this document. Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 24] Internet-Draft Pulse-Per-Second API 10 June 1998 13:46 C.1 FreeBSD A prototype implementation for FreeBSD, using the parallel printer port as interface is available in FreeBSD-current. The relevant source files are: src/include/timepps.h src/sys/sys/timepps.h src/sys/dev/ppbus/pps.c A higher performance implementation, using dedicated FPGA based hardware has also been made, but not yet included in the FreeBSD sources. Information valid as of: 9 June 1998 URL: http://www.freebsd.org Contact: Poul-Henning Kamp, phk@FreeBSD.org C.2 NetBSD A prototype implementation for NetBSD, using the "com" serial driver for NS8250, NS16450, and NS16650 UARTS is available in NetBSD-current. The relevant source files are: src/sys/sys/timepps.h src/sys/dev/ic/com.c src/sys/dev/ic/comvar.h Information valid as of: 10 June 1998 URL: http://www.NetBSD.ORG Contact: Jonathan Stone, jonathan@NetBSD.ORG Mogul, Mills, Brittenson, Stone, Kamp, Windl [Page 25]