2 * ntp_refclock - processing support for reference clocks
10 #include "ntp_unixtime.h"
12 #include "ntp_refclock.h"
13 #include "ntp_stdlib.h"
14 #include "ntp_assert.h"
18 #ifdef HAVE_SYS_IOCTL_H
19 # include <sys/ioctl.h>
20 #endif /* HAVE_SYS_IOCTL_H */
25 #include "ntp_syscall.h"
26 #endif /* KERNEL_PLL */
29 #include "ppsapi_timepps.h"
30 #include "refclock_atom.h"
31 #endif /* HAVE_PPSAPI */
34 * Reference clock support is provided here by maintaining the fiction
35 * that the clock is actually a peer. As no packets are exchanged with
36 * a reference clock, however, we replace the transmit, receive and
37 * packet procedures with separate code to simulate them. Routines
38 * refclock_transmit() and refclock_receive() maintain the peer
39 * variables in a state analogous to an actual peer and pass reference
40 * clock data on through the filters. Routines refclock_peer() and
41 * refclock_unpeer() are called to initialize and terminate reference
42 * clock associations. A set of utility routines is included to open
43 * serial devices, process sample data, and to perform various debugging
46 * The main interface used by these routines is the refclockproc
47 * structure, which contains for most drivers the decimal equivalants
48 * of the year, day, month, hour, second and millisecond/microsecond
49 * decoded from the ASCII timecode. Additional information includes
50 * the receive timestamp, exception report, statistics tallies, etc.
51 * In addition, there may be a driver-specific unit structure used for
52 * local control of the device.
54 * The support routines are passed a pointer to the peer structure,
55 * which is used for all peer-specific processing and contains a
56 * pointer to the refclockproc structure, which in turn contains a
57 * pointer to the unit structure, if used. The peer structure is
58 * identified by an interface address in the dotted quad form
59 * 127.127.t.u, where t is the clock type and u the unit.
61 #define FUDGEFAC .1 /* fudge correction factor */
62 #define LF 0x0a /* ASCII LF */
64 int cal_enable; /* enable refclock calibrate */
67 * Forward declarations
69 static int refclock_cmpl_fp (const void *, const void *);
70 static int refclock_sample (struct refclockproc *);
71 static int refclock_ioctl(int, u_int);
75 * refclock_report - note the occurance of an event
77 * This routine presently just remembers the report and logs it, but
78 * does nothing heroic for the trap handler. It tries to be a good
79 * citizen and bothers the system log only if things change.
87 struct refclockproc *pp;
115 if (pp->lastevent < 15)
117 if (pp->currentstatus != code) {
118 pp->currentstatus = (u_char)code;
119 report_event(PEVNT_CLOCK, peer, ceventstr(code));
125 * init_refclock - initialize the reference clock drivers
127 * This routine calls each of the drivers in turn to initialize internal
128 * variables, if necessary. Most drivers have nothing to say at this
136 for (i = 0; i < (int)num_refclock_conf; i++)
137 if (refclock_conf[i]->clock_init != noentry)
138 (refclock_conf[i]->clock_init)();
143 * refclock_newpeer - initialize and start a reference clock
145 * This routine allocates and initializes the interface structure which
146 * supports a reference clock in the form of an ordinary NTP peer. A
147 * driver-specific support routine completes the initialization, if
148 * used. Default peer variables which identify the clock and establish
149 * its reference ID and stratum are set here. It returns one if success
150 * and zero if the clock address is invalid or already running,
151 * insufficient resources are available or the driver declares a bum
156 struct peer *peer /* peer structure pointer */
159 struct refclockproc *pp;
164 * Check for valid clock address. If already running, shut it
167 if (!ISREFCLOCKADR(&peer->srcadr)) {
169 "refclock_newpeer: clock address %s invalid",
170 stoa(&peer->srcadr));
173 clktype = (u_char)REFCLOCKTYPE(&peer->srcadr);
174 unit = REFCLOCKUNIT(&peer->srcadr);
175 if (clktype >= num_refclock_conf ||
176 refclock_conf[clktype]->clock_start == noentry) {
178 "refclock_newpeer: clock type %d invalid\n",
184 * Allocate and initialize interface structure
186 pp = emalloc_zero(sizeof(*pp));
190 * Initialize structures
192 peer->refclktype = clktype;
193 peer->refclkunit = (u_char)unit;
194 peer->flags |= FLAG_REFCLOCK;
195 peer->leap = LEAP_NOTINSYNC;
196 peer->stratum = STRATUM_REFCLOCK;
197 peer->ppoll = peer->maxpoll;
199 pp->conf = refclock_conf[clktype];
200 pp->timestarted = current_time;
204 * Set peer.pmode based on the hmode. For appearances only.
206 switch (peer->hmode) {
208 peer->pmode = MODE_PASSIVE;
212 peer->pmode = MODE_SERVER;
217 * Do driver dependent initialization. The above defaults
218 * can be wiggled, then finish up for consistency.
220 if (!((refclock_conf[clktype]->clock_start)(unit, peer))) {
221 refclock_unpeer(peer);
224 peer->refid = pp->refid;
230 * refclock_unpeer - shut down a clock
234 struct peer *peer /* peer structure pointer */
241 * Wiggle the driver to release its resources, then give back
242 * the interface structure.
244 if (NULL == peer->procptr)
247 clktype = peer->refclktype;
248 unit = peer->refclkunit;
249 if (refclock_conf[clktype]->clock_shutdown != noentry)
250 (refclock_conf[clktype]->clock_shutdown)(unit, peer);
252 peer->procptr = NULL;
257 * refclock_timer - called once per second for housekeeping.
264 struct refclockproc * pp;
267 unit = p->refclkunit;
269 if (pp->conf->clock_timer != noentry)
270 (*pp->conf->clock_timer)(unit, p);
271 if (pp->action != NULL && pp->nextaction <= current_time)
277 * refclock_transmit - simulate the transmit procedure
279 * This routine implements the NTP transmit procedure for a reference
280 * clock. This provides a mechanism to call the driver at the NTP poll
281 * interval, as well as provides a reachability mechanism to detect a
282 * broken radio or other madness.
286 struct peer *peer /* peer structure pointer */
292 clktype = peer->refclktype;
293 unit = peer->refclkunit;
295 get_systime(&peer->xmt);
298 * This is a ripoff of the peer transmit routine, but
299 * specialized for reference clocks. We do a little less
300 * protocol here and call the driver-specific transmit routine.
302 if (peer->burst == 0) {
306 printf("refclock_transmit: at %ld %s\n",
307 current_time, stoa(&(peer->srcadr)));
311 * Update reachability and poll variables like the
314 oreach = peer->reach & 0xfe;
316 if (!(peer->reach & 0x0f))
317 clock_filter(peer, 0., 0., MAXDISPERSE);
318 peer->outdate = current_time;
321 report_event(PEVNT_UNREACH, peer, NULL);
322 peer->timereachable = current_time;
325 if (peer->flags & FLAG_BURST)
326 peer->burst = NSTAGE;
331 if (refclock_conf[clktype]->clock_poll != noentry)
332 (refclock_conf[clktype]->clock_poll)(unit, peer);
333 poll_update(peer, peer->hpoll);
338 * Compare two doubles - used with qsort()
346 const double *dp1 = (const double *)p1;
347 const double *dp2 = (const double *)p2;
358 * refclock_process_offset - update median filter
360 * This routine uses the given offset and timestamps to construct a new
361 * entry in the median filter circular buffer. Samples that overflow the
362 * filter are quietly discarded.
365 refclock_process_offset(
366 struct refclockproc *pp, /* refclock structure pointer */
367 l_fp lasttim, /* last timecode timestamp */
368 l_fp lastrec, /* last receive timestamp */
375 pp->lastrec = lastrec;
377 L_SUB(&lftemp, &lastrec);
378 LFPTOD(&lftemp, doffset);
379 SAMPLE(doffset + fudge);
384 * refclock_process - process a sample from the clock
385 * refclock_process_f - refclock_process with other than time1 fudge
387 * This routine converts the timecode in the form days, hours, minutes,
388 * seconds and milliseconds/microseconds to internal timestamp format,
389 * then constructs a new entry in the median filter circular buffer.
390 * Return success (1) if the data are correct and consistent with the
391 * converntional calendar.
393 * Important for PPS users: Normally, the pp->lastrec is set to the
394 * system time when the on-time character is received and the pp->year,
395 * ..., pp->second decoded and the seconds fraction pp->nsec in
396 * nanoseconds). When a PPS offset is available, pp->nsec is forced to
397 * zero and the fraction for pp->lastrec is set to the PPS offset.
401 struct refclockproc *pp, /* refclock structure pointer */
408 * Compute the timecode timestamp from the days, hours, minutes,
409 * seconds and milliseconds/microseconds of the timecode. Use
410 * clocktime() for the aggregate seconds and the msec/usec for
411 * the fraction, when present. Note that this code relies on the
412 * filesystem time for the years and does not use the years of
415 if (!clocktime(pp->day, pp->hour, pp->minute, pp->second, GMT,
416 pp->lastrec.l_ui, &pp->yearstart, &offset.l_ui))
420 DTOLFP(pp->nsec / 1e9, <emp);
421 L_ADD(&offset, <emp);
422 refclock_process_offset(pp, offset, pp->lastrec, fudge);
429 struct refclockproc *pp /* refclock structure pointer */
432 return refclock_process_f(pp, pp->fudgetime1);
437 * refclock_sample - process a pile of samples from the clock
439 * This routine implements a recursive median filter to suppress spikes
440 * in the data, as well as determine a performance statistic. It
441 * calculates the mean offset and RMS jitter. A time adjustment
442 * fudgetime1 can be added to the final offset to compensate for various
443 * systematic errors. The routine returns the number of samples
444 * processed, which could be zero.
448 struct refclockproc *pp /* refclock structure pointer */
451 size_t i, j, k, m, n;
452 double off[MAXSTAGE];
456 * Copy the raw offsets and sort into ascending order. Don't do
457 * anything if the buffer is empty.
460 while (pp->codeproc != pp->coderecv) {
461 pp->codeproc = (pp->codeproc + 1) % MAXSTAGE;
462 off[n] = pp->filter[pp->codeproc];
469 qsort(off, n, sizeof(off[0]), refclock_cmpl_fp);
472 * Reject the furthest from the median of the samples until
473 * approximately 60 percent of the samples remain.
476 m = n - (n * 4) / 10;
477 while ((j - i) > m) {
478 offset = off[(j + i) / 2];
479 if (off[j - 1] - offset < offset - off[i])
480 i++; /* reject low end */
482 j--; /* reject high end */
486 * Determine the offset and jitter.
490 for (k = i; k < j; k++) {
491 pp->offset += off[k];
493 pp->jitter += SQUARE(off[k] - off[k - 1]);
496 pp->jitter = max(SQRT(pp->jitter / m), LOGTOD(sys_precision));
500 "refclock_sample: n %d offset %.6f disp %.6f jitter %.6f\n",
501 (int)n, pp->offset, pp->disp, pp->jitter);
508 * refclock_receive - simulate the receive and packet procedures
510 * This routine simulates the NTP receive and packet procedures for a
511 * reference clock. This provides a mechanism in which the ordinary NTP
512 * filter, selection and combining algorithms can be used to suppress
513 * misbehaving radios and to mitigate between them when more than one is
514 * available for backup.
518 struct peer *peer /* peer structure pointer */
521 struct refclockproc *pp;
525 printf("refclock_receive: at %lu %s\n",
526 current_time, stoa(&peer->srcadr));
530 * Do a little sanity dance and update the peer structure. Groom
531 * the median filter samples and give the data to the clock
535 peer->leap = pp->leap;
536 if (peer->leap == LEAP_NOTINSYNC)
540 peer->timereceived = current_time;
542 report_event(PEVNT_REACH, peer, NULL);
543 peer->timereachable = current_time;
546 peer->reftime = pp->lastref;
547 peer->aorg = pp->lastrec;
548 peer->rootdisp = pp->disp;
549 get_systime(&peer->dst);
550 if (!refclock_sample(pp))
553 clock_filter(peer, pp->offset, 0., pp->jitter);
554 if (cal_enable && fabs(last_offset) < sys_mindisp && sys_peer !=
556 if (sys_peer->refclktype == REFCLK_ATOM_PPS &&
557 peer->refclktype != REFCLK_ATOM_PPS)
558 pp->fudgetime1 -= pp->offset * FUDGEFAC;
564 * refclock_gtlin - groom next input line and extract timestamp
566 * This routine processes the timecode received from the clock and
567 * strips the parity bit and control characters. It returns the number
568 * of characters in the line followed by a NULL character ('\0'), which
569 * is not included in the count. In case of an empty line, the previous
574 struct recvbuf *rbufp, /* receive buffer pointer */
575 char *lineptr, /* current line pointer */
576 int bmax, /* remaining characters in line */
577 l_fp *tsptr /* pointer to timestamp returned */
580 const char *sp, *spend;
588 dpend = dp + bmax - 1; /* leave room for NUL pad */
589 sp = (const char *)rbufp->recv_buffer;
590 spend = sp + rbufp->recv_length;
592 while (sp != spend && dp != dpend) {
596 if (c >= 0x20 && c < 0x7f)
599 /* Get length of data written to the destination buffer. If
600 * zero, do *not* place a NUL byte to preserve the previous
606 *tsptr = rbufp->recv_time;
607 DPRINTF(2, ("refclock_gtlin: fd %d time %s timecode %d %s\n",
608 rbufp->fd, ulfptoa(&rbufp->recv_time, 6), dlen,
617 * refclock_gtraw - get next line/chunk of data
619 * This routine returns the raw data received from the clock in both
620 * canonical or raw modes. The terminal interface routines map CR to LF.
621 * In canonical mode this results in two lines, one containing data
622 * followed by LF and another containing only LF. In raw mode the
623 * interface routines can deliver arbitraty chunks of data from one
624 * character to a maximum specified by the calling routine. In either
625 * mode the routine returns the number of characters in the line
626 * followed by a NULL character ('\0'), which is not included in the
629 * *tsptr receives a copy of the buffer timestamp.
633 struct recvbuf *rbufp, /* receive buffer pointer */
634 char *lineptr, /* current line pointer */
635 int bmax, /* remaining characters in line */
636 l_fp *tsptr /* pointer to timestamp returned */
641 bmax -= 1; /* leave room for trailing NUL */
642 if (bmax > rbufp->recv_length)
643 bmax = rbufp->recv_length;
644 memcpy(lineptr, rbufp->recv_buffer, bmax);
645 lineptr[bmax] = '\0';
647 *tsptr = rbufp->recv_time;
648 DPRINTF(2, ("refclock_gtraw: fd %d time %s timecode %d %s\n",
649 rbufp->fd, ulfptoa(&rbufp->recv_time, 6), bmax,
656 * indicate_refclock_packet()
658 * Passes a fragment of refclock input read from the device to the
659 * driver direct input routine, which may consume it (batch it for
660 * queuing once a logical unit is assembled). If it is not so
661 * consumed, queue it for the driver's receive entrypoint.
663 * The return value is TRUE if the data has been consumed as a fragment
664 * and should not be counted as a received packet.
667 indicate_refclock_packet(
668 struct refclockio * rio,
672 /* Does this refclock use direct input routine? */
673 if (rio->io_input != NULL && (*rio->io_input)(rb) == 0) {
675 * data was consumed - nothing to pass up
676 * into block input machine
682 add_full_recv_buffer(rb);
689 * process_refclock_packet()
691 * Used for deferred processing of 'io_input' on systems where threading
692 * is used (notably Windows). This is acting as a trampoline to make the
693 * real calls to the refclock functions.
695 #ifdef HAVE_IO_COMPLETION_PORT
697 process_refclock_packet(
701 struct refclockio * rio;
703 /* get the refclockio structure from the receive buffer */
704 rio = &rb->recv_peer->procptr->io;
706 /* call 'clock_recv' if either there is no input function or the
707 * raw input function tells us to feed the packet to the
710 if (rio->io_input == NULL || (*rio->io_input)(rb) != 0) {
714 (*rio->clock_recv)(rb);
717 #endif /* HAVE_IO_COMPLETION_PORT */
721 * The following code does not apply to WINNT & VMS ...
723 #if !defined(SYS_VXWORKS) && !defined(SYS_WINNT)
724 #if defined(HAVE_TERMIOS) || defined(HAVE_SYSV_TTYS) || defined(HAVE_BSD_TTYS)
727 * refclock_open - open serial port for reference clock
729 * This routine opens a serial port for I/O and sets default options. It
730 * returns the file descriptor if successful, or logs an error and
735 const char *dev, /* device name pointer */
736 u_int speed, /* serial port speed (code) */
737 u_int lflags /* line discipline flags */
743 char trash[128]; /* litter bin for old input data */
747 * Open serial port and set default options
757 fd = open(dev, omode, 0777);
758 /* refclock_open() long returned 0 on failure, avoid it. */
767 msyslog(LOG_ERR, "refclock_open %s: %m", dev);
771 if (!refclock_setup(fd, speed, lflags)) {
775 if (!refclock_ioctl(fd, lflags)) {
781 * We want to make sure there is no pending trash in the input
782 * buffer. Since we have non-blocking IO available, this is a
783 * good moment to read and dump all available outdated stuff
784 * that might have become toxic for the driver.
786 while (read(fd, trash, sizeof(trash)) > 0 || errno == EINTR)
794 * refclock_setup - initialize terminal interface structure
798 int fd, /* file descriptor */
799 u_int speed, /* serial port speed (code) */
800 u_int lflags /* line discipline flags */
807 * By default, the serial line port is initialized in canonical
808 * (line-oriented) mode at specified line speed, 8 bits and no
809 * parity. LF ends the line and CR is mapped to LF. The break,
810 * erase and kill functions are disabled. There is a different
811 * section for each terminal interface, as selected at compile
812 * time. The flag bits can be used to set raw mode and echo.
818 * POSIX serial line parameters (termios interface)
820 if (tcgetattr(fd, ttyp) < 0) {
823 "refclock_setup fd %d tcgetattr: %m",
830 * Set canonical mode and local connection; set specified speed,
831 * 8 bits and no parity; map CR to NL; ignore break.
836 ttyp->c_iflag = IGNBRK | IGNPAR | ICRNL;
838 ttyp->c_cflag = CS8 | CLOCAL | CREAD;
839 if (lflags & LDISC_7O1) {
840 /* HP Z3801A needs 7-bit, odd parity */
841 ttyp->c_cflag = CS7 | PARENB | PARODD | CLOCAL | CREAD;
843 cfsetispeed(&ttyb, speed);
844 cfsetospeed(&ttyb, speed);
845 for (i = 0; i < NCCS; ++i)
846 ttyp->c_cc[i] = '\0';
848 #if defined(TIOCMGET) && !defined(SCO5_CLOCK)
851 * If we have modem control, check to see if modem leads
852 * are active; if so, set remote connection. This is
853 * necessary for the kernel pps mods to work.
855 if (ioctl(fd, TIOCMGET, (char *)<emp) < 0)
857 "refclock_setup fd %d TIOCMGET: %m", fd);
860 printf("refclock_setup fd %d modem status: 0x%x\n",
863 if (ltemp & TIOCM_DSR && lflags & LDISC_REMOTE)
864 ttyp->c_cflag &= ~CLOCAL;
865 #endif /* TIOCMGET */
869 * Set raw and echo modes. These can be changed on-fly.
871 ttyp->c_lflag = ICANON;
872 if (lflags & LDISC_RAW) {
875 ttyp->c_cc[VMIN] = 1;
877 if (lflags & LDISC_ECHO)
878 ttyp->c_lflag |= ECHO;
879 if (tcsetattr(fd, TCSANOW, ttyp) < 0) {
882 "refclock_setup fd %d TCSANOW: %m",
889 * flush input and output buffers to discard any outdated stuff
890 * that might have become toxic for the driver. Failing to do so
891 * is logged, but we keep our fingers crossed otherwise.
893 if (tcflush(fd, TCIOFLUSH) < 0)
894 msyslog(LOG_ERR, "refclock_setup fd %d tcflush(): %m",
896 #endif /* HAVE_TERMIOS */
898 #ifdef HAVE_SYSV_TTYS
901 * System V serial line parameters (termio interface)
904 if (ioctl(fd, TCGETA, ttyp) < 0) {
907 "refclock_setup fd %d TCGETA: %m",
914 * Set canonical mode and local connection; set specified speed,
915 * 8 bits and no parity; map CR to NL; ignore break.
920 ttyp->c_iflag = IGNBRK | IGNPAR | ICRNL;
922 ttyp->c_cflag = speed | CS8 | CLOCAL | CREAD;
923 for (i = 0; i < NCCS; ++i)
924 ttyp->c_cc[i] = '\0';
926 #if defined(TIOCMGET) && !defined(SCO5_CLOCK)
929 * If we have modem control, check to see if modem leads
930 * are active; if so, set remote connection. This is
931 * necessary for the kernel pps mods to work.
933 if (ioctl(fd, TIOCMGET, (char *)<emp) < 0)
935 "refclock_setup fd %d TIOCMGET: %m", fd);
938 printf("refclock_setup fd %d modem status: %x\n",
941 if (ltemp & TIOCM_DSR)
942 ttyp->c_cflag &= ~CLOCAL;
943 #endif /* TIOCMGET */
947 * Set raw and echo modes. These can be changed on-fly.
949 ttyp->c_lflag = ICANON;
950 if (lflags & LDISC_RAW) {
953 ttyp->c_cc[VMIN] = 1;
955 if (ioctl(fd, TCSETA, ttyp) < 0) {
958 "refclock_setup fd %d TCSETA: %m", fd);
962 #endif /* HAVE_SYSV_TTYS */
967 * 4.3bsd serial line parameters (sgttyb interface)
969 if (ioctl(fd, TIOCGETP, (char *)ttyp) < 0) {
972 "refclock_setup fd %d TIOCGETP: %m",
978 ttyp->sg_ispeed = ttyp->sg_ospeed = speed;
979 ttyp->sg_flags = EVENP | ODDP | CRMOD;
980 if (ioctl(fd, TIOCSETP, (char *)ttyp) < 0) {
982 msyslog(LOG_ERR, "refclock_setup TIOCSETP: %m");
986 #endif /* HAVE_BSD_TTYS */
989 #endif /* HAVE_TERMIOS || HAVE_SYSV_TTYS || HAVE_BSD_TTYS */
993 * refclock_ioctl - set serial port control functions
995 * This routine attempts to hide the internal, system-specific details
996 * of serial ports. It can handle POSIX (termios), SYSV (termio) and BSD
997 * (sgtty) interfaces with varying degrees of success. The routine sets
998 * up optional features such as tty_clk. The routine returns TRUE if
1003 int fd, /* file descriptor */
1004 u_int lflags /* line discipline flags */
1008 * simply return TRUE if no UNIX line discipline is supported
1010 DPRINTF(1, ("refclock_ioctl: fd %d flags 0x%x\n", fd, lflags));
1014 #endif /* !defined(SYS_VXWORKS) && !defined(SYS_WINNT) */
1018 * refclock_control - set and/or return clock values
1020 * This routine is used mainly for debugging. It returns designated
1021 * values from the interface structure that can be displayed using
1022 * ntpdc and the clockstat command. It can also be used to initialize
1023 * configuration variables, such as fudgetimes, fudgevalues, reference
1029 const struct refclockstat *in,
1030 struct refclockstat *out
1034 struct refclockproc *pp;
1039 * Check for valid address and running peer
1041 if (!ISREFCLOCKADR(srcadr))
1044 clktype = (u_char)REFCLOCKTYPE(srcadr);
1045 unit = REFCLOCKUNIT(srcadr);
1047 peer = findexistingpeer(srcadr, NULL, NULL, -1, 0);
1052 INSIST(peer->procptr != NULL);
1056 * Initialize requested data
1059 if (in->haveflags & CLK_HAVETIME1)
1060 pp->fudgetime1 = in->fudgetime1;
1061 if (in->haveflags & CLK_HAVETIME2)
1062 pp->fudgetime2 = in->fudgetime2;
1063 if (in->haveflags & CLK_HAVEVAL1)
1064 peer->stratum = pp->stratum = (u_char)in->fudgeval1;
1065 if (in->haveflags & CLK_HAVEVAL2)
1066 peer->refid = pp->refid = in->fudgeval2;
1067 if (in->haveflags & CLK_HAVEFLAG1) {
1068 pp->sloppyclockflag &= ~CLK_FLAG1;
1069 pp->sloppyclockflag |= in->flags & CLK_FLAG1;
1071 if (in->haveflags & CLK_HAVEFLAG2) {
1072 pp->sloppyclockflag &= ~CLK_FLAG2;
1073 pp->sloppyclockflag |= in->flags & CLK_FLAG2;
1075 if (in->haveflags & CLK_HAVEFLAG3) {
1076 pp->sloppyclockflag &= ~CLK_FLAG3;
1077 pp->sloppyclockflag |= in->flags & CLK_FLAG3;
1079 if (in->haveflags & CLK_HAVEFLAG4) {
1080 pp->sloppyclockflag &= ~CLK_FLAG4;
1081 pp->sloppyclockflag |= in->flags & CLK_FLAG4;
1086 * Readback requested data
1089 out->fudgeval1 = pp->stratum;
1090 out->fudgeval2 = pp->refid;
1091 out->haveflags = CLK_HAVEVAL1 | CLK_HAVEVAL2;
1092 out->fudgetime1 = pp->fudgetime1;
1093 if (0.0 != out->fudgetime1)
1094 out->haveflags |= CLK_HAVETIME1;
1095 out->fudgetime2 = pp->fudgetime2;
1096 if (0.0 != out->fudgetime2)
1097 out->haveflags |= CLK_HAVETIME2;
1098 out->flags = (u_char) pp->sloppyclockflag;
1099 if (CLK_FLAG1 & out->flags)
1100 out->haveflags |= CLK_HAVEFLAG1;
1101 if (CLK_FLAG2 & out->flags)
1102 out->haveflags |= CLK_HAVEFLAG2;
1103 if (CLK_FLAG3 & out->flags)
1104 out->haveflags |= CLK_HAVEFLAG3;
1105 if (CLK_FLAG4 & out->flags)
1106 out->haveflags |= CLK_HAVEFLAG4;
1108 out->timereset = current_time - pp->timestarted;
1109 out->polls = pp->polls;
1110 out->noresponse = pp->noreply;
1111 out->badformat = pp->badformat;
1112 out->baddata = pp->baddata;
1114 out->lastevent = pp->lastevent;
1115 out->currentstatus = pp->currentstatus;
1116 out->type = pp->type;
1117 out->clockdesc = pp->clockdesc;
1118 out->lencode = (u_short)pp->lencode;
1119 out->p_lastcode = pp->a_lastcode;
1123 * Give the stuff to the clock
1125 if (refclock_conf[clktype]->clock_control != noentry)
1126 (refclock_conf[clktype]->clock_control)(unit, in, out, peer);
1131 * refclock_buginfo - return debugging info
1133 * This routine is used mainly for debugging. It returns designated
1134 * values from the interface structure that can be displayed using
1135 * ntpdc and the clkbug command.
1139 sockaddr_u *srcadr, /* clock address */
1140 struct refclockbug *bug /* output structure */
1144 struct refclockproc *pp;
1150 * Check for valid address and peer structure
1152 if (!ISREFCLOCKADR(srcadr))
1155 clktype = (u_char) REFCLOCKTYPE(srcadr);
1156 unit = REFCLOCKUNIT(srcadr);
1158 peer = findexistingpeer(srcadr, NULL, NULL, -1, 0);
1160 if (NULL == peer || NULL == peer->procptr)
1166 * Copy structure values
1169 bug->svalues = 0x0000003f;
1170 bug->values[0] = pp->year;
1171 bug->values[1] = pp->day;
1172 bug->values[2] = pp->hour;
1173 bug->values[3] = pp->minute;
1174 bug->values[4] = pp->second;
1175 bug->values[5] = pp->nsec;
1176 bug->values[6] = pp->yearstart;
1177 bug->values[7] = pp->coderecv;
1178 bug->stimes = 0xfffffffc;
1179 bug->times[0] = pp->lastref;
1180 bug->times[1] = pp->lastrec;
1181 for (u = 2; u < bug->ntimes; u++)
1182 DTOLFP(pp->filter[u - 2], &bug->times[u]);
1185 * Give the stuff to the clock
1187 if (refclock_conf[clktype]->clock_buginfo != noentry)
1188 (refclock_conf[clktype]->clock_buginfo)(unit, bug, peer);
1194 * refclock_ppsapi - initialize/update ppsapi
1196 * This routine is called after the fudge command to open the PPSAPI
1197 * interface for later parameter setting after the fudge command.
1201 int fddev, /* fd device */
1202 struct refclock_atom *ap /* atom structure pointer */
1205 if (ap->handle == 0) {
1206 if (time_pps_create(fddev, &ap->handle) < 0) {
1208 "refclock_ppsapi: time_pps_create: %m");
1211 ZERO(ap->ts); /* [Bug 2689] defined INIT state */
1218 * refclock_params - set ppsapi parameters
1220 * This routine is called to set the PPSAPI parameters after the fudge
1225 int mode, /* mode bits */
1226 struct refclock_atom *ap /* atom structure pointer */
1229 ZERO(ap->pps_params);
1230 ap->pps_params.api_version = PPS_API_VERS_1;
1233 * Solaris serial ports provide PPS pulse capture only on the
1234 * assert edge. FreeBSD serial ports provide capture on the
1235 * clear edge, while FreeBSD parallel ports provide capture
1236 * on the assert edge. Your mileage may vary.
1238 if (mode & CLK_FLAG2)
1239 ap->pps_params.mode = PPS_TSFMT_TSPEC | PPS_CAPTURECLEAR;
1241 ap->pps_params.mode = PPS_TSFMT_TSPEC | PPS_CAPTUREASSERT;
1242 if (time_pps_setparams(ap->handle, &ap->pps_params) < 0) {
1244 "refclock_params: time_pps_setparams: %m");
1249 * If flag3 is lit, select the kernel PPS if we can.
1251 if (mode & CLK_FLAG3) {
1252 if (time_pps_kcbind(ap->handle, PPS_KC_HARDPPS,
1253 ap->pps_params.mode & ~PPS_TSFMT_TSPEC,
1254 PPS_TSFMT_TSPEC) < 0) {
1256 "refclock_params: time_pps_kcbind: %m");
1266 * refclock_pps - called once per second
1268 * This routine is called once per second. It snatches the PPS
1269 * timestamp from the kernel and saves the sign-extended fraction in
1270 * a circular buffer for processing at the next poll event.
1274 struct peer *peer, /* peer structure pointer */
1275 struct refclock_atom *ap, /* atom structure pointer */
1276 int mode /* mode bits */
1279 struct refclockproc *pp;
1280 pps_info_t pps_info;
1281 struct timespec timeout;
1282 double dtemp, dcorr, trash;
1285 * We require the clock to be synchronized before setting the
1286 * parameters. When the parameters have been set, fetch the
1287 * most recent PPS timestamp.
1290 if (ap->handle == 0)
1293 if (ap->pps_params.mode == 0 && sys_leap != LEAP_NOTINSYNC) {
1294 if (refclock_params(pp->sloppyclockflag, ap) < 1)
1299 if (time_pps_fetch(ap->handle, PPS_TSFMT_TSPEC, &pps_info,
1301 refclock_report(peer, CEVNT_FAULT);
1304 timeout = ap->ts; /* save old timestamp for check */
1305 if (ap->pps_params.mode & PPS_CAPTUREASSERT)
1306 ap->ts = pps_info.assert_timestamp;
1307 else if (ap->pps_params.mode & PPS_CAPTURECLEAR)
1308 ap->ts = pps_info.clear_timestamp;
1312 /* [Bug 2689] Discard the first sample we read -- if the PPS
1313 * source is currently down / disconnected, we have read a
1314 * potentially *very* stale value here. So if our old TS value
1315 * is all-zero, we consider this sample unrealiable and drop it.
1317 * Note 1: a better check would compare the PPS time stamp to
1318 * the current system time and drop it if it's more than say 3s
1321 * Note 2: If we ever again get an all-zero PPS sample, the next
1322 * one will be discarded. This can happen every 136yrs and is
1323 * unlikely to be ever observed.
1325 if (0 == (timeout.tv_sec | timeout.tv_nsec))
1328 /* If the PPS source fails to deliver a new sample between
1329 * polls, it regurgitates the last sample. We do not want to
1330 * process the same sample multiple times.
1332 if (0 == memcmp(&timeout, &ap->ts, sizeof(timeout)))
1336 * Convert to signed fraction offset, apply fudge and properly
1337 * fold the correction into the [-0.5s,0.5s] range. Handle
1338 * excessive fudge times, too.
1340 dtemp = ap->ts.tv_nsec / 1e9;
1341 dcorr = modf((pp->fudgetime1 - dtemp), &trash);
1344 else if (dcorr < -0.5)
1347 /* phase gate check: avoid wobbling by +/-1s when too close to
1348 * the switch-over point. We allow +/-400ms max phase deviation.
1349 * The trade-off is clear: The smaller the limit, the less
1350 * sensitive to sampling noise the clock becomes. OTOH the
1351 * system must get into phase gate range by other means for the
1352 * PPS clock to lock in.
1354 if (fabs(dcorr) > 0.4)
1358 * record this time stamp and stuff in median filter
1360 pp->lastrec.l_ui = (u_int32)ap->ts.tv_sec + JAN_1970;
1361 pp->lastrec.l_uf = (u_int32)(dtemp * FRAC);
1366 printf("refclock_pps: %lu %f %f\n", current_time,
1367 dcorr, pp->fudgetime1);
1371 #endif /* HAVE_PPSAPI */
1372 #endif /* REFCLOCK */