RFC 2783
Pulse-Per-Second API for UNIX-like Operating Systems, Version 1.0
RFC 2783: Pulse-Per-Second API for UNIX-like Operating Systems, Version 1.0 โจ
Okay bestie, this is RFC 2783, and it's giving precise-timing realness ๐ฐ๏ธ๐ฅ. It's an Informational doc from the Network Working Group, dated March 2000. The authors are J. Mogul (Compaq WRL), D. Mills (University of Delaware), J. Brittenson (Sun), J. Stone (Stanford), and U. Windl (Universitaet Regensburg). The title block doesn't list anything it obsoletes or updates, so it's standing completely on its own ๐
Status of This Memo ๐
This memo provides information for the Internet community. It does not specify an Internet standard of any kind. Distribution of this memo is unlimited.
Copyright Notice ๐
Copyright (C) The Internet Society (2000). All Rights Reserved.
Abstract ๐ง
RFC 1589 describes a UNIX kernel implementation model for high-precision time-keeping ๐ธ. The model is meant to work alongside the Network Time Protocol (NTP, RFC 1305) or similar time synchronization protocols. One piece of it is an accurate interface to the high-accuracy, one pulse-per-second (PPS) output that precise time sources (like a GPS or GOES receiver) usually have. RFC 1589 never defined an API for managing the PPS facility, so implementors had no portable way to use PPS sources ๐ญ. This document is the one that fills that gap โจ.
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.............................................. 6
3.2 New data structures.......................................... 7
3.3 Mode bit definitions......................................... 10
3.4 New functions................................................ 12
3.4.1 New functions: obtaining PPS sources....................... 13
3.4.2 New functions: setting PPS parameters...................... 14
3.4.3 New functions: access to PPS timestamps.................... 16
3.4.4 New functions: disciplining the kernel timebase............ 18
3.5 Compliance rules............................................. 20
3.5.1 Functions.................................................. 20
3.5.2 Mode bits.................................................. 20
3.6 Examples..................................................... 21
4 Security Considerations........................................ 24
5 Acknowledgements............................................... 24
6 References..................................................... 25
7 Authors' Addresses............................................. 26
A. Extensions and related APIs................................... 27
A.1 Extension: Parameters for the "echo" mechanism............... 27
A.2 Extension: Obtaining information about external clocks....... 27
A.3 Extension: Finding a PPS source.............................. 28
B. Example implementation: PPSDISC Line discipline............... 29
B.1 Example...................................................... 29
C. Available implementations..................................... 30
Full Copyright Statement......................................... 31
1 Introduction ๐ฆ
Okay so RFC 1589 [4] is the model and programming interface for generic OS software that manages the system clock and timer functions ๐ฐ๏ธ. It gives improved accuracy and stability to most workstations and servers running the Network Time Protocol (NTP) [3] or a similar time sync protocol. It also supports external timing sources, like the precision pulse-per-second (PPS) signals that precise time sources (such as a GPS or GOES receiver) usually provide ๐ฐ๏ธ.
BUT, RFC 1589 never defined an application programming interface (API) for the PPS facility ๐ค. This document is the one that specifies that interface, for use with UNIX (or UNIX-like) operating systems. Those systems often conform to the "Single UNIX Specification" [5], sometimes known as POSIX ๐ .
One convenient way to get a PPS signal into a computer is to wire it to a modem-control pin on a serial-line interface. The Data Carrier Detect (DCD) pin is a popular choice for this ๐. The time source's time-code output usually gets sent to the computer over that same serial line. The computer spots a signal transition on the DCD pin, usually by catching an interrupt, and records a timestamp as soon as possible โฑ๏ธ.
Existing practice has mostly focussed on serial lines and DCD transitions, but PPS signals could also come through other kinds of devices ๐. The API in this document does not require a serial line, although it may be a little biased in that direction ๐.
The typical use of this facility is for the OS to record ("capture") a high-resolution timestamp as soon as possible after it detects a PPS signal transition (usually flagged by an interrupt) โก. That timestamp can then be handed off, with less strict delay constraints, to time-related software ๐. The software can compare the captured timestamp to the received time-code and accurately work out the offset between the system clock and the precise time source ๐งฎ.
The OS may also deliver the PPS event to a kernel procedure, called the "in-kernel PPS consumer." One example is the "hardpps()" procedure from RFC 1589, which is used to discipline the kernel's internal timebase ๐.
The API in this document lets one or more signal sources attached to a computer provide PPS inputs, if user-level software wants them ๐ซถ. User-level software can get signal-transition timestamps for any of these PPS sources. It can also optionally pick at most one of these PPS sources to discipline the system's internal timebase ๐.
The main purpose of this API is capturing true pulse-per-second events, but it can also timestamp events with other periods, or even aperiodic events, as long as they can be expressed as signal transitions โจ.
This document does not define the internal details of how the API must be implemented, and it doesn't set constraints on the accuracy, resolution, or latency of the PPS feature ๐. Still, the usefulness of this feature is inversely proportional to the delay (and the variance of that delay), so implementors are encouraged to take this seriously ๐ฅ.
In principle, the rate of events to be captured, or the frequency of the signals, can range from once per day (or less often) up to several thousand per second ๐. Since most implementations will do the timestamping as a processor interrupt at a fairly high priority, it's prudent to limit the rate of these events ๐ฆ. That can 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 all sorts of time representations. This API is all about high-accuracy, high-resolution time information, so the choice of representation really matters ๐ค. (Here we only consider binary representations, not human-format ones.)
There are two big questions:
- what is the resolution of the representation?
- what time scale is represented?
These questions tend to start contentious arguments ๐. Since this API is meant for NTP and POSIX-compliant systems, though, we can narrow the choices to representations that fit existing NTP and POSIX practice, even if some folks think that practice is "wrong" ๐คทโโ๏ธ.
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] ๐คฏ.
Okay but most computer systems can't measure time to that resolution (it would take 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 it defaults to the "struct timespec" representation ๐.
2.2 Time scale ๐๏ธ
Several different time scales have been proposed for computer systems, and UTC and TAI are the two obvious candidates ๐.
Some people prefer TAI, which is identical to UTC except that it does not correct for leap seconds. Their preference comes from how hard it is to compute precise time differences when leap seconds are involved, especially for times in the future (where the exact number of leap seconds is, in general, unknowable) ๐ฅบ.
BUT POSIX and NTP both use UTC, albeit with different base dates ๐โโ๏ธ. Since supporting TAI would, in general, require other changes to the POSIX specification, this API uses the POSIX base date of 00:00 January 1, 1970 UTC, and conforms to the POSIX use of the UTC time scale ๐ซถ.
3 API ๐งโโ๏ธ
A PPS facility can be used in two different ways:
- An application can obtain a timestamp, using the system's internal timebase, for the most recent PPS event.
- The 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 can be used on any number of PPS sources at the same time, while the timebase-disciplining feature can be used with at most one PPS source ๐ฅ.
Even though the proper implementation of this API needs support from the kernel of a UNIX system, this document defines the API in terms of a set of library routines. That gives the implementor some freedom to split the work between kernel code and library code (different divisions might suit microkernels and monolithic kernels, for example) ๐.
3.1. PPS abstraction ๐ธ
okay so a PPS signal is basically a series of pulses ๐ Each pulse has an "asserted" (logical true) phase and a "clear" (logical false) phase, and the two phases can be different lengths ๐ฆ The API may capture an "assert timestamp" the moment the signal transitions into the asserted phase, and a "clear timestamp" the moment it transitions into the clear phase โฑ๏ธ
Now, which actual voltages count as "true" and "false" is NOT this spec's job ๐ โโ๏ธ (if it even applies to you). BUT these assignments SHOULD be consistent with applicable standards, and PPS source implementors SHOULD document what they picked ๐
Reminder to implementors of DCD-based PPS support: TTL and RS-232C (V.24/V.28) interfaces both define the "true" state as the one having the highest positive voltage. TTL defines a nominal absence of voltage as the "false" state, but RS-232C (V.24/V.28) defines the "false" state by the presence of a negative voltage.
The API supports handing PPS events (and their timestamps) directly to an in-kernel PPS consumer ๐ง This could be the function called "hardpps()", as described in RFC 1589 [4], but the API doesn't require the kernel to use that name internally โจ The current version supports at most one in-kernel PPS consumer, and there's no way to explicitly name it ๐ซถ The implementation SHOULD impose access controls on the use of this feature ๐
The API optionally supports an "echo" feature ๐ฆ Here, events on the incoming PPS signal may be reflected through software, after the matching timestamp is captured, out to an output signal pin. This feature may be used to find an upper bound on the actual delay between the edges of the PPS signal and the capture of the timestamps, and that info can be super useful for precise calibration of the system ๐
The designation of an output pin for the echo signal, plus the sense and shape of the output transition, is outside the scope of this specification ๐ but it 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.
Also, the API optionally gives an application the ability to specify an offset value to be applied to captured timestamps ๐ This can correct for cable and/or radio-wave propagation delays, or compensate for systematic jitter in the external signal ๐ง The implementation SHOULD impose access controls on the use of this feature ๐
3.2. New data structures ๐
The data structure declarations and symbol definitions for this API live in the header file <sys/timepps.h> ๐ The header file MUST define all constants described in this specification, even if the implementation doesn't support them ๐
The API includes a few implementation-specific types ๐ฅ
typedef ... pps_handle_t; /* represents a PPS source */
typedef unsigned ... pps_seq_t; /* sequence number */
pps_handle_t is an opaque scalar type that represents a PPS source within the API ๐ฆ pps_seq_t is an unsigned integer data type of at least 32 bits โจ The precise declarations of both types are system-dependent ๐ธ
The API imports the standard POSIX definition for this data type ๐
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
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 {
struct timespec tspec;
ntp_fp_t ntpfp;
unsigned long longpad[3];
} pps_timeu_t;
Future revisions of this specification may add more fields to this union ๐ฎ
Note: adding a field to this union that is larger than 3*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 api_version; /* API version # */
int mode; /* mode bits */
pps_timeu_t assert_off_tu;
pps_timeu_t clear_off_tu;
} 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 when you inquire about a PPS source ๐ It holds the timestamps for the most recent assert event and the most recent clear event ๐ซถ The order in which those events were actually received is defined by the timestamps, not by any other aspect of the specification โฐ Each timestamp field is the value of the operating system's internal timebase when the timestamped event occurred, or as close to that time as possible (with the optional addition of a specified offset) ๐ท The current_mode field holds the value of the mode bits (see section 3.3) at the time the most recent transition was captured for this PPS source ๐ฏ An application can use current_mode to figure out the format of the timestamps returned ๐
The assert_sequence number increases once per captured assert timestamp ๐ Its initial value is undefined. If it gets incremented past the largest value for the type, 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 it gets incremented past the largest value for the type, the next value is zero ๐ Because of possible signal loss or excessive signal noise, the assert and clear sequence numbers might not always increase in step with each other ๐
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).
To get an uninterrupted series of sequence numbers (and therefore 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 lets an application discover whether it has missed any event timestamps because its sampling rate wasn't high enough ๐ต๏ธโโ๏ธ
The pps_params_t data type is used to discover and modify the parameters of a PPS source ๐ ๏ธ It includes a mode field, described in section 3.3 ๐ It also includes an api_version field, which is a read-only value giving the version of the API ๐ Currently, the only defined value is:
#define PPS_API_VERS_1 1
This field exists to enable binary compatibility with future versions of the API ๐
Note: the term "read-only" in this specification means that an application cannot modify the relevant data item; only the implementation can modify the value. The implementation MUST ignore attempts by the application to modify a read-only field.
As an OPTIONAL feature of the API, the implementation MAY support adding offsets to the timestamps that get captured ๐ง (Values of type "struct timespec" can represent negative offsets, bestie ๐) The assert_offset field of a pps_params_t value specifies a value to be added to generate a captured assert_timestamp. The clear_offset field of a pps_params_t value specifies a value to be added to generate a captured clear_timestamp ๐ Since any offsets apply to all users of a given PPS source, the implementation SHOULD impose access controls on the use of this feature ๐ for example, by allowing only the super-user to set the offset values ๐ The default value for both offsets is zero ๐ซง
3.3 Mode bit definitions โจ
okay so every PPS source comes with its own set of mode bits ๐ซถ Here's the full lineup in the pps_params_t mode field:
/* Device/implementation parameters */
#define PPS_CAPTUREASSERT 0x01
#define PPS_CAPTURECLEAR 0x02
#define PPS_CAPTUREBOTH 0x03
#define PPS_OFFSETASSERT 0x10
#define PPS_OFFSETCLEAR 0x20
#define PPS_CANWAIT 0x100
#define PPS_CANPOLL 0x200
/* Kernel actions */
#define PPS_ECHOASSERT 0x40
#define PPS_ECHOCLEAR 0x80
/* Timestamp formats */
#define PPS_TSFMT_TSPEC 0x1000
#define PPS_TSFMT_NTPFP 0x2000
These bits sort into three categories, and the category decides who gets to touch them ๐
- Device/implementation parameters. These describe the device or the implementation itself. If the implementation lets them change, they're read/write for users with enough privilege (like the super-user) and read-only for everyone else. If the implementation doesn't allow changes, they're just read-only, period.
- Kernel actions. These tell the kernel what to do when a signal arrives. If the implementation supports an action, its bit is read/write for privileged users and read-only for the rest. If the implementation doesn't support the action, that bit is always zero ๐
- Timestamp formats. These show which timestamp formats the device offers. They're always read-only, no exceptions ๐
Now let's go through the Device/implementation parameter bits one by one, because they're lowkey the most fun ๐ธ
PPS_CAPTUREASSERT : If this bit is set, the assert timestamp for the associated PPS source gets captured.
PPS_CAPTURECLEAR : If this bit is set, the clear timestamp for the associated PPS source gets captured.
PPS_CAPTUREBOTH : This one is the union of PPS_CAPTUREASSERT and PPS_CAPTURECLEAR, defined purely for convenience. It's giving combo meal ๐
PPS_OFFSETASSERT : If set, the assert_offset value gets added to the current value of the operating system's internal timebase, and that's how the captured assert_timestamp gets made โจ
PPS_OFFSETCLEAR : If set, the clear_offset value gets added to the current value of the operating system's internal timebase, and that's how the captured clear_timestamp gets made ๐
PPS_CANWAIT : If set, the application can ask that the time_pps_fetch() function (see section 3.4.3) blocks until the next timestamp shows up. Heads up: this mode bit is read-only ๐
PPS_CANPOLL : This bit is reserved for future use. An application SHOULD NOT depend on any functionality implied either by its presence or by its absence. Basically, don't build anything around it, bestie ๐
โโ๏ธ
If neither PPS_CAPTUREASSERT nor PPS_CAPTURECLEAR is set, then no valid timestamp will be available through the API. No capture bit, no timestamp. Simple as that ๐
Next up are the Kernel action bits, which are where things get a little more dramatic ๐ฅ
PPS_ECHOASSERT : If set, after the assert timestamp is captured, 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. Translation: the echo can't mess with the timing ๐ค
PPS_ECHOCLEAR : If set, after the clear timestamp is captured, 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. Same rule, other phase, zero exceptions ๐
โโ๏ธ
And finally, the timestamp formats, which are the bits that tell you how the data is packaged ๐
PPS_TSFMT_TSPEC : Timestamps and offsets are represented as values of type "struct timespec". All implementations MUST support this format, and it's the default unless an application asks for something else. This one is non-negotiable, so every implementation has it ๐ซก
PPS_TSFMT_NTPFP : Timestamps and offsets are represented as values of type "ntp_fp_t", which matches the NTP "64-bit unsigned fixed-point" timestamp format [3]. Support for this format is OPTIONAL, so it's a nice-to-have, not a must-have ๐ฆ
Other timestamp format bits may be defined as fields get added to the "pps_timeu_t" union. So the list isn't closed. Keep your eyes peeled ๐
The operating system might implement all of these mode bits, or just a subset. If an application tries to set a mode bit the implementation doesn't support, the API returns an error. If an application tries to modify a read-only mode bit, the API also returns an error. No sneaking changes through ๐ซ
3.4 New functions ๐ง
Here's where we get into the actual functions. Before we dive in, let's name the parameters we'll keep seeing ๐
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.
tsformat : An integer with exactly one of the timestamp format bits set.
3.4.1 New functions: obtaining PPS sources ๐
This is where you get your PPS handles. The API has functions to create them and destroy them ๐ซถ
SYNOPSIS
int time_pps_create(int filedes, pps_handle_t *handle);
int time_pps_destroy(pps_handle_t handle);
DESCRIPTION
Pretty much every other function in the PPS API works on PPS handles (type: pps_handle_t), so this is the starting line ๐ The time_pps_create() function takes a UNIX file descriptor that's already open, for an appropriate special file, and turns it into a PPS handle.
What counts as an appropriate special file is outside the scope of this spec. It can depend on the operating system and the local system configuration. One typical case is a serial line whose DCD pin is hooked up to a PPS event source ๐
The mode the UNIX file descriptor was originally opened in affects which operations are allowed on the PPS handle. The time_pps_setparams() and time_pps_kcbind() functions (see sections 3.4.2 and 3.4.4) SHOULD be prohibited by the implementation if the descriptor is open only for reading (O_RDONLY).
Note: operations on a descriptor opened with an inappropriate mode might fail with EBADF.
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, and it doesn't change any of the parameter settings for the PPS source either. So destroy the handle, but the fd and the settings stay right where they are ๐ฆ
Note: If this API gets adapted to an operating system that doesn't follow UNIX conventions for representing an accessible PPS source as an integer file descriptor, the time_pps_create() function may take different parameters from the ones shown here.
RETURN VALUES
On successful completion, time_pps_create() returns 0. Otherwise it returns -1, and errno gets set to indicate the error.
If it's called with a valid handle parameter, time_pps_destroy() returns 0. Otherwise, it returns -1.
ERRORS
If time_pps_create() fails, errno might be set to one of these 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 doesn't have the privileges needed to use the PPS API.
3.4.2 New functions: setting PPS parameters โ๏ธ
okay bestie, this section is all about the functions that set and check 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 โจ
so a suitably privileged application can use time_pps_setparams() to set the parameters (mode bits and timestamp offsets) for a PPS source ๐ซถ the pps_params_t type is in section 3.2, and the mode bits are in section 3.3 ๐ an app can call time_pps_getparams() to see what the current settings are ๐ and if you only want to change some of the parameters, you have to call time_pps_getparams() first to grab the current values, and then use time_pps_setparams() to set the new ones. it's giving "read before you write" energy ๐๐
Note: a call to time_pps_setparams() replaces the current values of all mode bits with the ones in the ppsparams argument, except for bits whose state can't be changed ๐ bits might be read-only because of access controls, or because the implementation fixes them.
the timestamp format of the assert_offset and clear_offset fields is set by the mode field ๐ฆ so when you call time_pps_setparams(), the kernel reads the offset values using the timestamp format given in the mode field of the ppsparams argument. if the requested format isn't supported, time_pps_setparams() has no effect and returns an error value ๐ when you call time_pps_getparams(), the kernel tells you the format of the offsets by setting one of the timestamp format bits in the mode field ๐ง
Note: an app that uses time_pps_getparams() to read the current offset values can't pick which format is used ๐ญ the implementation SHOULD return the offsets in the same timestamp format that was used when the offsets were set. (it's the vibe, it's the consistency, we love to see it ๐)
an app that wants to find out which mode bits it's allowed to set (based on its current effective user ID) can call time_pps_getcap() ๐ this function returns the set of mode bits the app can set without getting an EINVAL or EPERM error, for the specified PPS source. it does not return the current values of the mode bits ๐
โโ๏ธ a call to time_pps_getcap() returns the mode bits for all supported timestamp formats ๐
the time_pps_getcap() function MAY ignore the mode the UNIX file descriptor was opened with ๐ค so the app might still get an EBADF error on a call to time_pps_setparams(), even when time_pps_getcap() said the chosen mode bits were allowed. not fair, but it's the spec ๐
the mode bits that time_pps_getcap() returns for different PPS handles can be different ๐ that's because they reflect the specific capabilities of the underlying hardware connection to the PPS source, or of the source itself โญ
RETURN VALUES ๐ฌ
on successful completion, time_pps_setparams(), time_pps_getparams(), and time_pps_getcap() all return 0 โ
otherwise, they return -1 and set errno to show what went wrong ๐ฅบ
ERRORS ๐จ
if time_pps_setparams(), time_pps_getparams(), or time_pps_getcap() fails, errno may be set to one of these values:
[EBADF] The handle parameter is not associated with a valid
file descriptor, or the descriptor is not open for
writing.
[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 has one function that lets apps get their hands on PPS timestamps โจ as an implementation option, the app can ask the API to block until the next timestamp gets captured ๐ซ (fyi, the API doesn't directly support using select() or poll() to wait for PPS events, so don't go looking for that ๐
โโ๏ธ)
SYNOPSIS ๐ธ
int time_pps_fetch(pps_handle_t handle,
const int tsformat,
pps_info_t *ppsinfobuf,
const struct timespec *timeout);
DESCRIPTION โจ
an app can use time_pps_fetch() to get the most recent timestamps captured for the PPS source named by the handle parameter ๐ the tsformat parameter sets the timestamp format you want. if that format isn't supported, the call fails and returns an error value ๐ the application MUST specify exactly one timestamp format, no more, no less ๐ฅ
this function blocks until either a timestamp gets captured from the PPS source, or the timeout duration you set has run out โฐ if the timeout parameter is a NULL pointer, the function just blocks until a timestamp is captured ๐ซถ if the timeout parameter says the delay is zero, the function returns immediately ๐โโ๏ธ๐จ
blocking behaviour is an implementation option ๐ if the PPS_CANWAIT mode bit is clear, and the timeout parameter is either NULL or points to a non-zero value, the function returns an EOPNOTSUPP error ๐ญ an app can check whether this feature is there by using time_pps_getcap() to see if the PPS_CANWAIT mode bit is set ๐
the result goes into the ppsinfobuf parameter, whose fields are defined in section 3.2 ๐ง if the function returns because of a timeout or an error, the contents of ppsinfobuf are undefined ๐
if this function gets called before the system has captured a timestamp for the signal source, the ppsinfobuf that comes back will have its timestamp fields set to the time format's base date ๐ผ (for example, with PPS_TSFMT_TSPEC, both the tv_sec and tv_nsec fields will be zero ๐ซง)
RETURN VALUES ๐ฌ
on successful completion, time_pps_fetch() returns 0 โ
otherwise, it returns -1 and sets errno to show the error ๐ฅน
ERRORS ๐จ
if time_pps_fetch() fails, errno may be set to one of these values:
[EBADF] The handle parameter is not associated with a valid
file descriptor.
[EFAULT] A parameter points to an invalid address.
[EINTR] A signal was delivered before the time limit
specified by the timeout parameter expired and before
a timestamp has been captured.
[EINVAL] The requested timestamp format is not supported.
[EOPNOTSUPP] The use of the PPS API is not supported for the
associated file descriptor.
[ETIMEDOUT] The timeout duration has expired.
3.4.4 New functions: disciplining the kernel timebase โฑ๏ธ๐
the API has one OPTIONAL function that says if and how a PPS source gets handed to a kernel consumer of PPS events ๐ think of the code that disciplines the operating system's internal timebase, that's the vibe ๐ง
SYNOPSIS ๐ธ
int time_pps_kcbind(pps_handle_t handle,
const int kernel_consumer,
const int edge,
const int tsformat);
DESCRIPTION โจ
an app with the right privileges can use time_pps_kcbind() to bind a kernel consumer to the PPS source named by the handle ๐ซถ
the kernel consumer is identified by the kernel_consumer parameter ๐ง in the current version of the API, the possible values for this parameter are:
#define PPS_KC_HARDPPS 0
#define PPS_KC_HARDPPS_PLL 1
#define PPS_KC_HARDPPS_FLL 2
and here's what they mean:
PPS_KC_HARDPPS: the kernel's hardpps() function (or equivalent) ๐PPS_KC_HARDPPS_PLL: a variant of hardpps() that's constrained to use a phase-locked loop ๐PPS_KC_HARDPPS_FLL: a variant of hardpps() that's constrained to use a frequency-locked loop ๐
implementing any or all of these values is OPTIONAL ๐ซ
the edge parameter says which edge of the PPS signal causes a timestamp to get delivered to the kernel consumer โก it can be PPS_CAPTUREASSERT, PPS_CAPTURECLEAR, or PPS_CAPTUREBOTH, depending on the particular characteristics of the PPS source ๐ฆ it can also be zero, which removes any binding between the PPS source and the kernel consumer ๐ซง
the tsformat parameter sets the format for the timestamps delivered to the kernel consumer ๐ if this value is zero, the implementation MAY choose the appropriate format, or return EINVAL ๐คทโโ๏ธ the implementation MAY also ignore a non-zero value for this parameter ๐
the binding made by this call sticks around until a later call changes it, using the same kernel_consumer ๐ in particular, a later call to time_pps_destroy() for the specified handle does not affect the binding ๐
the binding doesn't depend on any earlier or later changes to the PPS_CAPTUREASSERT and PPS_CAPTURECLEAR mode bits for the device โจ however, if either the edge or the tsformat parameter values don't match what the PPS source can do, an error is returned ๐ฌ the implementation MAY also return an error if the tsformat value isn't supported for time_pps_kcbind(), even if it is supported for other uses of the API ๐
the operating system may enforce two restrictions on the bindings made by time_pps_kcbind() ๐ก๏ธ
- the kernel MAY return an error if an attempt is made to bind a kernel consumer to more than one PPS source at a time.
- the kernel MAY restrict the ability to set bindings to processes with sufficient privileges to modify the system's internal timebase. (On UNIX systems, that modification is normally done using
settimeofday()and/oradjtime(), and it's restricted to users with superuser privilege ๐)
Warning: if this feature is configured for a PPS source that doesn't have an accurate 1-pulse-per-second signal, or is otherwise set up wrong, using it may result in seriously incorrect timekeeping for the entire system ๐๐จ for the 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 its jitter (the variation in interarrival time) should be much less than the system's clock-tick interval ๐ฅบ
see RFC 1589 [4] for more info about how the system's timebase can be disciplined using a PPS signal ๐๐
RETURN VALUES ๐ฌ
on successful completion, time_pps_kcbind() returns 0 โ
otherwise, it returns -1 and sets errno to show the error ๐ฅน
ERRORS ๐จ
if time_pps_kcbind() fails, errno may be set to one of these values:
[EBADF] The handle parameter is not associated with a valid
file descriptor, or the descriptor is not open for
writing.
[EFAULT] A parameter points to an invalid address.
[EINVAL] The requested timestamp format is not supported.
[EOPNOTSUPP] The use of the PPS API is not supported for the
associated file descriptor, or this OPTIONAL
function is not supported.
[EPERM] The process's effective user ID does not have the
required privileges to set the binding.
3.5. Compliance rules
okay so this is the part where we get serious, bestie ๐ซถ The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "MAY", and "OPTIONAL" in this document are to be read the way RFC 2119 [1] describes them. Some features of this spec are OPTIONAL, but others are REQUIRED, so pay attention to which is which ๐
3.5.1. Functions
okay so an implementation MUST provide all of these functions, no skipping ๐
time_pps_create()time_pps_destroy()time_pps_setparams()time_pps_getparams()time_pps_getcap()time_pps_fetch()
and then there's this one function that an implementation MUST also provide, but it's giving "lowkey optional in spirit" ๐ It may be implemented as a function that always return an EOPNOTSUPP error, possibly on a per-source basis:
time_pps_kcbind()
3.5.2. Mode bits
An implementation MUST support at least one of these mode bits for each PPS source, so you get your choice of assert or clear ๐ฆ
PPS_CAPTUREASSERTPPS_CAPTURECLEAR
and it MAY support both of them. If an implementation supports both of these bits for a PPS source, it SHOULD allow them to be set simultaneously. Main character energy when both work together ๐
An implementation MUST support this timestamp format:
PPS_TSFMT_TSPEC
An implementation MAY support these mode bits, which is a total bonus if you've got them โจ
PPS_ECHOASSERTPPS_ECHOCLEARPPS_OFFSETASSERTPPS_OFFSETCLEAR
An implementation MAY support this timestamp format too ๐ธ
PPS_TSFMT_NTPFP
3.6. Examples
okay so here's a super simple use of this API, and yes it's cute ๐
int fd;
pps_handle_t handle;
pps_params_t params;
pps_info_t infobuf;
struct timespec timeout;
/* Open a file descriptor and enable PPS on rising edges */
fd = open(PPSfilename, O_RDWR, 0);
time_pps_create(fd, &handle);
time_pps_getparams(handle, ¶ms);
if ((params.mode & PPS_CAPTUREASSERT) == 0) {
fprintf(stderr, "%s cannot currently CAPTUREASSERT\n",
PPSfilename);
exit(1);
}
/* create a zero-valued timeout */
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
/* loop, printing the most recent timestamp every second or so */
while (1) {
sleep(1);
time_pps_fetch(handle, PPS_TSFMT_TSPEC, &infobuf, &timeout);
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 skips most of the error-checking you'd expect in a reliable program, so don't copy it blindly into prod ๐ญ
Also, on a system that supports PPS_CANWAIT, the stuff in these lines:
sleep(1);
time_pps_fetch(handle, PPS_TSFMT_TSPEC, &infobuf, &timeout);
might be more reliably accomplished using:
timeout.tv_sec = 100;
timeout.tv_nsec = 0;
time_pps_fetch(handle, PPS_TSFMT_TSPEC, &infobuf, &timeout);
The (arbitrary) timeout value is there to protect against the possibility that another application might disable PPS timestamps, or that the hardware generating the timestamps might fail. Defensive and iconic ๐ก๏ธ
A slightly more elaborate use of this API might look like this ๐
int fd;
pps_handle_t handle;
pps_params_t params;
pps_info_t infobuf;
int avail_mode;
struct timespec timeout;
/* Open a file descriptor */
fd = open(PPSfilename, O_RDWR, 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);
}
if ((avail_mode & PPS_OFFSETASSERT) == 0) {
fprintf(stderr, "%s cannot OFFSETASSERT\n", PPSfilename);
exit(1);
}
/*
* Capture assert timestamps, and
* compensate for a 675 nsec propagation delay
*/
time_pps_getparams(handle, ¶ms);
params.assert_offset.tv_sec = 0;
params.assert_offset.tv_nsec = 675;
params.mode |= PPS_CAPTUREASSERT | PPS_OFFSETASSERT;
time_pps_setparams(handle, ¶ms);
/* create a zero-valued timeout */
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
/* loop, printing the most recent timestamp every second or so */
while (1) {
if (avail_mode & PPS_CANWAIT) {
time_pps_fetch(handle, PPS_TSFMT_TSPEC, &infobuf, NULL);
/* waits for the next event */
} else {
sleep(1);
time_pps_fetch(handle, PPS_TSFMT_TSPEC, &infobuf,
timeout);
}
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 left out of this one, so be responsible ๐ซถ
4. Security Considerations ๐ฅ
okay bestie, this section is the one you actually need to read twice ๐ This API gives applications three capabilities:
- Causing the system to capture timestamps on certain events.
- Obtaining timestamps for certain events.
- Affecting the system's internal timebase.
The first capability shouldn't affect security directly, but it might cause a slight increase in interrupt latency and interrupt-handling overhead.
The second capability might be useful for building certain kinds of covert communication channels ๐ต๏ธโโ๏ธ
In most cases, neither of these first two is a significant security threat, because the traditional UNIX file protection facility can be used to limit access to the relevant special files. Adding the PPS API adds minimal extra risk, so no panic yet ๐
The final capability is reserved for highly privileged users. On UNIX systems, that means people with superuser privilege. Those users can get around protections based on file permissions. However, such users can in general cause unbounded havoc, and they can set the internal timebase (and its rate of change), so this API creates no new vulnerabilities. Still, be careful with root, periodt ๐จ
5. Acknowledgements ๐
The API in this document gets some of its inspiration from the LBL "ppsclock" distribution [2], which was originally implemented in 1993 by Steve McCanne, Craig Leres, and Van Jacobson. Huge thanks also to Poul-Henning Kamp, Craig Leres, Judah Levine, and Harlan Stenn, who gave helpful comments while this document was being drafted ๐ซถ๐ง
6. References ๐
- Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997.
- Steve McCanne, Craig Leres, and Van Jacobson. PPSCLOCK.
ftp://ftp.ee.lbl.gov/ppsclock.tar.Z. - Mills, D., "Network Time Protocol (Version 3): Specification, Implementation and Analysis", RFC 1305, March 1992.
- Mills, D., "A Kernel Model for Precision Timekeeping", RFC 1589, March, 1994.
- The Open Group. The Single UNIX Specification, Version 2 - 6 Vol Set for UNIX 98. Document number T912, The Open Group, February, 1997.
7. Authors' Addresses ๐
Here are the people who made this happen, with their contact details exactly as they're listed:
Jeffrey C. Mogul
Western Research Laboratory
Compaq Computer Corporation
250 University Avenue
Palo Alto, California, 94305, U.S.A.
Phone: 1 650 617 3304 (email preferred)
EMail: mogul@wrl.dec.com
David L. Mills
Electrical and Computer 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
Ulrich Windl
Universitaet Regensburg, Klinikum
EMail: ulrich.windl@rz.uni-regensburg.de
A. Extensions and related APIs ๐ง
okay so the API in the main body of this document could be way more useful with a few extensions or companion APIs. Those are the vibes of this appendix โจ
At present, the interfaces listed in this appendix are NOT part of the formal specification in this document, so they're more like future-you wishlist items ๐
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. Real iconic energy, but also a lot left to figure out ๐ฆ
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. Future clocks are giving unknown-unknowns ๐ธ
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 be best 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. It's like terminfo but for clocks, and I'm obsessed ๐ญ
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.
A.3. Extension: Finding a PPS source
Okay so the clockinfo database from section A.2, together with the discovery mechanisms described there, would let an application discover the PPS source (or sources) connected to a system. But 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 ask 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 the application could then use 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"
which lets the system administrator describe the configuration of PPS sources. Very organised, very slay ๐
B. Example implementation: PPSDISC Line discipline โจ
okay so this part is a sketch of one possible way to build the PPS API, bestie ๐ Think of it as a fun little blueprint, not the actual spec. The API doesn't require any of this, and apps should not count on this low-level interface being there ๐
the idea is to add one new line discipline called PPSDISC ๐ฆ It acts exactly like TTYDISC, except it handles modem DCD interrupts differently.
Once you pick it with the TIOCSETD ioctl(), you can run PPS operations on the serial line through some new ioctl() commands. The values below are just 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 ๐
here's a typical use case, and it's giving very clean energy:
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) {
fprintf(stderr, "PPS source is not suitable\n");
exit(1);
}
/*
* Set this line to timestamp on a rising-edge interrupt
*/
ioctl(fd, PPSGETPARAMS, ¶ms);
params.mode |= PPS_CAPTUREASSERT;
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);
ngl this example is a little reckless because it skips all the error checking ๐ญ don't copy it into anything real without adding that in, periodt ๐
C. Available implementations ๐
there are a bunch of implementations of this API listed at <http://www.ntp.org/ppsapi/PPSImpList.html> ๐ง just know that not all of them match the current version of the spec, so double-check before you pick one bestie ๐ซถ
Full Copyright Statement ๐
Okay, legal stuff but make it cute ๐ The Internet Society owns the copyright here, and all rights are reserved, but the vibe is generous.
You can copy and share this document and translations of it, and you can make derivative works that comment on it, explain it, or help people implement it. You can publish and distribute all of that, in whole or in part, with no restrictions, as long as the copyright notice and this paragraph show up on every copy and derivative work ๐
The one big catch is that you can't modify this document itself in any way. That means no removing the copyright notice, and no removing references to the Internet Society or other Internet organizations. The exceptions are when you need it to develop Internet standards, in which case you have to follow the copyright procedures in the Internet Standards process, or when you need to translate it into a language other than English ๐ธ
These limited permissions are perpetual, and the Internet Society or its successors or assigns won't revoke them ๐
This document and the info in it are provided on an "AS IS" basis, and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ๐
Acknowledgement ๐ซถ
Funding for the RFC Editor function is currently provided by the Internet Society โจ
๐ฆ where this page comes from
- ietf: rfc2783 2000-03
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms