2 * NTP client/server, based on OpenNTPD 3.9p1
4 * Author: Adam Tkac <vonsch@gmail.com>
6 * Licensed under GPLv2, see file LICENSE in this tarball for details.
8 * Parts of OpenNTPD clock syncronization code is replaced by
9 * code which is based on ntp-4.2.6, whuch carries the following
12 ***********************************************************************
14 * Copyright (c) University of Delaware 1992-2009 *
16 * Permission to use, copy, modify, and distribute this software and *
17 * its documentation for any purpose with or without fee is hereby *
18 * granted, provided that the above copyright notice appears in all *
19 * copies and that both the copyright notice and this permission *
20 * notice appear in supporting documentation, and that the name *
21 * University of Delaware not be used in advertising or publicity *
22 * pertaining to distribution of the software without specific, *
23 * written prior permission. The University of Delaware makes no *
24 * representations about the suitability this software for any *
25 * purpose. It is provided "as is" without express or implied *
28 ***********************************************************************
32 #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
33 #include <sys/timex.h>
34 #ifndef IPTOS_LOWDELAY
35 # define IPTOS_LOWDELAY 0x10
38 # error "Sorry, your kernel has to support IP_PKTINFO"
42 /* Verbosity control (max level of -dddd options accepted).
43 * max 5 is very talkative (and bloated). 2 is non-bloated,
44 * production level setting.
49 /* High-level description of the algorithm:
51 * We start running with very small poll_exp, BURSTPOLL,
52 * in order to quickly accumulate INITIAL_SAMLPES datapoints
53 * for each peer. Then, time is stepped if the offset is larger
54 * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
55 * poll_exp to MINPOLL and enter frequency measurement step:
56 * we collect new datapoints but ignore them for WATCH_THRESHOLD
57 * seconds. After WATCH_THRESHOLD seconds we look at accumulated
58 * offset and estimate frequency drift.
60 * (frequency measurement step seems to not be strictly needed,
61 * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
64 * After this, we enter "steady state": we collect a datapoint,
65 * we select the best peer, if this datapoint is not a new one
66 * (IOW: if this datapoint isn't for selected peer), sleep
67 * and collect another one; otherwise, use its offset to update
68 * frequency drift, if offset is somewhat large, reduce poll_exp,
69 * otherwise increase poll_exp.
71 * If offset is larger than STEP_THRESHOLD, which shouldn't normally
72 * happen, we assume that something "bad" happened (computer
73 * was hibernated, someone set totally wrong date, etc),
74 * then the time is stepped, all datapoints are discarded,
75 * and we go back to steady state.
78 #define RETRY_INTERVAL 5 /* on error, retry in N secs */
79 #define RESPONSE_INTERVAL 15 /* wait for reply up to N secs */
80 #define INITIAL_SAMLPES 4 /* how many samples do we want for init */
82 /* Clock discipline parameters and constants */
84 /* Step threshold (sec). std ntpd uses 0.128.
85 * Using exact power of 2 (1/8) results in smaller code */
86 #define STEP_THRESHOLD 0.125
87 #define WATCH_THRESHOLD 128 /* stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
88 /* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
89 //UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
91 #define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
92 #define BURSTPOLL 0 /* initial poll */
93 #define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
94 #define BIGPOLL 10 /* drop to lower poll at any trouble (10: 17 min) */
95 #define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
96 /* Actively lower poll when we see such big offsets.
97 * With STEP_THRESHOLD = 0.125, it means we try to sync more aggressively
98 * if offset increases over 0.03 sec */
99 #define POLLDOWN_OFFSET (STEP_THRESHOLD / 4)
100 #define MINDISP 0.01 /* minimum dispersion (sec) */
101 #define MAXDISP 16 /* maximum dispersion (sec) */
102 #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
103 #define MAXDIST 1 /* distance threshold (sec) */
104 #define MIN_SELECTED 1 /* minimum intersection survivors */
105 #define MIN_CLUSTERED 3 /* minimum cluster survivors */
107 #define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
109 /* Poll-adjust threshold.
110 * When we see that offset is small enough compared to discipline jitter,
111 * we grow a counter: += MINPOLL. When it goes over POLLADJ_LIMIT,
112 * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
113 * and when it goes below -POLLADJ_LIMIT, we poll_exp--
114 * (bumped from 30 to 36 since otherwise I often see poll_exp going *2* steps down)
116 #define POLLADJ_LIMIT 36
117 /* If offset < POLLADJ_GATE * discipline_jitter, then we can increase
118 * poll interval (we think we can't improve timekeeping
119 * by staying at smaller poll).
121 #define POLLADJ_GATE 4
122 /* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
126 /* FLL loop gain [why it depends on MAXPOLL??] */
127 #define FLL (MAXPOLL + 1)
128 /* Parameter averaging constant */
137 NTP_MSGSIZE_NOAUTH = 48,
138 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
141 MODE_MASK = (7 << 0),
142 VERSION_MASK = (7 << 3),
146 /* Leap Second Codes (high order two bits of m_status) */
147 LI_NOWARNING = (0 << 6), /* no warning */
148 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
149 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
150 LI_ALARM = (3 << 6), /* alarm condition */
153 MODE_RES0 = 0, /* reserved */
154 MODE_SYM_ACT = 1, /* symmetric active */
155 MODE_SYM_PAS = 2, /* symmetric passive */
156 MODE_CLIENT = 3, /* client */
157 MODE_SERVER = 4, /* server */
158 MODE_BROADCAST = 5, /* broadcast */
159 MODE_RES1 = 6, /* reserved for NTP control message */
160 MODE_RES2 = 7, /* reserved for private use */
163 //TODO: better base selection
164 #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
166 #define NUM_DATAPOINTS 8
179 uint8_t m_status; /* status of local clock and leap info */
181 uint8_t m_ppoll; /* poll value */
182 int8_t m_precision_exp;
183 s_fixedpt_t m_rootdelay;
184 s_fixedpt_t m_rootdisp;
186 l_fixedpt_t m_reftime;
187 l_fixedpt_t m_orgtime;
188 l_fixedpt_t m_rectime;
189 l_fixedpt_t m_xmttime;
191 uint8_t m_digest[NTP_DIGESTSIZE];
201 len_and_sockaddr *p_lsa;
203 /* when to send new query (if p_fd == -1)
204 * or when receive times out (if p_fd >= 0): */
207 uint32_t lastpkt_refid;
208 uint8_t lastpkt_status;
209 uint8_t lastpkt_stratum;
210 uint8_t reachable_bits;
211 double next_action_time;
213 double lastpkt_recv_time;
214 double lastpkt_delay;
215 double lastpkt_rootdelay;
216 double lastpkt_rootdisp;
217 /* produced by filter algorithm: */
218 double filter_offset;
219 double filter_dispersion;
220 double filter_jitter;
221 datapoint_t filter_datapoint[NUM_DATAPOINTS];
222 /* last sent packet: */
227 #define USING_KERNEL_PLL_LOOP 1
228 #define USING_INITIAL_FREQ_ESTIMATION 0
235 /* Insert new options above this line. */
236 /* Non-compat options: */
240 OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
245 /* total round trip delay to currently selected reference clock */
247 /* reference timestamp: time when the system clock was last set or corrected */
249 /* total dispersion to currently selected reference clock */
252 double last_script_run;
255 #if ENABLE_FEATURE_NTPD_SERVER
260 /* refid: 32-bit code identifying the particular server or reference clock
261 * in stratum 0 packets this is a four-character ASCII string,
262 * called the kiss code, used for debugging and monitoring
263 * in stratum 1 packets this is a four-character ASCII string
264 * assigned to the reference clock by IANA. Example: "GPS "
265 * in stratum 2+ packets, it's IPv4 address or 4 first bytes of MD5 hash of IPv6
269 /* precision is defined as the larger of the resolution and time to
270 * read the clock, in log2 units. For instance, the precision of a
271 * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
272 * system clock hardware representation is to the nanosecond.
274 * Delays, jitters of various kinds are clamper down to precision.
276 * If precision_sec is too large, discipline_jitter gets clamped to it
277 * and if offset is much smaller than discipline_jitter, poll interval
278 * grows even though we really can benefit from staying at smaller one,
279 * collecting non-lagged datapoits and correcting the offset.
280 * (Lagged datapoits exist when poll_exp is large but we still have
281 * systematic offset error - the time distance between datapoints
282 * is significat and older datapoints have smaller offsets.
283 * This makes our offset estimation a bit smaller than reality)
284 * Due to this effect, setting G_precision_sec close to
285 * STEP_THRESHOLD isn't such a good idea - offsets may grow
286 * too big and we will step. I observed it with -6.
288 * OTOH, setting precision too small would result in futile attempts
289 * to syncronize to the unachievable precision.
291 * -6 is 1/64 sec, -7 is 1/128 sec and so on.
293 #define G_precision_exp -8
294 #define G_precision_sec (1.0 / (1 << (- G_precision_exp)))
296 /* Bool. After set to 1, never goes back to 0: */
297 smallint adjtimex_was_done;
298 smallint initial_poll_complete;
300 #define STATE_NSET 0 /* initial state, "nothing is set" */
301 //#define STATE_FSET 1 /* frequency set from file */
302 #define STATE_SPIK 2 /* spike detected */
303 //#define STATE_FREQ 3 /* initial frequency */
304 #define STATE_SYNC 4 /* clock synchronized (normal operation) */
305 uint8_t discipline_state; // doc calls it c.state
306 uint8_t poll_exp; // s.poll
307 int polladj_count; // c.count
308 long kernel_freq_drift;
309 peer_t *last_update_peer;
310 double last_update_offset; // c.last
311 double last_update_recv_time; // s.t
312 double discipline_jitter; // c.jitter
313 //double cluster_offset; // s.offset
314 //double cluster_jitter; // s.jitter
315 #if !USING_KERNEL_PLL_LOOP
316 double discipline_freq_drift; // c.freq
317 /* Maybe conditionally calculate wander? it's used only for logging */
318 double discipline_wander; // c.wander
321 #define G (*ptr_to_globals)
323 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
326 #define VERB1 if (MAX_VERBOSE && G.verbose)
327 #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
328 #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
329 #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
330 #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
333 static double LOG2D(int a)
336 return 1.0 / (1UL << -a);
339 static ALWAYS_INLINE double SQUARE(double x)
343 static ALWAYS_INLINE double MAXD(double a, double b)
349 static ALWAYS_INLINE double MIND(double a, double b)
355 static NOINLINE double my_SQRT(double X)
362 double Xhalf = X * 0.5;
364 /* Fast and good approximation to 1/sqrt(X), black magic */
366 /*v.i = 0x5f3759df - (v.i >> 1);*/
367 v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
368 invsqrt = v.f; /* better than 0.2% accuracy */
370 /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
371 * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
373 * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
374 * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
376 invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
377 /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
378 /* With 4 iterations, more than half results will be exact,
379 * at 6th iterations result stabilizes with about 72% results exact.
380 * We are well satisfied with 0.05% accuracy.
383 return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
385 static ALWAYS_INLINE double SQRT(double X)
387 /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
388 if (sizeof(float) != 4)
391 /* This avoids needing libm, saves about 0.5k on x86-32 */
399 gettimeofday(&tv, NULL); /* never fails */
400 G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
405 d_to_tv(double d, struct timeval *tv)
407 tv->tv_sec = (long)d;
408 tv->tv_usec = (d - tv->tv_sec) * 1000000;
412 lfp_to_d(l_fixedpt_t lfp)
415 lfp.int_partl = ntohl(lfp.int_partl);
416 lfp.fractionl = ntohl(lfp.fractionl);
417 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
421 sfp_to_d(s_fixedpt_t sfp)
424 sfp.int_parts = ntohs(sfp.int_parts);
425 sfp.fractions = ntohs(sfp.fractions);
426 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
429 #if ENABLE_FEATURE_NTPD_SERVER
434 lfp.int_partl = (uint32_t)d;
435 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
436 lfp.int_partl = htonl(lfp.int_partl);
437 lfp.fractionl = htonl(lfp.fractionl);
444 sfp.int_parts = (uint16_t)d;
445 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
446 sfp.int_parts = htons(sfp.int_parts);
447 sfp.fractions = htons(sfp.fractions);
453 dispersion(const datapoint_t *dp)
455 return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
459 root_distance(peer_t *p)
461 /* The root synchronization distance is the maximum error due to
462 * all causes of the local clock relative to the primary server.
463 * It is defined as half the total delay plus total dispersion
466 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
467 + p->lastpkt_rootdisp
468 + p->filter_dispersion
469 + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
474 set_next(peer_t *p, unsigned t)
476 p->next_action_time = G.cur_time + t;
480 * Peer clock filter and its helpers
483 filter_datapoints(peer_t *p)
487 double minoff, maxoff, wavg, sum, w;
488 double x = x; /* for compiler */
489 double oldest_off = oldest_off;
490 double oldest_age = oldest_age;
491 double newest_off = newest_off;
492 double newest_age = newest_age;
494 minoff = maxoff = p->filter_datapoint[0].d_offset;
495 for (i = 1; i < NUM_DATAPOINTS; i++) {
496 if (minoff > p->filter_datapoint[i].d_offset)
497 minoff = p->filter_datapoint[i].d_offset;
498 if (maxoff < p->filter_datapoint[i].d_offset)
499 maxoff = p->filter_datapoint[i].d_offset;
502 idx = p->datapoint_idx; /* most recent datapoint */
504 * Drop two outliers and take weighted average of the rest:
505 * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
506 * we use older6/32, not older6/64 since sum of weights should be 1:
507 * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
513 * filter_dispersion = \ -------------
520 for (i = 0; i < NUM_DATAPOINTS; i++) {
522 bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
524 p->filter_datapoint[idx].d_offset,
525 p->filter_datapoint[idx].d_dispersion, dispersion(&p->filter_datapoint[idx]),
526 G.cur_time - p->filter_datapoint[idx].d_recv_time,
527 (minoff == p->filter_datapoint[idx].d_offset || maxoff == p->filter_datapoint[idx].d_offset)
528 ? " (outlier by offset)" : ""
532 sum += dispersion(&p->filter_datapoint[idx]) / (2 << i);
534 if (minoff == p->filter_datapoint[idx].d_offset) {
535 minoff -= 1; /* so that we don't match it ever again */
537 if (maxoff == p->filter_datapoint[idx].d_offset) {
540 oldest_off = p->filter_datapoint[idx].d_offset;
541 oldest_age = G.cur_time - p->filter_datapoint[idx].d_recv_time;
544 newest_off = oldest_off;
545 newest_age = oldest_age;
552 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
554 p->filter_dispersion = sum;
555 wavg += x; /* add another older6/64 to form older6/32 */
556 /* Fix systematic underestimation with large poll intervals.
557 * Imagine that we still have a bit of uncorrected drift,
558 * and poll interval is big (say, 100 sec). Offsets form a progression:
559 * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
560 * The algorithm above drops 0.0 and 0.7 as outliers,
561 * and then we have this estimation, ~25% off from 0.7:
562 * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
564 x = oldest_age - newest_age;
566 x = newest_age / x; /* in above example, 100 / (600 - 100) */
567 if (x < 1) { /* paranoia check */
568 x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
572 p->filter_offset = wavg;
574 /* +----- -----+ ^ 1/2
578 * filter_jitter = | --- * / (avg-offset_j) |
582 * where n is the number of valid datapoints in the filter (n > 1);
583 * if filter_jitter < precision then filter_jitter = precision
586 for (i = 0; i < NUM_DATAPOINTS; i++) {
587 sum += SQUARE(wavg - p->filter_datapoint[i].d_offset);
589 sum = SQRT(sum / NUM_DATAPOINTS);
590 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
592 VERB3 bb_error_msg("filter offset:%f(corr:%e) disp:%f jitter:%f",
594 p->filter_dispersion,
600 reset_peer_stats(peer_t *p, double offset)
603 bool small_ofs = fabs(offset) < 16 * STEP_THRESHOLD;
605 for (i = 0; i < NUM_DATAPOINTS; i++) {
607 p->filter_datapoint[i].d_recv_time -= offset;
608 if (p->filter_datapoint[i].d_offset != 0) {
609 p->filter_datapoint[i].d_offset -= offset;
612 p->filter_datapoint[i].d_recv_time = G.cur_time;
613 p->filter_datapoint[i].d_offset = 0;
614 p->filter_datapoint[i].d_dispersion = MAXDISP;
618 p->lastpkt_recv_time -= offset;
620 p->reachable_bits = 0;
621 p->lastpkt_recv_time = G.cur_time;
623 filter_datapoints(p); /* recalc p->filter_xxx */
624 p->next_action_time -= offset;
625 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
633 p = xzalloc(sizeof(*p));
634 p->p_lsa = xhost2sockaddr(s, 123);
635 p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
637 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
638 p->next_action_time = G.cur_time; /* = set_next(p, 0); */
639 reset_peer_stats(p, 16 * STEP_THRESHOLD);
641 llist_add_to(&G.ntp_peers, p);
647 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
648 msg_t *msg, ssize_t len)
654 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
656 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
659 bb_perror_msg("send failed");
666 send_query_to_peer(peer_t *p)
668 /* Why do we need to bind()?
669 * See what happens when we don't bind:
671 * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
672 * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
673 * gettimeofday({1259071266, 327885}, NULL) = 0
674 * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
675 * ^^^ we sent it from some source port picked by kernel.
676 * time(NULL) = 1259071266
677 * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
678 * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
679 * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
680 * ^^^ this recv will receive packets to any local port!
682 * Uncomment this and use strace to see it in action:
684 #define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
688 len_and_sockaddr *local_lsa;
690 family = p->p_lsa->u.sa.sa_family;
691 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
692 /* local_lsa has "null" address and port 0 now.
693 * bind() ensures we have a *particular port* selected by kernel
694 * and remembered in p->p_fd, thus later recv(p->p_fd)
695 * receives only packets sent to this port.
698 xbind(fd, &local_lsa->u.sa, local_lsa->len);
700 #if ENABLE_FEATURE_IPV6
701 if (family == AF_INET)
703 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
708 * Send out a random 64-bit number as our transmit time. The NTP
709 * server will copy said number into the originate field on the
710 * response that it sends us. This is totally legal per the SNTP spec.
712 * The impact of this is two fold: we no longer send out the current
713 * system time for the world to see (which may aid an attacker), and
714 * it gives us a (not very secure) way of knowing that we're not
715 * getting spoofed by an attacker that can't capture our traffic
716 * but can spoof packets from the NTP server we're communicating with.
718 * Save the real transmit timestamp locally.
720 p->p_xmt_msg.m_xmttime.int_partl = random();
721 p->p_xmt_msg.m_xmttime.fractionl = random();
722 p->p_xmttime = gettime1900d();
724 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
725 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
729 set_next(p, RETRY_INTERVAL);
733 p->reachable_bits <<= 1;
734 VERB1 bb_error_msg("sent query to %s", p->p_dotted);
735 set_next(p, RESPONSE_INTERVAL);
739 static void run_script(const char *action, double offset)
742 char *env1, *env2, *env3, *env4;
747 argv[0] = (char*) G.script_name;
748 argv[1] = (char*) action;
751 VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
753 env1 = xasprintf("%s=%u", "stratum", G.stratum);
755 env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
757 env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
759 env4 = xasprintf("%s=%f", "offset", offset);
761 /* Other items of potential interest: selected peer,
762 * rootdelay, reftime, rootdisp, refid, ntp_status,
763 * last_update_offset, last_update_recv_time, discipline_jitter,
764 * how many peers have reachable_bits = 0?
767 /* Don't want to wait: it may run hwclock --systohc, and that
768 * may take some time (seconds): */
769 /*wait4pid(spawn(argv));*/
773 unsetenv("freq_drift_ppm");
774 unsetenv("poll_interval");
781 G.last_script_run = G.cur_time;
785 step_time(double offset)
793 gettimeofday(&tv, NULL); /* never fails */
794 dtime = offset + tv.tv_sec;
795 dtime += 1.0e-6 * tv.tv_usec;
798 if (settimeofday(&tv, NULL) == -1)
799 bb_perror_msg_and_die("settimeofday");
802 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
804 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
806 /* Correct various fields which contain time-relative values: */
808 /* p->lastpkt_recv_time, p->next_action_time and such: */
809 for (item = G.ntp_peers; item != NULL; item = item->link) {
810 peer_t *pp = (peer_t *) item->data;
811 reset_peer_stats(pp, offset);
814 G.cur_time -= offset;
815 G.last_update_recv_time -= offset;
820 * Selection and clustering, and their helpers
826 double opt_rd; /* optimization */
829 compare_point_edge(const void *aa, const void *bb)
831 const point_t *a = aa;
832 const point_t *b = bb;
833 if (a->edge < b->edge) {
836 return (a->edge > b->edge);
843 compare_survivor_metric(const void *aa, const void *bb)
845 const survivor_t *a = aa;
846 const survivor_t *b = bb;
847 if (a->metric < b->metric) {
850 return (a->metric > b->metric);
853 fit(peer_t *p, double rd)
855 if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
856 /* One or zero bits in reachable_bits */
857 VERB3 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
860 #if 0 /* we filter out such packets earlier */
861 if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
862 || p->lastpkt_stratum >= MAXSTRAT
864 VERB3 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
868 /* rd is root_distance(p) */
869 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
870 VERB3 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
874 // /* Do we have a loop? */
875 // if (p->refid == p->dstaddr || p->refid == s.refid)
880 select_and_cluster(void)
885 int size = 3 * G.peer_cnt;
886 /* for selection algorithm */
888 unsigned num_points, num_candidates;
890 unsigned num_falsetickers;
891 /* for cluster algorithm */
892 survivor_t survivor[size];
893 unsigned num_survivors;
899 if (G.initial_poll_complete) while (item != NULL) {
902 p = (peer_t *) item->data;
903 rd = root_distance(p);
904 offset = p->filter_offset;
910 VERB4 bb_error_msg("interval: [%f %f %f] %s",
916 point[num_points].p = p;
917 point[num_points].type = -1;
918 point[num_points].edge = offset - rd;
919 point[num_points].opt_rd = rd;
921 point[num_points].p = p;
922 point[num_points].type = 0;
923 point[num_points].edge = offset;
924 point[num_points].opt_rd = rd;
926 point[num_points].p = p;
927 point[num_points].type = 1;
928 point[num_points].edge = offset + rd;
929 point[num_points].opt_rd = rd;
933 num_candidates = num_points / 3;
934 if (num_candidates == 0) {
935 VERB3 bb_error_msg("no valid datapoints, no peer selected");
938 //TODO: sorting does not seem to be done in reference code
939 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
941 /* Start with the assumption that there are no falsetickers.
942 * Attempt to find a nonempty intersection interval containing
943 * the midpoints of all truechimers.
944 * If a nonempty interval cannot be found, increase the number
945 * of assumed falsetickers by one and try again.
946 * If a nonempty interval is found and the number of falsetickers
947 * is less than the number of truechimers, a majority has been found
948 * and the midpoint of each truechimer represents
949 * the candidates available to the cluster algorithm.
951 num_falsetickers = 0;
954 unsigned num_midpoints = 0;
959 for (i = 0; i < num_points; i++) {
961 * if (point[i].type == -1) c++;
962 * if (point[i].type == 1) c--;
963 * and it's simpler to do it this way:
966 if (c >= num_candidates - num_falsetickers) {
967 /* If it was c++ and it got big enough... */
971 if (point[i].type == 0)
975 for (i = num_points-1; i >= 0; i--) {
977 if (c >= num_candidates - num_falsetickers) {
978 high = point[i].edge;
981 if (point[i].type == 0)
984 /* If the number of midpoints is greater than the number
985 * of allowed falsetickers, the intersection contains at
986 * least one truechimer with no midpoint - bad.
987 * Also, interval should be nonempty.
989 if (num_midpoints <= num_falsetickers && low < high)
992 if (num_falsetickers * 2 >= num_candidates) {
993 VERB3 bb_error_msg("too many falsetickers:%d (candidates:%d), no peer selected",
994 num_falsetickers, num_candidates);
998 VERB3 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
999 low, high, num_candidates, num_falsetickers);
1003 /* Construct a list of survivors (p, metric)
1004 * from the chime list, where metric is dominated
1005 * first by stratum and then by root distance.
1006 * All other things being equal, this is the order of preference.
1009 for (i = 0; i < num_points; i++) {
1010 if (point[i].edge < low || point[i].edge > high)
1013 survivor[num_survivors].p = p;
1014 /* x.opt_rd == root_distance(p); */
1015 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
1016 VERB4 bb_error_msg("survivor[%d] metric:%f peer:%s",
1017 num_survivors, survivor[num_survivors].metric, p->p_dotted);
1020 /* There must be at least MIN_SELECTED survivors to satisfy the
1021 * correctness assertions. Ordinarily, the Byzantine criteria
1022 * require four survivors, but for the demonstration here, one
1025 if (num_survivors < MIN_SELECTED) {
1026 VERB3 bb_error_msg("num_survivors %d < %d, no peer selected",
1027 num_survivors, MIN_SELECTED);
1031 //looks like this is ONLY used by the fact that later we pick survivor[0].
1032 //we can avoid sorting then, just find the minimum once!
1033 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1035 /* For each association p in turn, calculate the selection
1036 * jitter p->sjitter as the square root of the sum of squares
1037 * (p->offset - q->offset) over all q associations. The idea is
1038 * to repeatedly discard the survivor with maximum selection
1039 * jitter until a termination condition is met.
1042 unsigned max_idx = max_idx;
1043 double max_selection_jitter = max_selection_jitter;
1044 double min_jitter = min_jitter;
1046 if (num_survivors <= MIN_CLUSTERED) {
1047 VERB3 bb_error_msg("num_survivors %d <= %d, not discarding more",
1048 num_survivors, MIN_CLUSTERED);
1052 /* To make sure a few survivors are left
1053 * for the clustering algorithm to chew on,
1054 * we stop if the number of survivors
1055 * is less than or equal to MIN_CLUSTERED (3).
1057 for (i = 0; i < num_survivors; i++) {
1058 double selection_jitter_sq;
1061 if (i == 0 || p->filter_jitter < min_jitter)
1062 min_jitter = p->filter_jitter;
1064 selection_jitter_sq = 0;
1065 for (j = 0; j < num_survivors; j++) {
1066 peer_t *q = survivor[j].p;
1067 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1069 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1070 max_selection_jitter = selection_jitter_sq;
1073 VERB5 bb_error_msg("survivor %d selection_jitter^2:%f",
1074 i, selection_jitter_sq);
1076 max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
1077 VERB4 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1078 max_idx, max_selection_jitter, min_jitter);
1080 /* If the maximum selection jitter is less than the
1081 * minimum peer jitter, then tossing out more survivors
1082 * will not lower the minimum peer jitter, so we might
1085 if (max_selection_jitter < min_jitter) {
1086 VERB3 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1087 max_selection_jitter, min_jitter, num_survivors);
1091 /* Delete survivor[max_idx] from the list
1092 * and go around again.
1094 VERB5 bb_error_msg("dropping survivor %d", max_idx);
1096 while (max_idx < num_survivors) {
1097 survivor[max_idx] = survivor[max_idx + 1];
1103 /* Combine the offsets of the clustering algorithm survivors
1104 * using a weighted average with weight determined by the root
1105 * distance. Compute the selection jitter as the weighted RMS
1106 * difference between the first survivor and the remaining
1107 * survivors. In some cases the inherent clock jitter can be
1108 * reduced by not using this algorithm, especially when frequent
1109 * clockhopping is involved. bbox: thus we don't do it.
1113 for (i = 0; i < num_survivors; i++) {
1115 x = root_distance(p);
1117 z += p->filter_offset / x;
1118 w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1120 //G.cluster_offset = z / y;
1121 //G.cluster_jitter = SQRT(w / y);
1124 /* Pick the best clock. If the old system peer is on the list
1125 * and at the same stratum as the first survivor on the list,
1126 * then don't do a clock hop. Otherwise, select the first
1127 * survivor on the list as the new system peer.
1130 if (G.last_update_peer
1131 && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1133 /* Starting from 1 is ok here */
1134 for (i = 1; i < num_survivors; i++) {
1135 if (G.last_update_peer == survivor[i].p) {
1136 VERB4 bb_error_msg("keeping old synced peer");
1137 p = G.last_update_peer;
1142 G.last_update_peer = p;
1144 VERB3 bb_error_msg("selected peer %s filter_offset:%f age:%f",
1147 G.cur_time - p->lastpkt_recv_time
1154 * Local clock discipline and its helpers
1157 set_new_values(int disc_state, double offset, double recv_time)
1159 /* Enter new state and set state variables. Note we use the time
1160 * of the last clock filter sample, which must be earlier than
1163 VERB3 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
1164 disc_state, offset, recv_time);
1165 G.discipline_state = disc_state;
1166 G.last_update_offset = offset;
1167 G.last_update_recv_time = recv_time;
1169 /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
1171 update_local_clock(peer_t *p)
1174 long old_tmx_offset;
1176 /* Note: can use G.cluster_offset instead: */
1177 double offset = p->filter_offset;
1178 double recv_time = p->lastpkt_recv_time;
1180 #if !USING_KERNEL_PLL_LOOP
1183 double since_last_update;
1184 double etemp, dtemp;
1186 abs_offset = fabs(offset);
1189 /* If needed, -S script can detect this by looking at $offset
1190 * env var and kill parent */
1191 /* If the offset is too large, give up and go home */
1192 if (abs_offset > PANIC_THRESHOLD) {
1193 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1197 /* If this is an old update, for instance as the result
1198 * of a system peer change, avoid it. We never use
1199 * an old sample or the same sample twice.
1201 if (recv_time <= G.last_update_recv_time) {
1202 VERB3 bb_error_msg("same or older datapoint: %f >= %f, not using it",
1203 G.last_update_recv_time, recv_time);
1204 return 0; /* "leave poll interval as is" */
1207 /* Clock state machine transition function. This is where the
1208 * action is and defines how the system reacts to large time
1209 * and frequency errors.
1211 since_last_update = recv_time - G.reftime;
1212 #if !USING_KERNEL_PLL_LOOP
1215 #if USING_INITIAL_FREQ_ESTIMATION
1216 if (G.discipline_state == STATE_FREQ) {
1217 /* Ignore updates until the stepout threshold */
1218 if (since_last_update < WATCH_THRESHOLD) {
1219 VERB3 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1220 WATCH_THRESHOLD - since_last_update);
1221 return 0; /* "leave poll interval as is" */
1223 # if !USING_KERNEL_PLL_LOOP
1224 freq_drift = (offset - G.last_update_offset) / since_last_update;
1229 /* There are two main regimes: when the
1230 * offset exceeds the step threshold and when it does not.
1232 if (abs_offset > STEP_THRESHOLD) {
1233 switch (G.discipline_state) {
1235 /* The first outlyer: ignore it, switch to SPIK state */
1236 VERB3 bb_error_msg("offset:%f - spike detected", offset);
1237 G.discipline_state = STATE_SPIK;
1238 return -1; /* "decrease poll interval" */
1241 /* Ignore succeeding outlyers until either an inlyer
1242 * is found or the stepout threshold is exceeded.
1244 if (since_last_update < WATCH_THRESHOLD) {
1245 VERB3 bb_error_msg("spike detected, datapoint ignored, %f sec remains",
1246 WATCH_THRESHOLD - since_last_update);
1247 return -1; /* "decrease poll interval" */
1249 /* fall through: we need to step */
1252 /* Step the time and clamp down the poll interval.
1254 * In NSET state an initial frequency correction is
1255 * not available, usually because the frequency file has
1256 * not yet been written. Since the time is outside the
1257 * capture range, the clock is stepped. The frequency
1258 * will be set directly following the stepout interval.
1260 * In FSET state the initial frequency has been set
1261 * from the frequency file. Since the time is outside
1262 * the capture range, the clock is stepped immediately,
1263 * rather than after the stepout interval. Guys get
1264 * nervous if it takes 17 minutes to set the clock for
1267 * In SPIK state the stepout threshold has expired and
1268 * the phase is still above the step threshold. Note
1269 * that a single spike greater than the step threshold
1270 * is always suppressed, even at the longer poll
1273 VERB3 bb_error_msg("stepping time by %f; poll_exp=MINPOLL", offset);
1275 if (option_mask32 & OPT_q) {
1276 /* We were only asked to set time once. Done. */
1280 G.polladj_count = 0;
1281 G.poll_exp = MINPOLL;
1282 G.stratum = MAXSTRAT;
1284 run_script("step", offset);
1286 #if USING_INITIAL_FREQ_ESTIMATION
1287 if (G.discipline_state == STATE_NSET) {
1288 set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1289 return 1; /* "ok to increase poll interval" */
1292 set_new_values(STATE_SYNC, /*offset:*/ 0, recv_time);
1294 } else { /* abs_offset <= STEP_THRESHOLD */
1296 if (G.poll_exp < MINPOLL && G.initial_poll_complete) {
1297 VERB3 bb_error_msg("small offset:%f, disabling burst mode", offset);
1298 G.polladj_count = 0;
1299 G.poll_exp = MINPOLL;
1302 /* Compute the clock jitter as the RMS of exponentially
1303 * weighted offset differences. Used by the poll adjust code.
1305 etemp = SQUARE(G.discipline_jitter);
1306 dtemp = SQUARE(MAXD(fabs(offset - G.last_update_offset), G_precision_sec));
1307 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1308 VERB3 bb_error_msg("discipline jitter=%f", G.discipline_jitter);
1310 switch (G.discipline_state) {
1312 if (option_mask32 & OPT_q) {
1313 /* We were only asked to set time once.
1314 * The clock is precise enough, no need to step.
1318 #if USING_INITIAL_FREQ_ESTIMATION
1319 /* This is the first update received and the frequency
1320 * has not been initialized. The first thing to do
1321 * is directly measure the oscillator frequency.
1323 set_new_values(STATE_FREQ, offset, recv_time);
1325 set_new_values(STATE_SYNC, offset, recv_time);
1327 VERB3 bb_error_msg("transitioning to FREQ, datapoint ignored");
1328 return 0; /* "leave poll interval as is" */
1330 #if 0 /* this is dead code for now */
1332 /* This is the first update and the frequency
1333 * has been initialized. Adjust the phase, but
1334 * don't adjust the frequency until the next update.
1336 set_new_values(STATE_SYNC, offset, recv_time);
1337 /* freq_drift remains 0 */
1341 #if USING_INITIAL_FREQ_ESTIMATION
1343 /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1344 * Correct the phase and frequency and switch to SYNC state.
1345 * freq_drift was already estimated (see code above)
1347 set_new_values(STATE_SYNC, offset, recv_time);
1352 #if !USING_KERNEL_PLL_LOOP
1353 /* Compute freq_drift due to PLL and FLL contributions.
1355 * The FLL and PLL frequency gain constants
1356 * depend on the poll interval and Allan
1357 * intercept. The FLL is not used below one-half
1358 * the Allan intercept. Above that the loop gain
1359 * increases in steps to 1 / AVG.
1361 if ((1 << G.poll_exp) > ALLAN / 2) {
1362 etemp = FLL - G.poll_exp;
1365 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1367 /* For the PLL the integration interval
1368 * (numerator) is the minimum of the update
1369 * interval and poll interval. This allows
1370 * oversampling, but not undersampling.
1372 etemp = MIND(since_last_update, (1 << G.poll_exp));
1373 dtemp = (4 * PLL) << G.poll_exp;
1374 freq_drift += offset * etemp / SQUARE(dtemp);
1376 set_new_values(STATE_SYNC, offset, recv_time);
1379 if (G.stratum != p->lastpkt_stratum + 1) {
1380 G.stratum = p->lastpkt_stratum + 1;
1381 run_script("stratum", offset);
1385 G.reftime = G.cur_time;
1386 G.ntp_status = p->lastpkt_status;
1387 G.refid = p->lastpkt_refid;
1388 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1389 dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
1390 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
1391 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1392 VERB3 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1394 /* We are in STATE_SYNC now, but did not do adjtimex yet.
1395 * (Any other state does not reach this, they all return earlier)
1396 * By this time, freq_drift and G.last_update_offset are set
1397 * to values suitable for adjtimex.
1399 #if !USING_KERNEL_PLL_LOOP
1400 /* Calculate the new frequency drift and frequency stability (wander).
1401 * Compute the clock wander as the RMS of exponentially weighted
1402 * frequency differences. This is not used directly, but can,
1403 * along with the jitter, be a highly useful monitoring and
1406 dtemp = G.discipline_freq_drift + freq_drift;
1407 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1408 etemp = SQUARE(G.discipline_wander);
1409 dtemp = SQUARE(dtemp);
1410 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1412 VERB3 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1413 G.discipline_freq_drift,
1414 (long)(G.discipline_freq_drift * 65536e6),
1416 G.discipline_wander);
1419 memset(&tmx, 0, sizeof(tmx));
1420 if (adjtimex(&tmx) < 0)
1421 bb_perror_msg_and_die("adjtimex");
1422 VERB3 bb_error_msg("p adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1423 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1427 if (!G.adjtimex_was_done) {
1428 G.adjtimex_was_done = 1;
1429 /* When we use adjtimex for the very first time,
1430 * we need to ADD to pre-existing tmx.offset - it may be !0
1432 memset(&tmx, 0, sizeof(tmx));
1433 if (adjtimex(&tmx) < 0)
1434 bb_perror_msg_and_die("adjtimex");
1435 old_tmx_offset = tmx.offset;
1437 memset(&tmx, 0, sizeof(tmx));
1439 //doesn't work, offset remains 0 (!) in kernel:
1440 //ntpd: set adjtimex freq:1786097 tmx.offset:77487
1441 //ntpd: prev adjtimex freq:1786097 tmx.offset:0
1442 //ntpd: cur adjtimex freq:1786097 tmx.offset:0
1443 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1444 /* 65536 is one ppm */
1445 tmx.freq = G.discipline_freq_drift * 65536e6;
1446 tmx.offset = G.last_update_offset * 1000000; /* usec */
1448 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1449 tmx.offset = (G.last_update_offset * 1000000) /* usec */
1450 /* + (G.last_update_offset < 0 ? -0.5 : 0.5) - too small to bother */
1451 + old_tmx_offset; /* almost always 0 */
1452 tmx.status = STA_PLL;
1453 if (G.ntp_status & LI_PLUSSEC)
1454 tmx.status |= STA_INS;
1455 if (G.ntp_status & LI_MINUSSEC)
1456 tmx.status |= STA_DEL;
1457 tmx.constant = G.poll_exp - 4;
1458 //tmx.esterror = (u_int32)(clock_jitter * 1e6);
1459 //tmx.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1460 rc = adjtimex(&tmx);
1462 bb_perror_msg_and_die("adjtimex");
1463 /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
1464 * Not sure why. Perhaps it is normal.
1466 VERB3 bb_error_msg("adjtimex:%d freq:%ld offset:%ld constant:%ld status:0x%x",
1467 rc, tmx.freq, tmx.offset, tmx.constant, tmx.status);
1470 /* always gives the same output as above msg */
1471 memset(&tmx, 0, sizeof(tmx));
1472 if (adjtimex(&tmx) < 0)
1473 bb_perror_msg_and_die("adjtimex");
1474 VERB3 bb_error_msg("c adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1475 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1478 G.kernel_freq_drift = tmx.freq / 65536;
1479 VERB2 bb_error_msg("update peer:%s, offset:%f, clock drift:%ld ppm",
1480 p->p_dotted, G.last_update_offset, G.kernel_freq_drift);
1482 return 1; /* "ok to increase poll interval" */
1487 * We've got a new reply packet from a peer, process it
1491 retry_interval(void)
1493 /* Local problem, want to retry soon */
1494 unsigned interval, r;
1495 interval = RETRY_INTERVAL;
1497 interval += r % (unsigned)(RETRY_INTERVAL / 4);
1498 VERB3 bb_error_msg("chose retry interval:%u", interval);
1502 poll_interval(int exponent)
1504 unsigned interval, r;
1505 exponent = G.poll_exp + exponent;
1508 interval = 1 << exponent;
1510 interval += ((r & (interval-1)) >> 4) + ((r >> 8) & 1); /* + 1/16 of interval, max */
1511 VERB3 bb_error_msg("chose poll interval:%u (poll_exp:%d exp:%d)", interval, G.poll_exp, exponent);
1514 static NOINLINE void
1515 recv_and_process_peer_pkt(peer_t *p)
1520 double T1, T2, T3, T4;
1522 datapoint_t *datapoint;
1525 /* We can recvfrom here and check from.IP, but some multihomed
1526 * ntp servers reply from their *other IP*.
1527 * TODO: maybe we should check at least what we can: from.port == 123?
1529 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1531 bb_perror_msg("recv(%s) error", p->p_dotted);
1532 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
1533 || errno == ENETUNREACH || errno == ENETDOWN
1534 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
1537 //TODO: always do this?
1538 interval = retry_interval();
1539 goto set_next_and_close_sock;
1544 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1545 bb_error_msg("malformed packet received from %s", p->p_dotted);
1549 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1550 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1555 if ((msg.m_status & LI_ALARM) == LI_ALARM
1556 || msg.m_stratum == 0
1557 || msg.m_stratum > NTP_MAXSTRATUM
1559 // TODO: stratum 0 responses may have commands in 32-bit m_refid field:
1560 // "DENY", "RSTR" - peer does not like us at all
1561 // "RATE" - peer is overloaded, reduce polling freq
1562 interval = poll_interval(0);
1563 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
1564 goto set_next_and_close_sock;
1567 // /* Verify valid root distance */
1568 // if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
1569 // return; /* invalid header values */
1571 p->lastpkt_status = msg.m_status;
1572 p->lastpkt_stratum = msg.m_stratum;
1573 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1574 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1575 p->lastpkt_refid = msg.m_refid;
1578 * From RFC 2030 (with a correction to the delay math):
1580 * Timestamp Name ID When Generated
1581 * ------------------------------------------------------------
1582 * Originate Timestamp T1 time request sent by client
1583 * Receive Timestamp T2 time request received by server
1584 * Transmit Timestamp T3 time reply sent by server
1585 * Destination Timestamp T4 time reply received by client
1587 * The roundtrip delay and local clock offset are defined as
1589 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
1592 T2 = lfp_to_d(msg.m_rectime);
1593 T3 = lfp_to_d(msg.m_xmttime);
1596 p->lastpkt_recv_time = T4;
1598 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
1599 p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
1600 datapoint = &p->filter_datapoint[p->datapoint_idx];
1601 datapoint->d_recv_time = T4;
1602 datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
1603 /* The delay calculation is a special case. In cases where the
1604 * server and client clocks are running at different rates and
1605 * with very fast networks, the delay can appear negative. In
1606 * order to avoid violating the Principle of Least Astonishment,
1607 * the delay is clamped not less than the system precision.
1609 p->lastpkt_delay = (T4 - T1) - (T3 - T2);
1610 if (p->lastpkt_delay < G_precision_sec)
1611 p->lastpkt_delay = G_precision_sec;
1612 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
1613 if (!p->reachable_bits) {
1614 /* 1st datapoint ever - replicate offset in every element */
1616 for (i = 1; i < NUM_DATAPOINTS; i++) {
1617 p->filter_datapoint[i].d_offset = datapoint->d_offset;
1621 p->reachable_bits |= 1;
1622 if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
1623 bb_error_msg("reply from %s: reach 0x%02x offset %f delay %f status 0x%02x strat %d refid 0x%08x rootdelay %f",
1626 datapoint->d_offset,
1631 p->lastpkt_rootdelay
1632 /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
1633 * m_reftime, m_orgtime, m_rectime, m_xmttime
1638 /* Muck with statictics and update the clock */
1639 filter_datapoints(p);
1640 q = select_and_cluster();
1644 if (!(option_mask32 & OPT_w)) {
1645 rc = update_local_clock(q);
1646 /* If drift is dangerously large, immediately
1647 * drop poll interval one step down.
1649 if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
1650 VERB3 bb_error_msg("offset:%f > POLLDOWN_OFFSET", q->filter_offset);
1655 /* else: no peer selected, rc = -1: we want to poll more often */
1658 /* Adjust the poll interval by comparing the current offset
1659 * with the clock jitter. If the offset is less than
1660 * the clock jitter times a constant, then the averaging interval
1661 * is increased, otherwise it is decreased. A bit of hysteresis
1662 * helps calm the dance. Works best using burst mode.
1665 bb_error_msg("offset:%f POLLADJ_GATE*discipline_jitter:%f poll:%s",
1666 q->filter_offset, POLLADJ_GATE * G.discipline_jitter,
1667 fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter
1671 if (rc > 0 && fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter) {
1672 /* was += G.poll_exp but it is a bit
1673 * too optimistic for my taste at high poll_exp's */
1674 G.polladj_count += MINPOLL;
1675 if (G.polladj_count > POLLADJ_LIMIT) {
1676 G.polladj_count = 0;
1677 if (G.poll_exp < MAXPOLL) {
1679 VERB3 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1680 G.discipline_jitter, G.poll_exp);
1683 VERB3 bb_error_msg("polladj: incr:%d", G.polladj_count);
1686 G.polladj_count -= G.poll_exp * 2;
1687 if (G.polladj_count < -POLLADJ_LIMIT || G.poll_exp >= BIGPOLL) {
1689 G.polladj_count = 0;
1690 if (G.poll_exp > MINPOLL) {
1694 /* Correct p->next_action_time in each peer
1695 * which waits for sending, so that they send earlier.
1696 * Old pp->next_action_time are on the order
1697 * of t + (1 << old_poll_exp) + small_random,
1698 * we simply need to subtract ~half of that.
1700 for (item = G.ntp_peers; item != NULL; item = item->link) {
1701 peer_t *pp = (peer_t *) item->data;
1703 pp->next_action_time -= (1 << G.poll_exp);
1705 VERB3 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1706 G.discipline_jitter, G.poll_exp);
1709 VERB3 bb_error_msg("polladj: decr:%d", G.polladj_count);
1714 /* Decide when to send new query for this peer */
1715 interval = poll_interval(0);
1717 set_next_and_close_sock:
1718 set_next(p, interval);
1719 /* We do not expect any more packets from this peer for now.
1720 * Closing the socket informs kernel about it.
1721 * We open a new socket when we send a new query.
1729 #if ENABLE_FEATURE_NTPD_SERVER
1730 static NOINLINE void
1731 recv_and_process_client_pkt(void /*int fd*/)
1735 len_and_sockaddr *to;
1736 struct sockaddr *from;
1738 uint8_t query_status;
1739 l_fixedpt_t query_xmttime;
1741 to = get_sock_lsa(G.listen_fd);
1742 from = xzalloc(to->len);
1744 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
1745 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1748 if (errno == EAGAIN)
1750 bb_perror_msg_and_die("recv");
1752 addr = xmalloc_sockaddr2dotted_noport(from);
1753 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
1758 query_status = msg.m_status;
1759 query_xmttime = msg.m_xmttime;
1761 /* Build a reply packet */
1762 memset(&msg, 0, sizeof(msg));
1763 msg.m_status = G.stratum < MAXSTRAT ? G.ntp_status : LI_ALARM;
1764 msg.m_status |= (query_status & VERSION_MASK);
1765 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
1766 MODE_SERVER : MODE_SYM_PAS;
1767 msg.m_stratum = G.stratum;
1768 msg.m_ppoll = G.poll_exp;
1769 msg.m_precision_exp = G_precision_exp;
1770 /* this time was obtained between poll() and recv() */
1771 msg.m_rectime = d_to_lfp(G.cur_time);
1772 msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
1773 msg.m_reftime = d_to_lfp(G.reftime);
1774 msg.m_orgtime = query_xmttime;
1775 msg.m_rootdelay = d_to_sfp(G.rootdelay);
1776 //simple code does not do this, fix simple code!
1777 msg.m_rootdisp = d_to_sfp(G.rootdisp);
1778 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
1779 msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
1781 /* We reply from the local address packet was sent to,
1782 * this makes to/from look swapped here: */
1783 do_sendto(G.listen_fd,
1784 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
1793 /* Upstream ntpd's options:
1795 * -4 Force DNS resolution of host names to the IPv4 namespace.
1796 * -6 Force DNS resolution of host names to the IPv6 namespace.
1797 * -a Require cryptographic authentication for broadcast client,
1798 * multicast client and symmetric passive associations.
1799 * This is the default.
1800 * -A Do not require cryptographic authentication for broadcast client,
1801 * multicast client and symmetric passive associations.
1802 * This is almost never a good idea.
1803 * -b Enable the client to synchronize to broadcast servers.
1805 * Specify the name and path of the configuration file,
1806 * default /etc/ntp.conf
1807 * -d Specify debugging mode. This option may occur more than once,
1808 * with each occurrence indicating greater detail of display.
1810 * Specify debugging level directly.
1812 * Specify the name and path of the frequency file.
1813 * This is the same operation as the "driftfile FILE"
1814 * configuration command.
1815 * -g Normally, ntpd exits with a message to the system log
1816 * if the offset exceeds the panic threshold, which is 1000 s
1817 * by default. This option allows the time to be set to any value
1818 * without restriction; however, this can happen only once.
1819 * If the threshold is exceeded after that, ntpd will exit
1820 * with a message to the system log. This option can be used
1821 * with the -q and -x options. See the tinker command for other options.
1823 * Chroot the server to the directory jaildir. This option also implies
1824 * that the server attempts to drop root privileges at startup
1825 * (otherwise, chroot gives very little additional security).
1826 * You may need to also specify a -u option.
1828 * Specify the name and path of the symmetric key file,
1829 * default /etc/ntp/keys. This is the same operation
1830 * as the "keys FILE" configuration command.
1832 * Specify the name and path of the log file. The default
1833 * is the system log file. This is the same operation as
1834 * the "logfile FILE" configuration command.
1835 * -L Do not listen to virtual IPs. The default is to listen.
1837 * -N To the extent permitted by the operating system,
1838 * run the ntpd at the highest priority.
1840 * Specify the name and path of the file used to record the ntpd
1841 * process ID. This is the same operation as the "pidfile FILE"
1842 * configuration command.
1844 * To the extent permitted by the operating system,
1845 * run the ntpd at the specified priority.
1846 * -q Exit the ntpd just after the first time the clock is set.
1847 * This behavior mimics that of the ntpdate program, which is
1848 * to be retired. The -g and -x options can be used with this option.
1849 * Note: The kernel time discipline is disabled with this option.
1851 * Specify the default propagation delay from the broadcast/multicast
1852 * server to this client. This is necessary only if the delay
1853 * cannot be computed automatically by the protocol.
1855 * Specify the directory path for files created by the statistics
1856 * facility. This is the same operation as the "statsdir DIR"
1857 * configuration command.
1859 * Add a key number to the trusted key list. This option can occur
1862 * Specify a user, and optionally a group, to switch to.
1865 * Add a system variable listed by default.
1866 * -x Normally, the time is slewed if the offset is less than the step
1867 * threshold, which is 128 ms by default, and stepped if above
1868 * the threshold. This option sets the threshold to 600 s, which is
1869 * well within the accuracy window to set the clock manually.
1870 * Note: since the slew rate of typical Unix kernels is limited
1871 * to 0.5 ms/s, each second of adjustment requires an amortization
1872 * interval of 2000 s. Thus, an adjustment as much as 600 s
1873 * will take almost 14 days to complete. This option can be used
1874 * with the -g and -q options. See the tinker command for other options.
1875 * Note: The kernel time discipline is disabled with this option.
1878 /* By doing init in a separate function we decrease stack usage
1881 static NOINLINE void ntp_init(char **argv)
1889 bb_error_msg_and_die(bb_msg_you_must_be_root);
1891 /* Set some globals */
1892 G.stratum = MAXSTRAT;
1894 G.poll_exp = BURSTPOLL; /* speeds up initial sync */
1895 G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
1899 opt_complementary = "dd:p::wn"; /* d: counter; p: list; -w implies -n */
1900 opts = getopt32(argv,
1902 "wp:S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
1904 "46aAbgL", /* compat, ignored */
1905 &peers, &G.script_name, &G.verbose);
1906 if (!(opts & (OPT_p|OPT_l)))
1908 // if (opts & OPT_x) /* disable stepping, only slew is allowed */
1909 // G.time_was_stepped = 1;
1911 add_peers(llist_pop(&peers));
1912 if (!(opts & OPT_n)) {
1913 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
1914 logmode = LOGMODE_NONE;
1916 #if ENABLE_FEATURE_NTPD_SERVER
1919 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
1920 socket_want_pktinfo(G.listen_fd);
1921 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
1924 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
1926 setpriority(PRIO_PROCESS, 0, -15);
1928 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
1929 /* Removed SIGHUP here: */
1930 bb_signals((1 << SIGPIPE) | (1 << SIGCHLD), SIG_IGN);
1933 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
1934 int ntpd_main(int argc UNUSED_PARAM, char **argv)
1942 memset(&G, 0, sizeof(G));
1943 SET_PTR_TO_GLOBALS(&G);
1947 /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
1948 cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
1949 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
1950 pfd = xzalloc(sizeof(pfd[0]) * cnt);
1952 /* Countdown: we never sync before we sent INITIAL_SAMLPES+1
1953 * packets to each peer.
1954 * NB: if some peer is not responding, we may end up sending
1955 * fewer packets to it and more to other peers.
1956 * NB2: sync usually happens using INITIAL_SAMLPES packets,
1957 * since last reply does not come back instantaneously.
1959 cnt = G.peer_cnt * (INITIAL_SAMLPES + 1);
1961 while (!bb_got_signal) {
1967 /* Nothing between here and poll() blocks for any significant time */
1969 nextaction = G.cur_time + 3600;
1972 #if ENABLE_FEATURE_NTPD_SERVER
1973 if (G.listen_fd != -1) {
1974 pfd[0].fd = G.listen_fd;
1975 pfd[0].events = POLLIN;
1979 /* Pass over peer list, send requests, time out on receives */
1980 for (item = G.ntp_peers; item != NULL; item = item->link) {
1981 peer_t *p = (peer_t *) item->data;
1983 if (p->next_action_time <= G.cur_time) {
1984 if (p->p_fd == -1) {
1985 /* Time to send new req */
1987 G.initial_poll_complete = 1;
1989 send_query_to_peer(p);
1991 /* Timed out waiting for reply */
1994 timeout = poll_interval(-2); /* -2: try a bit sooner */
1995 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
1996 p->p_dotted, p->reachable_bits, timeout);
1997 set_next(p, timeout);
2001 if (p->next_action_time < nextaction)
2002 nextaction = p->next_action_time;
2005 /* Wait for reply from this peer */
2006 pfd[i].fd = p->p_fd;
2007 pfd[i].events = POLLIN;
2013 timeout = nextaction - G.cur_time;
2016 timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
2018 /* Here we may block */
2019 VERB2 bb_error_msg("poll %us, sockets:%u, poll interval:%us", timeout, i, 1 << G.poll_exp);
2020 nfds = poll(pfd, i, timeout * 1000);
2021 gettime1900d(); /* sets G.cur_time */
2023 if (G.adjtimex_was_done
2024 && G.cur_time - G.last_script_run > 11*60
2026 /* Useful for updating battery-backed RTC and such */
2027 run_script("periodic", G.last_update_offset);
2028 gettime1900d(); /* sets G.cur_time */
2033 /* Process any received packets */
2035 #if ENABLE_FEATURE_NTPD_SERVER
2036 if (G.listen_fd != -1) {
2037 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
2039 recv_and_process_client_pkt(/*G.listen_fd*/);
2040 gettime1900d(); /* sets G.cur_time */
2045 for (; nfds != 0 && j < i; j++) {
2046 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
2048 recv_and_process_peer_pkt(idx2peer[j]);
2049 gettime1900d(); /* sets G.cur_time */
2052 } /* while (!bb_got_signal) */
2054 kill_myself_with_sig(bb_got_signal);
2062 /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
2064 /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
2068 direct_freq(double fp_offset)
2073 * If the kernel is enabled, we need the residual offset to
2074 * calculate the frequency correction.
2076 if (pll_control && kern_enable) {
2077 memset(&ntv, 0, sizeof(ntv));
2080 clock_offset = ntv.offset / 1e9;
2081 #else /* STA_NANO */
2082 clock_offset = ntv.offset / 1e6;
2083 #endif /* STA_NANO */
2084 drift_comp = FREQTOD(ntv.freq);
2086 #endif /* KERNEL_PLL */
2087 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2093 set_freq(double freq) /* frequency update */
2101 * If the kernel is enabled, update the kernel frequency.
2103 if (pll_control && kern_enable) {
2104 memset(&ntv, 0, sizeof(ntv));
2105 ntv.modes = MOD_FREQUENCY;
2106 ntv.freq = DTOFREQ(drift_comp);
2108 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2109 report_event(EVNT_FSET, NULL, tbuf);
2111 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2112 report_event(EVNT_FSET, NULL, tbuf);
2114 #else /* KERNEL_PLL */
2115 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2116 report_event(EVNT_FSET, NULL, tbuf);
2117 #endif /* KERNEL_PLL */
2126 * This code segment works when clock adjustments are made using
2127 * precision time kernel support and the ntp_adjtime() system
2128 * call. This support is available in Solaris 2.6 and later,
2129 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
2130 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
2131 * DECstation 5000/240 and Alpha AXP, additional kernel
2132 * modifications provide a true microsecond clock and nanosecond
2133 * clock, respectively.
2135 * Important note: The kernel discipline is used only if the
2136 * step threshold is less than 0.5 s, as anything higher can
2137 * lead to overflow problems. This might occur if some misguided
2138 * lad set the step threshold to something ridiculous.
2140 if (pll_control && kern_enable) {
2142 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2145 * We initialize the structure for the ntp_adjtime()
2146 * system call. We have to convert everything to
2147 * microseconds or nanoseconds first. Do not update the
2148 * system variables if the ext_enable flag is set. In
2149 * this case, the external clock driver will update the
2150 * variables, which will be read later by the local
2151 * clock driver. Afterwards, remember the time and
2152 * frequency offsets for jitter and stability values and
2153 * to update the frequency file.
2155 memset(&ntv, 0, sizeof(ntv));
2157 ntv.modes = MOD_STATUS;
2160 ntv.modes = MOD_BITS | MOD_NANO;
2161 #else /* STA_NANO */
2162 ntv.modes = MOD_BITS;
2163 #endif /* STA_NANO */
2164 if (clock_offset < 0)
2169 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2170 ntv.constant = sys_poll;
2171 #else /* STA_NANO */
2172 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2173 ntv.constant = sys_poll - 4;
2174 #endif /* STA_NANO */
2175 ntv.esterror = (u_int32)(clock_jitter * 1e6);
2176 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2177 ntv.status = STA_PLL;
2180 * Enable/disable the PPS if requested.
2183 if (!(pll_status & STA_PPSTIME))
2184 report_event(EVNT_KERN,
2185 NULL, "PPS enabled");
2186 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2188 if (pll_status & STA_PPSTIME)
2189 report_event(EVNT_KERN,
2190 NULL, "PPS disabled");
2191 ntv.status &= ~(STA_PPSTIME |
2194 if (sys_leap == LEAP_ADDSECOND)
2195 ntv.status |= STA_INS;
2196 else if (sys_leap == LEAP_DELSECOND)
2197 ntv.status |= STA_DEL;
2201 * Pass the stuff to the kernel. If it squeals, turn off
2202 * the pps. In any case, fetch the kernel offset,
2203 * frequency and jitter.
2205 if (ntp_adjtime(&ntv) == TIME_ERROR) {
2206 if (!(ntv.status & STA_PPSSIGNAL))
2207 report_event(EVNT_KERN, NULL,
2210 pll_status = ntv.status;
2212 clock_offset = ntv.offset / 1e9;
2213 #else /* STA_NANO */
2214 clock_offset = ntv.offset / 1e6;
2215 #endif /* STA_NANO */
2216 clock_frequency = FREQTOD(ntv.freq);
2219 * If the kernel PPS is lit, monitor its performance.
2221 if (ntv.status & STA_PPSTIME) {
2223 clock_jitter = ntv.jitter / 1e9;
2224 #else /* STA_NANO */
2225 clock_jitter = ntv.jitter / 1e6;
2226 #endif /* STA_NANO */
2229 #if defined(STA_NANO) && NTP_API == 4
2231 * If the TAI changes, update the kernel TAI.
2233 if (loop_tai != sys_tai) {
2235 ntv.modes = MOD_TAI;
2236 ntv.constant = sys_tai;
2239 #endif /* STA_NANO */
2241 #endif /* KERNEL_PLL */