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 #define RETRY_INTERVAL 5 /* on error, retry in N secs */
50 #define QUERYTIME_MAX 15 /* wait for reply up to N secs */
52 #define FREQ_TOLERANCE 0.000015 /* % frequency tolerance (15 PPM) */
53 #define MINPOLL 4 /* % minimum poll interval (6: 64 s) */
54 #define MAXPOLL 12 /* % maximum poll interval (12: 1.1h, 17: 36.4h) (was 17) */
55 #define MINDISP 0.01 /* % minimum dispersion (s) */
56 #define MAXDISP 16 /* maximum dispersion (s) */
57 #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
58 #define MAXDIST 1 /* % distance threshold (s) */
59 #define MIN_SELECTED 1 /* % minimum intersection survivors */
60 #define MIN_CLUSTERED 3 /* % minimum cluster survivors */
62 #define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
64 /* Clock discipline parameters and constants */
65 #define STEP_THRESHOLD 0.128 /* step threshold (s) */
66 #define WATCH_THRESHOLD 150 /* stepout threshold (s). std ntpd uses 900 (11 mins (!)) */
67 /* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
68 #define PANIC_THRESHOLD 1000 /* panic threshold (s) */
70 /* Poll-adjust threshold.
71 * When we see that offset is small enough compared to discipline jitter,
72 * we grow a counter: += MINPOLL. When it goes over POLLADJ_LIMIT,
73 * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
74 * and when it goes below -POLLADJ_LIMIT, we poll_exp--
76 #define POLLADJ_LIMIT 30
77 /* If offset < POLLADJ_GATE * discipline_jitter, then we can increase
78 * poll interval (we think we can't improve timekeeping
79 * by staying at smaller poll).
81 #define POLLADJ_GATE 4
82 /* Compromise Allan intercept (s). doc uses 1500, std ntpd uses 512 */
86 /* FLL loop gain [why it depends on MAXPOLL??] */
87 #define FLL (MAXPOLL + 1)
88 /* Parameter averaging constant */
97 NTP_MSGSIZE_NOAUTH = 48,
98 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
101 MODE_MASK = (7 << 0),
102 VERSION_MASK = (7 << 3),
106 /* Leap Second Codes (high order two bits of m_status) */
107 LI_NOWARNING = (0 << 6), /* no warning */
108 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
109 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
110 LI_ALARM = (3 << 6), /* alarm condition */
113 MODE_RES0 = 0, /* reserved */
114 MODE_SYM_ACT = 1, /* symmetric active */
115 MODE_SYM_PAS = 2, /* symmetric passive */
116 MODE_CLIENT = 3, /* client */
117 MODE_SERVER = 4, /* server */
118 MODE_BROADCAST = 5, /* broadcast */
119 MODE_RES1 = 6, /* reserved for NTP control message */
120 MODE_RES2 = 7, /* reserved for private use */
123 //TODO: better base selection
124 #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
126 #define NUM_DATAPOINTS 8
139 uint8_t m_status; /* status of local clock and leap info */
141 uint8_t m_ppoll; /* poll value */
142 int8_t m_precision_exp;
143 s_fixedpt_t m_rootdelay;
144 s_fixedpt_t m_rootdisp;
146 l_fixedpt_t m_reftime;
147 l_fixedpt_t m_orgtime;
148 l_fixedpt_t m_rectime;
149 l_fixedpt_t m_xmttime;
151 uint8_t m_digest[NTP_DIGESTSIZE];
161 len_and_sockaddr *p_lsa;
163 /* when to send new query (if p_fd == -1)
164 * or when receive times out (if p_fd >= 0): */
165 time_t next_action_time;
168 uint32_t lastpkt_refid;
169 uint8_t lastpkt_leap;
170 uint8_t lastpkt_stratum;
171 uint8_t p_reachable_bits;
173 double lastpkt_recv_time;
174 double lastpkt_delay;
175 double lastpkt_rootdelay;
176 double lastpkt_rootdisp;
177 /* produced by filter algorithm: */
178 double filter_offset;
179 double filter_dispersion;
180 double filter_jitter;
181 datapoint_t filter_datapoint[NUM_DATAPOINTS];
182 /* last sent packet: */
192 /* Insert new options above this line. */
193 /* Non-compat options: */
195 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
199 /* total round trip delay to currently selected reference clock */
201 /* reference timestamp: time when the system clock was last set or corrected */
203 /* total dispersion to currently selected reference clock */
206 #if ENABLE_FEATURE_NTPD_SERVER
211 /* refid: 32-bit code identifying the particular server or reference clock
212 * in stratum 0 packets this is a four-character ASCII string,
213 * called the kiss code, used for debugging and monitoring
214 * in stratum 1 packets this is a four-character ASCII string
215 * assigned to the reference clock by IANA. Example: "GPS "
216 * in stratum 2+ packets, it's IPv4 address or 4 first bytes of MD5 hash of IPv6
220 /* precision is defined as the larger of the resolution and time to
221 * read the clock, in log2 units. For instance, the precision of a
222 * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
223 * system clock hardware representation is to the nanosecond.
225 * Delays, jitters of various kinds are clamper down to precision.
227 * If precision_sec is too large, discipline_jitter gets clamped to it
228 * and if offset is much smaller than discipline_jitter, poll interval
229 * grows even though we really can benefit from staying at smaller one,
230 * collecting non-lagged datapoits and correcting the offset.
231 * (Lagged datapoits exist when poll_exp is large but we still have
232 * systematic offset error - the time distance between datapoints
233 * is significat and older datapoints have smaller offsets.
234 * This makes our offset estimation a bit smaller than reality)
235 * Due to this effect, setting G_precision_sec close to
236 * STEP_THRESHOLD isn't such a good idea - offsets may grow
237 * too big and we will step. I observed it with -6.
239 * OTOH, setting precision too small would result in futile attempts
240 * to syncronize to the unachievable precision.
242 * -6 is 1/64 sec, -7 is 1/128 sec and so on.
244 #define G_precision_exp -8
245 #define G_precision_sec (1.0 / (1 << (- G_precision_exp)))
247 /* Bool. After set to 1, never goes back to 0: */
249 // uint8_t time_was_stepped;
250 uint8_t adjtimex_was_done;
252 uint8_t discipline_state; // doc calls it c.state
253 uint8_t poll_exp; // s.poll
254 int polladj_count; // c.count
255 long kernel_freq_drift;
256 double last_update_offset; // c.last
257 double last_update_recv_time; // s.t
258 double discipline_jitter; // c.jitter
259 //TODO: add s.jitter - grep for it here and see clock_combine() in doc
260 #define USING_KERNEL_PLL_LOOP 1
261 #if !USING_KERNEL_PLL_LOOP
262 double discipline_freq_drift; // c.freq
263 //TODO: conditionally calculate wander? it's used only for logging
264 double discipline_wander; // c.wander
267 #define G (*ptr_to_globals)
269 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
272 #define VERB1 if (MAX_VERBOSE && G.verbose)
273 #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
274 #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
275 #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
276 #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
279 static double LOG2D(int a)
282 return 1.0 / (1UL << -a);
285 static ALWAYS_INLINE double SQUARE(double x)
289 static ALWAYS_INLINE double MAXD(double a, double b)
295 static ALWAYS_INLINE double MIND(double a, double b)
301 #define SQRT(x) (sqrt(x))
307 gettimeofday(&tv, NULL); /* never fails */
308 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
312 d_to_tv(double d, struct timeval *tv)
314 tv->tv_sec = (long)d;
315 tv->tv_usec = (d - tv->tv_sec) * 1000000;
319 lfp_to_d(l_fixedpt_t lfp)
322 lfp.int_partl = ntohl(lfp.int_partl);
323 lfp.fractionl = ntohl(lfp.fractionl);
324 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
328 sfp_to_d(s_fixedpt_t sfp)
331 sfp.int_parts = ntohs(sfp.int_parts);
332 sfp.fractions = ntohs(sfp.fractions);
333 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
336 #if ENABLE_FEATURE_NTPD_SERVER
341 lfp.int_partl = (uint32_t)d;
342 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
343 lfp.int_partl = htonl(lfp.int_partl);
344 lfp.fractionl = htonl(lfp.fractionl);
351 sfp.int_parts = (uint16_t)d;
352 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
353 sfp.int_parts = htons(sfp.int_parts);
354 sfp.fractions = htons(sfp.fractions);
360 dispersion(const datapoint_t *dp, double t)
362 return dp->d_dispersion + FREQ_TOLERANCE * (t - dp->d_recv_time);
366 root_distance(peer_t *p, double t)
368 /* The root synchronization distance is the maximum error due to
369 * all causes of the local clock relative to the primary server.
370 * It is defined as half the total delay plus total dispersion
373 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
374 + p->lastpkt_rootdisp
375 + p->filter_dispersion
376 + FREQ_TOLERANCE * (t - p->lastpkt_recv_time)
381 set_next(peer_t *p, unsigned t)
383 p->next_action_time = time(NULL) + t;
387 * Peer clock filter and its helpers
390 filter_datapoints(peer_t *p, double t)
394 double minoff, maxoff, wavg, sum, w;
395 double x = x; /* for compiler */
396 double oldest_off = oldest_off;
397 double oldest_age = oldest_age;
398 double newest_off = newest_off;
399 double newest_age = newest_age;
401 minoff = maxoff = p->filter_datapoint[0].d_offset;
402 for (i = 1; i < NUM_DATAPOINTS; i++) {
403 if (minoff > p->filter_datapoint[i].d_offset)
404 minoff = p->filter_datapoint[i].d_offset;
405 if (maxoff < p->filter_datapoint[i].d_offset)
406 maxoff = p->filter_datapoint[i].d_offset;
409 idx = p->datapoint_idx; /* most recent datapoint */
411 * Drop two outliers and take weighted average of the rest:
412 * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
413 * we use older6/32, not older6/64 since sum of weights should be 1:
414 * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
420 // filter_dispersion = \ -------------
426 for (i = 0; i < NUM_DATAPOINTS; i++) {
428 bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
430 p->filter_datapoint[idx].d_offset,
431 p->filter_datapoint[idx].d_dispersion, dispersion(&p->filter_datapoint[idx], t),
432 t - p->filter_datapoint[idx].d_recv_time,
433 (minoff == p->filter_datapoint[idx].d_offset || maxoff == p->filter_datapoint[idx].d_offset)
434 ? " (outlier by offset)" : ""
438 sum += dispersion(&p->filter_datapoint[idx], t) / (2 << i);
440 if (minoff == p->filter_datapoint[idx].d_offset) {
441 minoff -= 1; /* so that we don't match it ever again */
443 if (maxoff == p->filter_datapoint[idx].d_offset) {
446 oldest_off = p->filter_datapoint[idx].d_offset;
447 oldest_age = t - p->filter_datapoint[idx].d_recv_time;
450 newest_off = oldest_off;
451 newest_age = oldest_age;
458 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
460 p->filter_dispersion = sum;
461 wavg += x; /* add another older6/64 to form older6/32 */
462 /* Fix systematic underestimation with large poll intervals.
463 * Imagine that we still have a bit of uncorrected drift,
464 * and poll interval is big (say, 100 sec). Offsets form a progression:
465 * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
466 * The algorithm above drops 0.0 and 0.7 as outliers,
467 * and then we have this estimation, ~25% off from 0.7:
468 * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
470 x = newest_age / (oldest_age - newest_age); /* in above example, 100 / (600 - 100) */
472 x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
475 p->filter_offset = wavg;
477 // +----- -----+ ^ 1/2
481 // filter_jitter = --- * | / (avg-offset_j) |
485 // where n is the number of valid datapoints in the filter (n > 1);
486 // if filter_jitter < precision then filter_jitter = precision
488 for (i = 0; i < NUM_DATAPOINTS; i++) {
489 sum += SQUARE(wavg - p->filter_datapoint[i].d_offset);
491 sum = SQRT(sum) / NUM_DATAPOINTS;
492 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
494 VERB3 bb_error_msg("filter offset:%f(corr:%e) disp:%f jitter:%f",
496 p->filter_dispersion,
502 reset_peer_stats(peer_t *p, double t, double offset)
505 for (i = 0; i < NUM_DATAPOINTS; i++) {
506 if (offset < 16 * STEP_THRESHOLD) {
507 p->filter_datapoint[i].d_recv_time -= offset;
508 if (p->filter_datapoint[i].d_offset != 0) {
509 p->filter_datapoint[i].d_offset -= offset;
512 p->filter_datapoint[i].d_recv_time = t;
513 p->filter_datapoint[i].d_offset = 0;
514 p->filter_datapoint[i].d_dispersion = MAXDISP;
517 if (offset < 16 * STEP_THRESHOLD) {
518 p->lastpkt_recv_time -= offset;
520 p->p_reachable_bits = 0;
521 p->lastpkt_recv_time = t;
523 filter_datapoints(p, t); /* recalc p->filter_xxx */
524 p->next_action_time -= (time_t)offset;
525 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
533 p = xzalloc(sizeof(*p));
534 p->p_lsa = xhost2sockaddr(s, 123);
535 p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
537 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
538 p->next_action_time = time(NULL); /* = set_next(p, 0); */
539 reset_peer_stats(p, gettime1900d(), 16 * STEP_THRESHOLD);
540 /* Speed up initial sync: with small offsets from peers,
541 * 3 samples will sync
543 p->filter_datapoint[6].d_dispersion = 0;
544 p->filter_datapoint[7].d_dispersion = 0;
546 llist_add_to(&G.ntp_peers, p);
552 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
553 msg_t *msg, ssize_t len)
559 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
561 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
564 bb_perror_msg("send failed");
571 send_query_to_peer(peer_t *p)
573 // Why do we need to bind()?
574 // See what happens when we don't bind:
576 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
577 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
578 // gettimeofday({1259071266, 327885}, NULL) = 0
579 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
580 // ^^^ we sent it from some source port picked by kernel.
581 // time(NULL) = 1259071266
582 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
583 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
584 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
585 // ^^^ this recv will receive packets to any local port!
587 // Uncomment this and use strace to see it in action:
588 #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
592 len_and_sockaddr *local_lsa;
594 family = p->p_lsa->u.sa.sa_family;
595 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
596 /* local_lsa has "null" address and port 0 now.
597 * bind() ensures we have a *particular port* selected by kernel
598 * and remembered in p->p_fd, thus later recv(p->p_fd)
599 * receives only packets sent to this port.
602 xbind(fd, &local_lsa->u.sa, local_lsa->len);
604 #if ENABLE_FEATURE_IPV6
605 if (family == AF_INET)
607 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
612 * Send out a random 64-bit number as our transmit time. The NTP
613 * server will copy said number into the originate field on the
614 * response that it sends us. This is totally legal per the SNTP spec.
616 * The impact of this is two fold: we no longer send out the current
617 * system time for the world to see (which may aid an attacker), and
618 * it gives us a (not very secure) way of knowing that we're not
619 * getting spoofed by an attacker that can't capture our traffic
620 * but can spoof packets from the NTP server we're communicating with.
622 * Save the real transmit timestamp locally.
624 p->p_xmt_msg.m_xmttime.int_partl = random();
625 p->p_xmt_msg.m_xmttime.fractionl = random();
626 p->p_xmttime = gettime1900d();
628 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
629 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
633 set_next(p, RETRY_INTERVAL);
637 p->p_reachable_bits <<= 1;
638 VERB1 bb_error_msg("sent query to %s", p->p_dotted);
639 set_next(p, QUERYTIME_MAX);
646 step_time(double offset)
653 gettimeofday(&tv, NULL); /* never fails */
654 dtime = offset + tv.tv_sec;
655 dtime += 1.0e-6 * tv.tv_usec;
658 if (settimeofday(&tv, NULL) == -1)
659 bb_perror_msg_and_die("settimeofday");
662 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
664 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
666 // G.time_was_stepped = 1;
671 * Selection and clustering, and their helpers
679 compare_point_edge(const void *aa, const void *bb)
681 const point_t *a = aa;
682 const point_t *b = bb;
683 if (a->edge < b->edge) {
686 return (a->edge > b->edge);
693 compare_survivor_metric(const void *aa, const void *bb)
695 const survivor_t *a = aa;
696 const survivor_t *b = bb;
697 if (a->metric < b->metric)
699 return (a->metric > b->metric);
702 fit(peer_t *p, double rd)
704 if (p->p_reachable_bits == 0) {
705 VERB3 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
708 //TODO: we never accept such packets anyway, right?
709 if ((p->lastpkt_leap & LI_ALARM) == LI_ALARM
710 || p->lastpkt_stratum >= MAXSTRAT
712 VERB3 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
715 /* rd is root_distance(p, t) */
716 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
717 VERB3 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
721 // /* Do we have a loop? */
722 // if (p->refid == p->dstaddr || p->refid == s.refid)
727 select_and_cluster(double t)
731 int size = 3 * G.peer_cnt;
732 /* for selection algorithm */
734 unsigned num_points, num_candidates;
736 unsigned num_falsetickers;
737 /* for cluster algorithm */
738 survivor_t survivor[size];
739 unsigned num_survivors;
745 while (item != NULL) {
746 peer_t *p = (peer_t *) item->data;
747 double rd = root_distance(p, t);
748 double offset = p->filter_offset;
755 VERB4 bb_error_msg("interval: [%f %f %f] %s",
761 point[num_points].p = p;
762 point[num_points].type = -1;
763 point[num_points].edge = offset - rd;
765 point[num_points].p = p;
766 point[num_points].type = 0;
767 point[num_points].edge = offset;
769 point[num_points].p = p;
770 point[num_points].type = 1;
771 point[num_points].edge = offset + rd;
775 num_candidates = num_points / 3;
776 if (num_candidates == 0) {
777 VERB3 bb_error_msg("no valid datapoints, no peer selected");
778 return NULL; /* never happers? */
780 //TODO: sorting does not seem to be done in reference code
781 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
783 /* Start with the assumption that there are no falsetickers.
784 * Attempt to find a nonempty intersection interval containing
785 * the midpoints of all truechimers.
786 * If a nonempty interval cannot be found, increase the number
787 * of assumed falsetickers by one and try again.
788 * If a nonempty interval is found and the number of falsetickers
789 * is less than the number of truechimers, a majority has been found
790 * and the midpoint of each truechimer represents
791 * the candidates available to the cluster algorithm.
793 num_falsetickers = 0;
796 unsigned num_midpoints = 0;
801 for (i = 0; i < num_points; i++) {
803 * if (point[i].type == -1) c++;
804 * if (point[i].type == 1) c--;
805 * and it's simpler to do it this way:
808 if (c >= num_candidates - num_falsetickers) {
809 /* If it was c++ and it got big enough... */
813 if (point[i].type == 0)
817 for (i = num_points-1; i >= 0; i--) {
819 if (c >= num_candidates - num_falsetickers) {
820 high = point[i].edge;
823 if (point[i].type == 0)
826 /* If the number of midpoints is greater than the number
827 * of allowed falsetickers, the intersection contains at
828 * least one truechimer with no midpoint - bad.
829 * Also, interval should be nonempty.
831 if (num_midpoints <= num_falsetickers && low < high)
834 if (num_falsetickers * 2 >= num_candidates) {
835 VERB3 bb_error_msg("too many falsetickers:%d (candidates:%d), no peer selected",
836 num_falsetickers, num_candidates);
840 VERB3 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
841 low, high, num_candidates, num_falsetickers);
845 /* Construct a list of survivors (p, metric)
846 * from the chime list, where metric is dominated
847 * first by stratum and then by root distance.
848 * All other things being equal, this is the order of preference.
851 for (i = 0; i < num_points; i++) {
854 if (point[i].edge < low || point[i].edge > high)
857 survivor[num_survivors].p = p;
858 //TODO: save root_distance in point_t and reuse here?
859 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + root_distance(p, t);
860 VERB4 bb_error_msg("survivor[%d] metric:%f peer:%s",
861 num_survivors, survivor[num_survivors].metric, p->p_dotted);
864 /* There must be at least MIN_SELECTED survivors to satisfy the
865 * correctness assertions. Ordinarily, the Byzantine criteria
866 * require four survivors, but for the demonstration here, one
869 if (num_survivors < MIN_SELECTED) {
870 VERB3 bb_error_msg("num_survivors %d < %d, no peer selected",
871 num_survivors, MIN_SELECTED);
875 //looks like this is ONLY used by the fact that later we pick survivor[0].
876 //we can avoid sorting then, just find the minimum once!
877 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
879 /* For each association p in turn, calculate the selection
880 * jitter p->sjitter as the square root of the sum of squares
881 * (p->offset - q->offset) over all q associations. The idea is
882 * to repeatedly discard the survivor with maximum selection
883 * jitter until a termination condition is met.
886 unsigned max_idx = max_idx;
887 double max_selection_jitter = max_selection_jitter;
888 double min_jitter = min_jitter;
890 if (num_survivors <= MIN_CLUSTERED) {
891 bb_error_msg("num_survivors %d <= %d, not discarding more",
892 num_survivors, MIN_CLUSTERED);
896 /* To make sure a few survivors are left
897 * for the clustering algorithm to chew on,
898 * we stop if the number of survivors
899 * is less than or equal to MIN_CLUSTERED (3).
901 for (i = 0; i < num_survivors; i++) {
902 double selection_jitter_sq;
903 peer_t *p = survivor[i].p;
905 if (i == 0 || p->filter_jitter < min_jitter)
906 min_jitter = p->filter_jitter;
908 selection_jitter_sq = 0;
909 for (j = 0; j < num_survivors; j++) {
910 peer_t *q = survivor[j].p;
911 //TODO: where is 1/(n-1) * ... multiplier?
912 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
914 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
915 max_selection_jitter = selection_jitter_sq;
918 VERB5 bb_error_msg("survivor %d selection_jitter^2:%f",
919 i, selection_jitter_sq);
921 max_selection_jitter = SQRT(max_selection_jitter);
922 VERB4 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
923 max_idx, max_selection_jitter, min_jitter);
925 /* If the maximum selection jitter is less than the
926 * minimum peer jitter, then tossing out more survivors
927 * will not lower the minimum peer jitter, so we might
930 if (max_selection_jitter < min_jitter) {
931 VERB3 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
932 max_selection_jitter, min_jitter, num_survivors);
936 /* Delete survivor[max_idx] from the list
937 * and go around again.
939 VERB5 bb_error_msg("dropping survivor %d", max_idx);
941 while (max_idx < num_survivors) {
942 survivor[max_idx] = survivor[max_idx + 1];
947 /* Pick the best clock. If the old system peer is on the list
948 * and at the same stratum as the first survivor on the list,
949 * then don't do a clock hop. Otherwise, select the first
950 * survivor on the list as the new system peer.
952 //TODO - see clock_combine()
953 VERB3 bb_error_msg("selected peer %s filter_offset:%f age:%f",
954 survivor[0].p->p_dotted,
955 survivor[0].p->filter_offset,
956 t - survivor[0].p->lastpkt_recv_time
958 return survivor[0].p;
963 * Local clock discipline and its helpers
966 set_new_values(int disc_state, double offset, double recv_time)
968 /* Enter new state and set state variables. Note we use the time
969 * of the last clock filter sample, which must be earlier than
972 VERB3 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
973 disc_state, offset, recv_time);
974 G.discipline_state = disc_state;
975 G.last_update_offset = offset;
976 G.last_update_recv_time = recv_time;
978 /* Clock state definitions */
979 #define STATE_NSET 0 /* initial state, "nothing is set" */
980 #define STATE_FSET 1 /* frequency set from file */
981 #define STATE_SPIK 2 /* spike detected */
982 #define STATE_FREQ 3 /* initial frequency */
983 #define STATE_SYNC 4 /* clock synchronized (normal operation) */
984 /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
986 update_local_clock(peer_t *p, double t)
991 double offset = p->filter_offset;
992 double recv_time = p->lastpkt_recv_time;
995 double since_last_update;
998 abs_offset = fabs(offset);
1000 /* If the offset is too large, give up and go home */
1001 if (abs_offset > PANIC_THRESHOLD) {
1002 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1005 /* If this is an old update, for instance as the result
1006 * of a system peer change, avoid it. We never use
1007 * an old sample or the same sample twice.
1009 if (recv_time <= G.last_update_recv_time) {
1010 VERB3 bb_error_msg("same or older datapoint: %f >= %f, not using it",
1011 G.last_update_recv_time, recv_time);
1012 return 0; /* "leave poll interval as is" */
1015 /* Clock state machine transition function. This is where the
1016 * action is and defines how the system reacts to large time
1017 * and frequency errors.
1019 since_last_update = recv_time - G.reftime;
1021 if (G.discipline_state == STATE_FREQ) {
1022 /* Ignore updates until the stepout threshold */
1023 if (since_last_update < WATCH_THRESHOLD) {
1024 VERB3 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1025 WATCH_THRESHOLD - since_last_update);
1026 return 0; /* "leave poll interval as is" */
1028 freq_drift = (offset - G.last_update_offset) / since_last_update;
1031 /* There are two main regimes: when the
1032 * offset exceeds the step threshold and when it does not.
1034 if (abs_offset > STEP_THRESHOLD) {
1037 switch (G.discipline_state) {
1039 /* The first outlyer: ignore it, switch to SPIK state */
1040 VERB3 bb_error_msg("offset:%f - spike detected", offset);
1041 G.discipline_state = STATE_SPIK;
1042 return -1; /* "decrease poll interval" */
1045 /* Ignore succeeding outlyers until either an inlyer
1046 * is found or the stepout threshold is exceeded.
1048 if (since_last_update < WATCH_THRESHOLD) {
1049 VERB3 bb_error_msg("spike detected, datapoint ignored, %f sec remains",
1050 WATCH_THRESHOLD - since_last_update);
1051 return -1; /* "decrease poll interval" */
1053 /* fall through: we need to step */
1056 /* Step the time and clamp down the poll interval.
1058 * In NSET state an initial frequency correction is
1059 * not available, usually because the frequency file has
1060 * not yet been written. Since the time is outside the
1061 * capture range, the clock is stepped. The frequency
1062 * will be set directly following the stepout interval.
1064 * In FSET state the initial frequency has been set
1065 * from the frequency file. Since the time is outside
1066 * the capture range, the clock is stepped immediately,
1067 * rather than after the stepout interval. Guys get
1068 * nervous if it takes 17 minutes to set the clock for
1071 * In SPIK state the stepout threshold has expired and
1072 * the phase is still above the step threshold. Note
1073 * that a single spike greater than the step threshold
1074 * is always suppressed, even at the longer poll
1077 VERB3 bb_error_msg("stepping time by %f; poll_exp=MINPOLL", offset);
1079 if (option_mask32 & OPT_q) {
1080 /* We were only asked to set time once. Done. */
1084 G.polladj_count = 0;
1085 G.poll_exp = MINPOLL;
1086 G.stratum = MAXSTRAT;
1087 for (item = G.ntp_peers; item != NULL; item = item->link) {
1088 peer_t *pp = (peer_t *) item->data;
1089 reset_peer_stats(pp, t, offset);
1091 if (G.discipline_state == STATE_NSET) {
1092 set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1093 return 1; /* "ok to increase poll interval" */
1095 set_new_values(STATE_SYNC, /*offset:*/ 0, recv_time);
1097 } else { /* abs_offset <= STEP_THRESHOLD */
1099 if (G.poll_exp < MINPOLL) {
1100 VERB3 bb_error_msg("saw small offset %f, disabling burst mode", offset);
1101 G.poll_exp = MINPOLL;
1104 /* Compute the clock jitter as the RMS of exponentially
1105 * weighted offset differences. Used by the poll adjust code.
1107 etemp = SQUARE(G.discipline_jitter);
1108 dtemp = SQUARE(MAXD(fabs(offset - G.last_update_offset), G_precision_sec));
1109 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1110 VERB3 bb_error_msg("discipline jitter=%f", G.discipline_jitter);
1112 switch (G.discipline_state) {
1114 if (option_mask32 & OPT_q) {
1115 /* We were only asked to set time once.
1116 * The clock is precise enough, no need to step.
1120 /* This is the first update received and the frequency
1121 * has not been initialized. The first thing to do
1122 * is directly measure the oscillator frequency.
1124 set_new_values(STATE_FREQ, offset, recv_time);
1125 VERB3 bb_error_msg("transitioning to FREQ, datapoint ignored");
1126 return -1; /* "decrease poll interval" */
1128 #if 0 /* this is dead code for now */
1130 /* This is the first update and the frequency
1131 * has been initialized. Adjust the phase, but
1132 * don't adjust the frequency until the next update.
1134 set_new_values(STATE_SYNC, offset, recv_time);
1135 /* freq_drift remains 0 */
1140 /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1141 * Correct the phase and frequency and switch to SYNC state.
1142 * freq_drift was already estimated (see code above)
1144 set_new_values(STATE_SYNC, offset, recv_time);
1148 /* Compute freq_drift due to PLL and FLL contributions.
1150 * The FLL and PLL frequency gain constants
1151 * depend on the poll interval and Allan
1152 * intercept. The FLL is not used below one-half
1153 * the Allan intercept. Above that the loop gain
1154 * increases in steps to 1 / AVG.
1156 if ((1 << G.poll_exp) > ALLAN / 2) {
1157 etemp = FLL - G.poll_exp;
1160 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1162 /* For the PLL the integration interval
1163 * (numerator) is the minimum of the update
1164 * interval and poll interval. This allows
1165 * oversampling, but not undersampling.
1167 etemp = MIND(since_last_update, (1 << G.poll_exp));
1168 dtemp = (4 * PLL) << G.poll_exp;
1169 freq_drift += offset * etemp / SQUARE(dtemp);
1170 set_new_values(STATE_SYNC, offset, recv_time);
1173 G.stratum = p->lastpkt_stratum + 1;
1177 G.leap = p->lastpkt_leap;
1178 G.refid = p->lastpkt_refid;
1179 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1180 dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(s.jitter));
1181 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (t - p->lastpkt_recv_time) + abs_offset, MINDISP);
1182 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1183 VERB3 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1185 /* We are in STATE_SYNC now, but did not do adjtimex yet.
1186 * (Any other state does not reach this, they all return earlier)
1187 * By this time, freq_drift and G.last_update_offset are set
1188 * to values suitable for adjtimex.
1190 #if !USING_KERNEL_PLL_LOOP
1191 /* Calculate the new frequency drift and frequency stability (wander).
1192 * Compute the clock wander as the RMS of exponentially weighted
1193 * frequency differences. This is not used directly, but can,
1194 * along with the jitter, be a highly useful monitoring and
1197 dtemp = G.discipline_freq_drift + freq_drift;
1198 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1199 etemp = SQUARE(G.discipline_wander);
1200 dtemp = SQUARE(dtemp);
1201 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1203 VERB3 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1204 G.discipline_freq_drift,
1205 (long)(G.discipline_freq_drift * 65536e6),
1207 G.discipline_wander);
1210 memset(&tmx, 0, sizeof(tmx));
1211 if (adjtimex(&tmx) < 0)
1212 bb_perror_msg_and_die("adjtimex");
1213 VERB3 bb_error_msg("p adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1214 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1218 if (!G.adjtimex_was_done) {
1219 G.adjtimex_was_done = 1;
1220 /* When we use adjtimex for the very first time,
1221 * we need to ADD to pre-existing tmx.offset - it may be !0
1223 memset(&tmx, 0, sizeof(tmx));
1224 if (adjtimex(&tmx) < 0)
1225 bb_perror_msg_and_die("adjtimex");
1226 old_tmx_offset = tmx.offset;
1228 memset(&tmx, 0, sizeof(tmx));
1230 //doesn't work, offset remains 0 (!) in kernel:
1231 //ntpd: set adjtimex freq:1786097 tmx.offset:77487
1232 //ntpd: prev adjtimex freq:1786097 tmx.offset:0
1233 //ntpd: cur adjtimex freq:1786097 tmx.offset:0
1234 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1235 /* 65536 is one ppm */
1236 tmx.freq = G.discipline_freq_drift * 65536e6;
1237 tmx.offset = G.last_update_offset * 1000000; /* usec */
1239 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1240 tmx.offset = (G.last_update_offset * 1000000) /* usec */
1241 /* + (G.last_update_offset < 0 ? -0.5 : 0.5) - too small to bother */
1242 + old_tmx_offset; /* almost always 0 */
1243 tmx.status = STA_PLL;
1244 //if (sys_leap == LEAP_ADDSECOND)
1245 // tmx.status |= STA_INS;
1246 //else if (sys_leap == LEAP_DELSECOND)
1247 // tmx.status |= STA_DEL;
1248 tmx.constant = G.poll_exp - 4;
1249 //tmx.esterror = (u_int32)(clock_jitter * 1e6);
1250 //tmx.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1251 rc = adjtimex(&tmx);
1253 bb_perror_msg_and_die("adjtimex");
1254 /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
1255 * Not sure why. Perhaps it is normal.
1257 VERB3 bb_error_msg("adjtimex:%d freq:%ld offset:%ld constant:%ld status:0x%x",
1258 rc, tmx.freq, tmx.offset, tmx.constant, tmx.status);
1261 /* always gives the same output as above msg */
1262 memset(&tmx, 0, sizeof(tmx));
1263 if (adjtimex(&tmx) < 0)
1264 bb_perror_msg_and_die("adjtimex");
1265 VERB3 bb_error_msg("c adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1266 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1269 if (G.kernel_freq_drift != tmx.freq / 65536) {
1270 G.kernel_freq_drift = tmx.freq / 65536;
1271 VERB2 bb_error_msg("kernel clock drift: %ld ppm", G.kernel_freq_drift);
1273 // #define STA_MODE 0x4000 /* mode (0 = PLL, 1 = FLL) (ro) */ - ?
1274 // it appeared after a while:
1275 //ntpd: p adjtimex freq:-14545653 offset:-5396 constant:10 status:0x41
1276 //ntpd: c adjtimex freq:-14547835 offset:-8307 constant:10 status:0x1
1277 //ntpd: p adjtimex freq:-14547835 offset:-6398 constant:10 status:0x41
1278 //ntpd: c adjtimex freq:-14550486 offset:-10158 constant:10 status:0x1
1279 //ntpd: p adjtimex freq:-14550486 offset:-6132 constant:10 status:0x41
1280 //ntpd: c adjtimex freq:-14636129 offset:-10158 constant:10 status:0x4001
1281 //ntpd: p adjtimex freq:-14636129 offset:-10002 constant:10 status:0x4041
1282 //ntpd: c adjtimex freq:-14636245 offset:-7497 constant:10 status:0x1
1283 //ntpd: p adjtimex freq:-14636245 offset:-4573 constant:10 status:0x41
1284 //ntpd: c adjtimex freq:-14642034 offset:-11715 constant:10 status:0x1
1285 //ntpd: p adjtimex freq:-14642034 offset:-4098 constant:10 status:0x41
1286 //ntpd: c adjtimex freq:-14699112 offset:-11746 constant:10 status:0x4001
1287 //ntpd: p adjtimex freq:-14699112 offset:-4239 constant:10 status:0x4041
1288 //ntpd: c adjtimex freq:-14762330 offset:-12786 constant:10 status:0x4001
1289 //ntpd: p adjtimex freq:-14762330 offset:-4434 constant:10 status:0x4041
1290 //ntpd: b adjtimex freq:0 offset:-9669 constant:8 status:0x1
1291 //ntpd: adjtimex:0 freq:-14809095 offset:-9669 constant:10 status:0x4001
1292 //ntpd: c adjtimex freq:-14809095 offset:-9669 constant:10 status:0x4001
1294 return 1; /* "ok to increase poll interval" */
1299 * We've got a new reply packet from a peer, process it
1303 retry_interval(void)
1305 /* Local problem, want to retry soon */
1306 unsigned interval, r;
1307 interval = RETRY_INTERVAL;
1309 interval += r % (unsigned)(RETRY_INTERVAL / 4);
1310 VERB3 bb_error_msg("chose retry interval:%u", interval);
1314 poll_interval(int exponent) /* exp is always -1 or 0 */
1316 /* Want to send next packet at (1 << G.poll_exp) + small random value */
1317 unsigned interval, r;
1318 exponent += G.poll_exp; /* G.poll_exp is always > 0 */
1319 /* never true: if (exp < 0) exp = 0; */
1320 interval = 1 << exponent;
1322 interval += ((r & (interval-1)) >> 4) + ((r >> 8) & 1); /* + 1/16 of interval, max */
1323 VERB3 bb_error_msg("chose poll interval:%u (poll_exp:%d exp:%d)", interval, G.poll_exp, exponent);
1327 recv_and_process_peer_pkt(peer_t *p)
1332 double T1, T2, T3, T4;
1334 datapoint_t *datapoint;
1337 /* We can recvfrom here and check from.IP, but some multihomed
1338 * ntp servers reply from their *other IP*.
1339 * TODO: maybe we should check at least what we can: from.port == 123?
1341 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1343 bb_perror_msg("recv(%s) error", p->p_dotted);
1344 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
1345 || errno == ENETUNREACH || errno == ENETDOWN
1346 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
1349 //TODO: always do this?
1350 set_next(p, retry_interval());
1356 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1357 bb_error_msg("malformed packet received from %s", p->p_dotted);
1361 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1362 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1367 if ((msg.m_status & LI_ALARM) == LI_ALARM
1368 || msg.m_stratum == 0
1369 || msg.m_stratum > NTP_MAXSTRATUM
1371 // TODO: stratum 0 responses may have commands in 32-bit m_refid field:
1372 // "DENY", "RSTR" - peer does not like us at all
1373 // "RATE" - peer is overloaded, reduce polling freq
1374 interval = poll_interval(0);
1375 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
1380 // * Verify the server is synchronized with valid stratum and
1381 // * reference time not later than the transmit time.
1383 // if (p->lastpkt_leap == NOSYNC || p->lastpkt_stratum >= MAXSTRAT)
1384 // return; /* unsynchronized */
1386 // /* Verify valid root distance */
1387 // if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
1388 // return; /* invalid header values */
1390 p->lastpkt_leap = msg.m_status;
1391 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1392 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1393 p->lastpkt_refid = msg.m_refid;
1396 * From RFC 2030 (with a correction to the delay math):
1398 * Timestamp Name ID When Generated
1399 * ------------------------------------------------------------
1400 * Originate Timestamp T1 time request sent by client
1401 * Receive Timestamp T2 time request received by server
1402 * Transmit Timestamp T3 time reply sent by server
1403 * Destination Timestamp T4 time reply received by client
1405 * The roundtrip delay and local clock offset are defined as
1407 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
1410 T2 = lfp_to_d(msg.m_rectime);
1411 T3 = lfp_to_d(msg.m_xmttime);
1412 T4 = gettime1900d();
1414 p->lastpkt_recv_time = T4;
1416 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
1417 p->datapoint_idx = p->p_reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
1418 datapoint = &p->filter_datapoint[p->datapoint_idx];
1419 datapoint->d_recv_time = T4;
1420 datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
1421 /* The delay calculation is a special case. In cases where the
1422 * server and client clocks are running at different rates and
1423 * with very fast networks, the delay can appear negative. In
1424 * order to avoid violating the Principle of Least Astonishment,
1425 * the delay is clamped not less than the system precision.
1427 p->lastpkt_delay = (T4 - T1) - (T3 - T2);
1428 if (p->lastpkt_delay < G_precision_sec)
1429 p->lastpkt_delay = G_precision_sec;
1430 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
1431 if (!p->p_reachable_bits) {
1432 /* 1st datapoint ever - replicate offset in every element */
1434 for (i = 1; i < NUM_DATAPOINTS; i++) {
1435 p->filter_datapoint[i].d_offset = datapoint->d_offset;
1439 p->p_reachable_bits |= 1;
1441 bb_error_msg("reply from %s: reach 0x%02x offset %f delay %f",
1443 p->p_reachable_bits,
1444 datapoint->d_offset, p->lastpkt_delay);
1447 /* Muck with statictics and update the clock */
1448 filter_datapoints(p, T4);
1449 q = select_and_cluster(T4);
1452 rc = update_local_clock(q, T4);
1455 /* Adjust the poll interval by comparing the current offset
1456 * with the clock jitter. If the offset is less than
1457 * the clock jitter times a constant, then the averaging interval
1458 * is increased, otherwise it is decreased. A bit of hysteresis
1459 * helps calm the dance. Works best using burst mode.
1462 bb_error_msg("offset:%f POLLADJ_GATE*discipline_jitter:%f poll:%s",
1463 q->filter_offset, POLLADJ_GATE * G.discipline_jitter,
1464 fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter
1468 if (rc > 0 && fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter) {
1469 /* was += G.poll_exp but it is a bit
1470 * too optimistic for my taste at high poll_exp's */
1471 G.polladj_count += MINPOLL;
1472 if (G.polladj_count > POLLADJ_LIMIT) {
1473 G.polladj_count = 0;
1474 if (G.poll_exp < MAXPOLL) {
1476 VERB3 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1477 G.discipline_jitter, G.poll_exp);
1480 VERB3 bb_error_msg("polladj: incr:%d", G.polladj_count);
1483 G.polladj_count -= G.poll_exp * 2;
1484 if (G.polladj_count < -POLLADJ_LIMIT) {
1485 G.polladj_count = 0;
1486 if (G.poll_exp > MINPOLL) {
1488 VERB3 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1489 G.discipline_jitter, G.poll_exp);
1492 VERB3 bb_error_msg("polladj: decr:%d", G.polladj_count);
1497 /* Decide when to send new query for this peer */
1498 interval = poll_interval(0);
1499 set_next(p, interval);
1502 /* We do not expect any more packets from this peer for now.
1503 * Closing the socket informs kernel about it.
1504 * We open a new socket when we send a new query.
1512 #if ENABLE_FEATURE_NTPD_SERVER
1514 recv_and_process_client_pkt(void /*int fd*/)
1519 len_and_sockaddr *to;
1520 struct sockaddr *from;
1522 uint8_t query_status;
1523 l_fixedpt_t query_xmttime;
1525 to = get_sock_lsa(G.listen_fd);
1526 from = xzalloc(to->len);
1528 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
1529 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1532 if (errno == EAGAIN)
1534 bb_perror_msg_and_die("recv");
1536 addr = xmalloc_sockaddr2dotted_noport(from);
1537 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
1542 query_status = msg.m_status;
1543 query_xmttime = msg.m_xmttime;
1545 /* Build a reply packet */
1546 memset(&msg, 0, sizeof(msg));
1547 msg.m_status = G.stratum < MAXSTRAT ? G.leap : LI_ALARM;
1548 msg.m_status |= (query_status & VERSION_MASK);
1549 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
1550 MODE_SERVER : MODE_SYM_PAS;
1551 msg.m_stratum = G.stratum;
1552 msg.m_ppoll = G.poll_exp;
1553 msg.m_precision_exp = G_precision_exp;
1554 rectime = gettime1900d();
1555 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
1556 msg.m_reftime = d_to_lfp(G.reftime);
1557 msg.m_orgtime = query_xmttime;
1558 msg.m_rootdelay = d_to_sfp(G.rootdelay);
1559 //simple code does not do this, fix simple code!
1560 msg.m_rootdisp = d_to_sfp(G.rootdisp);
1561 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
1562 msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
1564 /* We reply from the local address packet was sent to,
1565 * this makes to/from look swapped here: */
1566 do_sendto(G.listen_fd,
1567 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
1576 /* Upstream ntpd's options:
1578 * -4 Force DNS resolution of host names to the IPv4 namespace.
1579 * -6 Force DNS resolution of host names to the IPv6 namespace.
1580 * -a Require cryptographic authentication for broadcast client,
1581 * multicast client and symmetric passive associations.
1582 * This is the default.
1583 * -A Do not require cryptographic authentication for broadcast client,
1584 * multicast client and symmetric passive associations.
1585 * This is almost never a good idea.
1586 * -b Enable the client to synchronize to broadcast servers.
1588 * Specify the name and path of the configuration file,
1589 * default /etc/ntp.conf
1590 * -d Specify debugging mode. This option may occur more than once,
1591 * with each occurrence indicating greater detail of display.
1593 * Specify debugging level directly.
1595 * Specify the name and path of the frequency file.
1596 * This is the same operation as the "driftfile FILE"
1597 * configuration command.
1598 * -g Normally, ntpd exits with a message to the system log
1599 * if the offset exceeds the panic threshold, which is 1000 s
1600 * by default. This option allows the time to be set to any value
1601 * without restriction; however, this can happen only once.
1602 * If the threshold is exceeded after that, ntpd will exit
1603 * with a message to the system log. This option can be used
1604 * with the -q and -x options. See the tinker command for other options.
1606 * Chroot the server to the directory jaildir. This option also implies
1607 * that the server attempts to drop root privileges at startup
1608 * (otherwise, chroot gives very little additional security).
1609 * You may need to also specify a -u option.
1611 * Specify the name and path of the symmetric key file,
1612 * default /etc/ntp/keys. This is the same operation
1613 * as the "keys FILE" configuration command.
1615 * Specify the name and path of the log file. The default
1616 * is the system log file. This is the same operation as
1617 * the "logfile FILE" configuration command.
1618 * -L Do not listen to virtual IPs. The default is to listen.
1620 * -N To the extent permitted by the operating system,
1621 * run the ntpd at the highest priority.
1623 * Specify the name and path of the file used to record the ntpd
1624 * process ID. This is the same operation as the "pidfile FILE"
1625 * configuration command.
1627 * To the extent permitted by the operating system,
1628 * run the ntpd at the specified priority.
1629 * -q Exit the ntpd just after the first time the clock is set.
1630 * This behavior mimics that of the ntpdate program, which is
1631 * to be retired. The -g and -x options can be used with this option.
1632 * Note: The kernel time discipline is disabled with this option.
1634 * Specify the default propagation delay from the broadcast/multicast
1635 * server to this client. This is necessary only if the delay
1636 * cannot be computed automatically by the protocol.
1638 * Specify the directory path for files created by the statistics
1639 * facility. This is the same operation as the "statsdir DIR"
1640 * configuration command.
1642 * Add a key number to the trusted key list. This option can occur
1645 * Specify a user, and optionally a group, to switch to.
1648 * Add a system variable listed by default.
1649 * -x Normally, the time is slewed if the offset is less than the step
1650 * threshold, which is 128 ms by default, and stepped if above
1651 * the threshold. This option sets the threshold to 600 s, which is
1652 * well within the accuracy window to set the clock manually.
1653 * Note: since the slew rate of typical Unix kernels is limited
1654 * to 0.5 ms/s, each second of adjustment requires an amortization
1655 * interval of 2000 s. Thus, an adjustment as much as 600 s
1656 * will take almost 14 days to complete. This option can be used
1657 * with the -g and -q options. See the tinker command for other options.
1658 * Note: The kernel time discipline is disabled with this option.
1661 /* By doing init in a separate function we decrease stack usage
1664 static NOINLINE void ntp_init(char **argv)
1672 bb_error_msg_and_die(bb_msg_you_must_be_root);
1674 /* Set some globals */
1676 /* With constant b = 100, G.precision_exp is also constant -6.
1677 * Uncomment this to verify.
1684 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
1685 clock_getres(CLOCK_REALTIME, &tp);
1687 tp.tv_nsec = 10000000;
1688 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
1690 b = 100; /* b = 1000000000/10000000 = 100 */
1694 /*G.precision_exp = prec;*/
1695 /*G.precision_sec = (1.0 / (1 << (- prec)));*/
1696 bb_error_msg("G.precision_exp:%d sec:%f", prec, G_precision_sec); /* -6 */
1699 G.stratum = MAXSTRAT;
1700 G.poll_exp = 1; /* should use MINPOLL, but 1 speeds up initial sync */
1701 G.reftime = G.last_update_recv_time = gettime1900d();
1705 opt_complementary = "dd:p::"; /* d: counter, p: list */
1706 opts = getopt32(argv,
1708 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
1710 "46aAbgL", /* compat, ignored */
1711 &peers, &G.verbose);
1712 if (!(opts & (OPT_p|OPT_l)))
1714 // if (opts & OPT_x) /* disable stepping, only slew is allowed */
1715 // G.time_was_stepped = 1;
1717 add_peers(llist_pop(&peers));
1718 if (!(opts & OPT_n)) {
1719 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
1720 logmode = LOGMODE_NONE;
1722 #if ENABLE_FEATURE_NTPD_SERVER
1725 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
1726 socket_want_pktinfo(G.listen_fd);
1727 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
1730 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
1732 setpriority(PRIO_PROCESS, 0, -15);
1734 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
1735 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
1738 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
1739 int ntpd_main(int argc UNUSED_PARAM, char **argv)
1745 memset(&g, 0, sizeof(g));
1746 SET_PTR_TO_GLOBALS(&g);
1751 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
1752 unsigned cnt = g.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
1753 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
1754 pfd = xzalloc(sizeof(pfd[0]) * cnt);
1757 while (!bb_got_signal) {
1760 unsigned sent_cnt, trial_cnt;
1762 time_t cur_time, nextaction;
1764 /* Nothing between here and poll() blocks for any significant time */
1766 cur_time = time(NULL);
1767 nextaction = cur_time + 3600;
1770 #if ENABLE_FEATURE_NTPD_SERVER
1771 if (g.listen_fd != -1) {
1772 pfd[0].fd = g.listen_fd;
1773 pfd[0].events = POLLIN;
1777 /* Pass over peer list, send requests, time out on receives */
1778 sent_cnt = trial_cnt = 0;
1779 for (item = g.ntp_peers; item != NULL; item = item->link) {
1780 peer_t *p = (peer_t *) item->data;
1782 /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
1783 if ((int)(cur_time - p->next_action_time) >= 0) {
1784 if (p->p_fd == -1) {
1785 /* Time to send new req */
1787 if (send_query_to_peer(p) == 0)
1790 /* Timed out waiting for reply */
1793 timeout = poll_interval(-1); /* try a bit faster */
1794 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
1795 p->p_dotted, p->p_reachable_bits, timeout);
1796 set_next(p, timeout);
1800 if (p->next_action_time < nextaction)
1801 nextaction = p->next_action_time;
1804 /* Wait for reply from this peer */
1805 pfd[i].fd = p->p_fd;
1806 pfd[i].events = POLLIN;
1812 // if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0) {
1813 // G.time_was_stepped = 1;
1816 timeout = nextaction - cur_time;
1820 /* Here we may block */
1821 VERB2 bb_error_msg("poll %us, sockets:%u", timeout, i);
1822 nfds = poll(pfd, i, timeout * 1000);
1826 /* Process any received packets */
1828 #if ENABLE_FEATURE_NTPD_SERVER
1829 if (g.listen_fd != -1) {
1830 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1832 recv_and_process_client_pkt(/*g.listen_fd*/);
1837 for (; nfds != 0 && j < i; j++) {
1838 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1840 recv_and_process_peer_pkt(idx2peer[j]);
1843 } /* while (!bb_got_signal) */
1845 kill_myself_with_sig(bb_got_signal);
1853 /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
1855 /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
1859 direct_freq(double fp_offset)
1864 * If the kernel is enabled, we need the residual offset to
1865 * calculate the frequency correction.
1867 if (pll_control && kern_enable) {
1868 memset(&ntv, 0, sizeof(ntv));
1871 clock_offset = ntv.offset / 1e9;
1872 #else /* STA_NANO */
1873 clock_offset = ntv.offset / 1e6;
1874 #endif /* STA_NANO */
1875 drift_comp = FREQTOD(ntv.freq);
1877 #endif /* KERNEL_PLL */
1878 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
1884 set_freq(double freq) /* frequency update */
1892 * If the kernel is enabled, update the kernel frequency.
1894 if (pll_control && kern_enable) {
1895 memset(&ntv, 0, sizeof(ntv));
1896 ntv.modes = MOD_FREQUENCY;
1897 ntv.freq = DTOFREQ(drift_comp);
1899 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
1900 report_event(EVNT_FSET, NULL, tbuf);
1902 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
1903 report_event(EVNT_FSET, NULL, tbuf);
1905 #else /* KERNEL_PLL */
1906 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
1907 report_event(EVNT_FSET, NULL, tbuf);
1908 #endif /* KERNEL_PLL */
1917 * This code segment works when clock adjustments are made using
1918 * precision time kernel support and the ntp_adjtime() system
1919 * call. This support is available in Solaris 2.6 and later,
1920 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
1921 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
1922 * DECstation 5000/240 and Alpha AXP, additional kernel
1923 * modifications provide a true microsecond clock and nanosecond
1924 * clock, respectively.
1926 * Important note: The kernel discipline is used only if the
1927 * step threshold is less than 0.5 s, as anything higher can
1928 * lead to overflow problems. This might occur if some misguided
1929 * lad set the step threshold to something ridiculous.
1931 if (pll_control && kern_enable) {
1933 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
1936 * We initialize the structure for the ntp_adjtime()
1937 * system call. We have to convert everything to
1938 * microseconds or nanoseconds first. Do not update the
1939 * system variables if the ext_enable flag is set. In
1940 * this case, the external clock driver will update the
1941 * variables, which will be read later by the local
1942 * clock driver. Afterwards, remember the time and
1943 * frequency offsets for jitter and stability values and
1944 * to update the frequency file.
1946 memset(&ntv, 0, sizeof(ntv));
1948 ntv.modes = MOD_STATUS;
1951 ntv.modes = MOD_BITS | MOD_NANO;
1952 #else /* STA_NANO */
1953 ntv.modes = MOD_BITS;
1954 #endif /* STA_NANO */
1955 if (clock_offset < 0)
1960 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
1961 ntv.constant = sys_poll;
1962 #else /* STA_NANO */
1963 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
1964 ntv.constant = sys_poll - 4;
1965 #endif /* STA_NANO */
1966 ntv.esterror = (u_int32)(clock_jitter * 1e6);
1967 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1968 ntv.status = STA_PLL;
1971 * Enable/disable the PPS if requested.
1974 if (!(pll_status & STA_PPSTIME))
1975 report_event(EVNT_KERN,
1976 NULL, "PPS enabled");
1977 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
1979 if (pll_status & STA_PPSTIME)
1980 report_event(EVNT_KERN,
1981 NULL, "PPS disabled");
1982 ntv.status &= ~(STA_PPSTIME |
1985 if (sys_leap == LEAP_ADDSECOND)
1986 ntv.status |= STA_INS;
1987 else if (sys_leap == LEAP_DELSECOND)
1988 ntv.status |= STA_DEL;
1992 * Pass the stuff to the kernel. If it squeals, turn off
1993 * the pps. In any case, fetch the kernel offset,
1994 * frequency and jitter.
1996 if (ntp_adjtime(&ntv) == TIME_ERROR) {
1997 if (!(ntv.status & STA_PPSSIGNAL))
1998 report_event(EVNT_KERN, NULL,
2001 pll_status = ntv.status;
2003 clock_offset = ntv.offset / 1e9;
2004 #else /* STA_NANO */
2005 clock_offset = ntv.offset / 1e6;
2006 #endif /* STA_NANO */
2007 clock_frequency = FREQTOD(ntv.freq);
2010 * If the kernel PPS is lit, monitor its performance.
2012 if (ntv.status & STA_PPSTIME) {
2014 clock_jitter = ntv.jitter / 1e9;
2015 #else /* STA_NANO */
2016 clock_jitter = ntv.jitter / 1e6;
2017 #endif /* STA_NANO */
2020 #if defined(STA_NANO) && NTP_API == 4
2022 * If the TAI changes, update the kernel TAI.
2024 if (loop_tai != sys_tai) {
2026 ntv.modes = MOD_TAI;
2027 ntv.constant = sys_tai;
2030 #endif /* STA_NANO */
2032 #endif /* KERNEL_PLL */