summaryrefslogtreecommitdiff
path: root/networking/ntpd.c (plain)
blob: 1532669d3b45e723dd080ad44f0831fb383f0d5e
1/*
2 * NTP client/server, based on OpenNTPD 3.9p1
3 *
4 * Busybox port author: Adam Tkac (C) 2009 <vonsch@gmail.com>
5 *
6 * OpenNTPd 3.9p1 copyright holders:
7 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
8 * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
9 *
10 * OpenNTPd code is licensed under ISC-style licence:
11 *
12 * Permission to use, copy, modify, and distribute this software for any
13 * purpose with or without fee is hereby granted, provided that the above
14 * copyright notice and this permission notice appear in all copies.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
17 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
19 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
21 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
22 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 ***********************************************************************
24 *
25 * Parts of OpenNTPD clock syncronization code is replaced by
26 * code which is based on ntp-4.2.6, which carries the following
27 * copyright notice:
28 *
29 * Copyright (c) University of Delaware 1992-2009
30 *
31 * Permission to use, copy, modify, and distribute this software and
32 * its documentation for any purpose with or without fee is hereby
33 * granted, provided that the above copyright notice appears in all
34 * copies and that both the copyright notice and this permission
35 * notice appear in supporting documentation, and that the name
36 * University of Delaware not be used in advertising or publicity
37 * pertaining to distribution of the software without specific,
38 * written prior permission. The University of Delaware makes no
39 * representations about the suitability this software for any
40 * purpose. It is provided "as is" without express or implied warranty.
41 ***********************************************************************
42 */
43//config:config NTPD
44//config: bool "ntpd"
45//config: default y
46//config: select PLATFORM_LINUX
47//config: help
48//config: The NTP client/server daemon.
49//config:
50//config:config FEATURE_NTPD_SERVER
51//config: bool "Make ntpd usable as a NTP server"
52//config: default y
53//config: depends on NTPD
54//config: help
55//config: Make ntpd usable as a NTP server. If you disable this option
56//config: ntpd will be usable only as a NTP client.
57//config:
58//config:config FEATURE_NTPD_CONF
59//config: bool "Make ntpd understand /etc/ntp.conf"
60//config: default y
61//config: depends on NTPD
62//config: help
63//config: Make ntpd look in /etc/ntp.conf for peers. Only "server address"
64//config: is supported.
65
66//applet:IF_NTPD(APPLET(ntpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
67
68//kbuild:lib-$(CONFIG_NTPD) += ntpd.o
69
70//usage:#define ntpd_trivial_usage
71//usage: "[-dnqNw"IF_FEATURE_NTPD_SERVER("l -I IFACE")"] [-S PROG] [-p PEER]..."
72//usage:#define ntpd_full_usage "\n\n"
73//usage: "NTP client/server\n"
74//usage: "\n -d Verbose"
75//usage: "\n -n Do not daemonize"
76//usage: "\n -q Quit after clock is set"
77//usage: "\n -N Run at high priority"
78//usage: "\n -w Do not set time (only query peers), implies -n"
79//usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 mins"
80//usage: "\n -p PEER Obtain time from PEER (may be repeated)"
81//usage: IF_FEATURE_NTPD_CONF(
82//usage: "\n If -p is not given, 'server HOST' lines"
83//usage: "\n from /etc/ntp.conf are used"
84//usage: )
85//usage: IF_FEATURE_NTPD_SERVER(
86//usage: "\n -l Also run as server on port 123"
87//usage: "\n -I IFACE Bind server to IFACE, implies -l"
88//usage: )
89
90// -l and -p options are not compatible with "standard" ntpd:
91// it has them as "-l logfile" and "-p pidfile".
92// -S and -w are not compat either, "standard" ntpd has no such opts.
93
94#include "libbb.h"
95#include <math.h>
96#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
97#include <sys/resource.h> /* setpriority */
98
99#ifdef __BIONIC__
100#include <linux/timex.h>
101extern int adjtimex (struct timex *);
102#else
103#include <sys/timex.h>
104#endif
105#ifndef IPTOS_LOWDELAY
106# define IPTOS_LOWDELAY 0x10
107#endif
108
109
110/* Verbosity control (max level of -dddd options accepted).
111 * max 6 is very talkative (and bloated). 3 is non-bloated,
112 * production level setting.
113 */
114#define MAX_VERBOSE 3
115
116
117/* High-level description of the algorithm:
118 *
119 * We start running with very small poll_exp, BURSTPOLL,
120 * in order to quickly accumulate INITIAL_SAMPLES datapoints
121 * for each peer. Then, time is stepped if the offset is larger
122 * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
123 * poll_exp to MINPOLL and enter frequency measurement step:
124 * we collect new datapoints but ignore them for WATCH_THRESHOLD
125 * seconds. After WATCH_THRESHOLD seconds we look at accumulated
126 * offset and estimate frequency drift.
127 *
128 * (frequency measurement step seems to not be strictly needed,
129 * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
130 * define set to 0)
131 *
132 * After this, we enter "steady state": we collect a datapoint,
133 * we select the best peer, if this datapoint is not a new one
134 * (IOW: if this datapoint isn't for selected peer), sleep
135 * and collect another one; otherwise, use its offset to update
136 * frequency drift, if offset is somewhat large, reduce poll_exp,
137 * otherwise increase poll_exp.
138 *
139 * If offset is larger than STEP_THRESHOLD, which shouldn't normally
140 * happen, we assume that something "bad" happened (computer
141 * was hibernated, someone set totally wrong date, etc),
142 * then the time is stepped, all datapoints are discarded,
143 * and we go back to steady state.
144 *
145 * Made some changes to speed up re-syncing after our clock goes bad
146 * (tested with suspending my laptop):
147 * - if largish offset (>= STEP_THRESHOLD == 1 sec) is seen
148 * from a peer, schedule next query for this peer soon
149 * without drastically lowering poll interval for everybody.
150 * This makes us collect enough data for step much faster:
151 * e.g. at poll = 10 (1024 secs), step was done within 5 minutes
152 * after first reply which indicated that our clock is 14 seconds off.
153 * - on step, do not discard d_dispersion data of the existing datapoints,
154 * do not clear reachable_bits. This prevents discarding first ~8
155 * datapoints after the step.
156 */
157
158#define INITIAL_SAMPLES 4 /* how many samples do we want for init */
159#define BAD_DELAY_GROWTH 4 /* drop packet if its delay grew by more than this */
160
161#define RETRY_INTERVAL 32 /* on send/recv error, retry in N secs (need to be power of 2) */
162#define NOREPLY_INTERVAL 512 /* sent, but got no reply: cap next query by this many seconds */
163#define RESPONSE_INTERVAL 16 /* wait for reply up to N secs */
164
165/* Step threshold (sec). std ntpd uses 0.128.
166 */
167#define STEP_THRESHOLD 1
168/* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
169 * Using exact power of 2 (1/8) results in smaller code
170 */
171#define SLEW_THRESHOLD 0.125
172/* Stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
173#define WATCH_THRESHOLD 128
174/* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
175//UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
176
177/*
178 * If we got |offset| > BIGOFF from a peer, cap next query interval
179 * for this peer by this many seconds:
180 */
181#define BIGOFF STEP_THRESHOLD
182#define BIGOFF_INTERVAL (1 << 7) /* 128 s */
183
184#define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
185#define BURSTPOLL 0 /* initial poll */
186#define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
187/*
188 * If offset > discipline_jitter * POLLADJ_GATE, and poll interval is > 2^BIGPOLL,
189 * then it is decreased _at once_. (If <= 2^BIGPOLL, it will be decreased _eventually_).
190 */
191#define BIGPOLL 9 /* 2^9 sec ~= 8.5 min */
192#define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
193/*
194 * Actively lower poll when we see such big offsets.
195 * With SLEW_THRESHOLD = 0.125, it means we try to sync more aggressively
196 * if offset increases over ~0.04 sec
197 */
198//#define POLLDOWN_OFFSET (SLEW_THRESHOLD / 3)
199#define MINDISP 0.01 /* minimum dispersion (sec) */
200#define MAXDISP 16 /* maximum dispersion (sec) */
201#define MAXSTRAT 16 /* maximum stratum (infinity metric) */
202#define MAXDIST 1 /* distance threshold (sec) */
203#define MIN_SELECTED 1 /* minimum intersection survivors */
204#define MIN_CLUSTERED 3 /* minimum cluster survivors */
205
206#define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
207
208/* Poll-adjust threshold.
209 * When we see that offset is small enough compared to discipline jitter,
210 * we grow a counter: += MINPOLL. When counter goes over POLLADJ_LIMIT,
211 * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
212 * and when it goes below -POLLADJ_LIMIT, we poll_exp--.
213 * (Bumped from 30 to 40 since otherwise I often see poll_exp going *2* steps down)
214 */
215#define POLLADJ_LIMIT 40
216/* If offset < discipline_jitter * POLLADJ_GATE, then we decide to increase
217 * poll interval (we think we can't improve timekeeping
218 * by staying at smaller poll).
219 */
220#define POLLADJ_GATE 4
221#define TIMECONST_HACK_GATE 2
222/* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
223#define ALLAN 512
224/* PLL loop gain */
225#define PLL 65536
226/* FLL loop gain [why it depends on MAXPOLL??] */
227#define FLL (MAXPOLL + 1)
228/* Parameter averaging constant */
229#define AVG 4
230
231
232enum {
233 NTP_VERSION = 4,
234 NTP_MAXSTRATUM = 15,
235
236 NTP_DIGESTSIZE = 16,
237 NTP_MSGSIZE_NOAUTH = 48,
238 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
239
240 /* Status Masks */
241 MODE_MASK = (7 << 0),
242 VERSION_MASK = (7 << 3),
243 VERSION_SHIFT = 3,
244 LI_MASK = (3 << 6),
245
246 /* Leap Second Codes (high order two bits of m_status) */
247 LI_NOWARNING = (0 << 6), /* no warning */
248 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
249 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
250 LI_ALARM = (3 << 6), /* alarm condition */
251
252 /* Mode values */
253 MODE_RES0 = 0, /* reserved */
254 MODE_SYM_ACT = 1, /* symmetric active */
255 MODE_SYM_PAS = 2, /* symmetric passive */
256 MODE_CLIENT = 3, /* client */
257 MODE_SERVER = 4, /* server */
258 MODE_BROADCAST = 5, /* broadcast */
259 MODE_RES1 = 6, /* reserved for NTP control message */
260 MODE_RES2 = 7, /* reserved for private use */
261};
262
263//TODO: better base selection
264#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
265
266#define NUM_DATAPOINTS 8
267
268typedef struct {
269 uint32_t int_partl;
270 uint32_t fractionl;
271} l_fixedpt_t;
272
273typedef struct {
274 uint16_t int_parts;
275 uint16_t fractions;
276} s_fixedpt_t;
277
278typedef struct {
279 uint8_t m_status; /* status of local clock and leap info */
280 uint8_t m_stratum;
281 uint8_t m_ppoll; /* poll value */
282 int8_t m_precision_exp;
283 s_fixedpt_t m_rootdelay;
284 s_fixedpt_t m_rootdisp;
285 uint32_t m_refid;
286 l_fixedpt_t m_reftime;
287 l_fixedpt_t m_orgtime;
288 l_fixedpt_t m_rectime;
289 l_fixedpt_t m_xmttime;
290 uint32_t m_keyid;
291 uint8_t m_digest[NTP_DIGESTSIZE];
292} msg_t;
293
294typedef struct {
295 double d_offset;
296 double d_recv_time;
297 double d_dispersion;
298} datapoint_t;
299
300typedef struct {
301 len_and_sockaddr *p_lsa;
302 char *p_dotted;
303 int p_fd;
304 int datapoint_idx;
305 uint32_t lastpkt_refid;
306 uint8_t lastpkt_status;
307 uint8_t lastpkt_stratum;
308 uint8_t reachable_bits;
309 /* when to send new query (if p_fd == -1)
310 * or when receive times out (if p_fd >= 0): */
311 double next_action_time;
312 double p_xmttime;
313 double p_raw_delay;
314 /* p_raw_delay is set even by "high delay" packets */
315 /* lastpkt_delay isn't */
316 double lastpkt_recv_time;
317 double lastpkt_delay;
318 double lastpkt_rootdelay;
319 double lastpkt_rootdisp;
320 /* produced by filter algorithm: */
321 double filter_offset;
322 double filter_dispersion;
323 double filter_jitter;
324 datapoint_t filter_datapoint[NUM_DATAPOINTS];
325 /* last sent packet: */
326 msg_t p_xmt_msg;
327 char p_hostname[1];
328} peer_t;
329
330
331#define USING_KERNEL_PLL_LOOP 1
332#define USING_INITIAL_FREQ_ESTIMATION 0
333
334enum {
335 OPT_n = (1 << 0),
336 OPT_q = (1 << 1),
337 OPT_N = (1 << 2),
338 OPT_x = (1 << 3),
339 /* Insert new options above this line. */
340 /* Non-compat options: */
341 OPT_w = (1 << 4),
342 OPT_p = (1 << 5),
343 OPT_S = (1 << 6),
344 OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
345 OPT_I = (1 << 8) * ENABLE_FEATURE_NTPD_SERVER,
346 /* We hijack some bits for other purposes */
347 OPT_qq = (1 << 31),
348};
349
350struct globals {
351 double cur_time;
352 /* total round trip delay to currently selected reference clock */
353 double rootdelay;
354 /* reference timestamp: time when the system clock was last set or corrected */
355 double reftime;
356 /* total dispersion to currently selected reference clock */
357 double rootdisp;
358
359 double last_script_run;
360 char *script_name;
361 llist_t *ntp_peers;
362#if ENABLE_FEATURE_NTPD_SERVER
363 int listen_fd;
364 char *if_name;
365# define G_listen_fd (G.listen_fd)
366#else
367# define G_listen_fd (-1)
368#endif
369 unsigned verbose;
370 unsigned peer_cnt;
371 /* refid: 32-bit code identifying the particular server or reference clock
372 * in stratum 0 packets this is a four-character ASCII string,
373 * called the kiss code, used for debugging and monitoring
374 * in stratum 1 packets this is a four-character ASCII string
375 * assigned to the reference clock by IANA. Example: "GPS "
376 * in stratum 2+ packets, it's IPv4 address or 4 first bytes
377 * of MD5 hash of IPv6
378 */
379 uint32_t refid;
380 uint8_t ntp_status;
381 /* precision is defined as the larger of the resolution and time to
382 * read the clock, in log2 units. For instance, the precision of a
383 * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
384 * system clock hardware representation is to the nanosecond.
385 *
386 * Delays, jitters of various kinds are clamped down to precision.
387 *
388 * If precision_sec is too large, discipline_jitter gets clamped to it
389 * and if offset is smaller than discipline_jitter * POLLADJ_GATE, poll
390 * interval grows even though we really can benefit from staying at
391 * smaller one, collecting non-lagged datapoits and correcting offset.
392 * (Lagged datapoits exist when poll_exp is large but we still have
393 * systematic offset error - the time distance between datapoints
394 * is significant and older datapoints have smaller offsets.
395 * This makes our offset estimation a bit smaller than reality)
396 * Due to this effect, setting G_precision_sec close to
397 * STEP_THRESHOLD isn't such a good idea - offsets may grow
398 * too big and we will step. I observed it with -6.
399 *
400 * OTOH, setting precision_sec far too small would result in futile
401 * attempts to syncronize to an unachievable precision.
402 *
403 * -6 is 1/64 sec, -7 is 1/128 sec and so on.
404 * -8 is 1/256 ~= 0.003906 (worked well for me --vda)
405 * -9 is 1/512 ~= 0.001953 (let's try this for some time)
406 */
407#define G_precision_exp -9
408 /*
409 * G_precision_exp is used only for construction outgoing packets.
410 * It's ok to set G_precision_sec to a slightly different value
411 * (One which is "nicer looking" in logs).
412 * Exact value would be (1.0 / (1 << (- G_precision_exp))):
413 */
414#define G_precision_sec 0.002
415 uint8_t stratum;
416
417#define STATE_NSET 0 /* initial state, "nothing is set" */
418//#define STATE_FSET 1 /* frequency set from file */
419//#define STATE_SPIK 2 /* spike detected */
420//#define STATE_FREQ 3 /* initial frequency */
421#define STATE_SYNC 4 /* clock synchronized (normal operation) */
422 uint8_t discipline_state; // doc calls it c.state
423 uint8_t poll_exp; // s.poll
424 int polladj_count; // c.count
425 long kernel_freq_drift;
426 peer_t *last_update_peer;
427 double last_update_offset; // c.last
428 double last_update_recv_time; // s.t
429 double discipline_jitter; // c.jitter
430 /* Since we only compare it with ints, can simplify code
431 * by not making this variable floating point:
432 */
433 unsigned offset_to_jitter_ratio;
434 //double cluster_offset; // s.offset
435 //double cluster_jitter; // s.jitter
436#if !USING_KERNEL_PLL_LOOP
437 double discipline_freq_drift; // c.freq
438 /* Maybe conditionally calculate wander? it's used only for logging */
439 double discipline_wander; // c.wander
440#endif
441};
442#define G (*ptr_to_globals)
443
444
445#define VERB1 if (MAX_VERBOSE && G.verbose)
446#define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
447#define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
448#define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
449#define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
450#define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
451
452
453static double LOG2D(int a)
454{
455 if (a < 0)
456 return 1.0 / (1UL << -a);
457 return 1UL << a;
458}
459static ALWAYS_INLINE double SQUARE(double x)
460{
461 return x * x;
462}
463static ALWAYS_INLINE double MAXD(double a, double b)
464{
465 if (a > b)
466 return a;
467 return b;
468}
469static ALWAYS_INLINE double MIND(double a, double b)
470{
471 if (a < b)
472 return a;
473 return b;
474}
475static NOINLINE double my_SQRT(double X)
476{
477 union {
478 float f;
479 int32_t i;
480 } v;
481 double invsqrt;
482 double Xhalf = X * 0.5;
483
484 /* Fast and good approximation to 1/sqrt(X), black magic */
485 v.f = X;
486 /*v.i = 0x5f3759df - (v.i >> 1);*/
487 v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
488 invsqrt = v.f; /* better than 0.2% accuracy */
489
490 /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
491 * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
492 * f'(x) = -2/(x*x*x)
493 * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
494 * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
495 */
496 invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
497 /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
498 /* With 4 iterations, more than half results will be exact,
499 * at 6th iterations result stabilizes with about 72% results exact.
500 * We are well satisfied with 0.05% accuracy.
501 */
502
503 return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
504}
505static ALWAYS_INLINE double SQRT(double X)
506{
507 /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
508 if (sizeof(float) != 4)
509 return sqrt(X);
510
511 /* This avoids needing libm, saves about 0.5k on x86-32 */
512 return my_SQRT(X);
513}
514
515static double
516gettime1900d(void)
517{
518 struct timeval tv;
519 gettimeofday(&tv, NULL); /* never fails */
520 G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
521 return G.cur_time;
522}
523
524static void
525d_to_tv(double d, struct timeval *tv)
526{
527 tv->tv_sec = (long)d;
528 tv->tv_usec = (d - tv->tv_sec) * 1000000;
529}
530
531static double
532lfp_to_d(l_fixedpt_t lfp)
533{
534 double ret;
535 lfp.int_partl = ntohl(lfp.int_partl);
536 lfp.fractionl = ntohl(lfp.fractionl);
537 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
538 return ret;
539}
540static double
541sfp_to_d(s_fixedpt_t sfp)
542{
543 double ret;
544 sfp.int_parts = ntohs(sfp.int_parts);
545 sfp.fractions = ntohs(sfp.fractions);
546 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
547 return ret;
548}
549#if ENABLE_FEATURE_NTPD_SERVER
550static l_fixedpt_t
551d_to_lfp(double d)
552{
553 l_fixedpt_t lfp;
554 lfp.int_partl = (uint32_t)d;
555 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
556 lfp.int_partl = htonl(lfp.int_partl);
557 lfp.fractionl = htonl(lfp.fractionl);
558 return lfp;
559}
560static s_fixedpt_t
561d_to_sfp(double d)
562{
563 s_fixedpt_t sfp;
564 sfp.int_parts = (uint16_t)d;
565 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
566 sfp.int_parts = htons(sfp.int_parts);
567 sfp.fractions = htons(sfp.fractions);
568 return sfp;
569}
570#endif
571
572static double
573dispersion(const datapoint_t *dp)
574{
575 return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
576}
577
578static double
579root_distance(peer_t *p)
580{
581 /* The root synchronization distance is the maximum error due to
582 * all causes of the local clock relative to the primary server.
583 * It is defined as half the total delay plus total dispersion
584 * plus peer jitter.
585 */
586 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
587 + p->lastpkt_rootdisp
588 + p->filter_dispersion
589 + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
590 + p->filter_jitter;
591}
592
593static void
594set_next(peer_t *p, unsigned t)
595{
596 p->next_action_time = G.cur_time + t;
597}
598
599/*
600 * Peer clock filter and its helpers
601 */
602static void
603filter_datapoints(peer_t *p)
604{
605 int i, idx;
606 double sum, wavg;
607 datapoint_t *fdp;
608
609#if 0
610/* Simulations have shown that use of *averaged* offset for p->filter_offset
611 * is in fact worse than simply using last received one: with large poll intervals
612 * (>= 2048) averaging code uses offset values which are outdated by hours,
613 * and time/frequency correction goes totally wrong when fed essentially bogus offsets.
614 */
615 int got_newest;
616 double minoff, maxoff, w;
617 double x = x; /* for compiler */
618 double oldest_off = oldest_off;
619 double oldest_age = oldest_age;
620 double newest_off = newest_off;
621 double newest_age = newest_age;
622
623 fdp = p->filter_datapoint;
624
625 minoff = maxoff = fdp[0].d_offset;
626 for (i = 1; i < NUM_DATAPOINTS; i++) {
627 if (minoff > fdp[i].d_offset)
628 minoff = fdp[i].d_offset;
629 if (maxoff < fdp[i].d_offset)
630 maxoff = fdp[i].d_offset;
631 }
632
633 idx = p->datapoint_idx; /* most recent datapoint's index */
634 /* Average offset:
635 * Drop two outliers and take weighted average of the rest:
636 * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
637 * we use older6/32, not older6/64 since sum of weights should be 1:
638 * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
639 */
640 wavg = 0;
641 w = 0.5;
642 /* n-1
643 * --- dispersion(i)
644 * filter_dispersion = \ -------------
645 * / (i+1)
646 * --- 2
647 * i=0
648 */
649 got_newest = 0;
650 sum = 0;
651 for (i = 0; i < NUM_DATAPOINTS; i++) {
652 VERB5 {
653 bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
654 i,
655 fdp[idx].d_offset,
656 fdp[idx].d_dispersion, dispersion(&fdp[idx]),
657 G.cur_time - fdp[idx].d_recv_time,
658 (minoff == fdp[idx].d_offset || maxoff == fdp[idx].d_offset)
659 ? " (outlier by offset)" : ""
660 );
661 }
662
663 sum += dispersion(&fdp[idx]) / (2 << i);
664
665 if (minoff == fdp[idx].d_offset) {
666 minoff -= 1; /* so that we don't match it ever again */
667 } else
668 if (maxoff == fdp[idx].d_offset) {
669 maxoff += 1;
670 } else {
671 oldest_off = fdp[idx].d_offset;
672 oldest_age = G.cur_time - fdp[idx].d_recv_time;
673 if (!got_newest) {
674 got_newest = 1;
675 newest_off = oldest_off;
676 newest_age = oldest_age;
677 }
678 x = oldest_off * w;
679 wavg += x;
680 w /= 2;
681 }
682
683 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
684 }
685 p->filter_dispersion = sum;
686 wavg += x; /* add another older6/64 to form older6/32 */
687 /* Fix systematic underestimation with large poll intervals.
688 * Imagine that we still have a bit of uncorrected drift,
689 * and poll interval is big (say, 100 sec). Offsets form a progression:
690 * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
691 * The algorithm above drops 0.0 and 0.7 as outliers,
692 * and then we have this estimation, ~25% off from 0.7:
693 * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
694 */
695 x = oldest_age - newest_age;
696 if (x != 0) {
697 x = newest_age / x; /* in above example, 100 / (600 - 100) */
698 if (x < 1) { /* paranoia check */
699 x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
700 wavg += x;
701 }
702 }
703 p->filter_offset = wavg;
704
705#else
706
707 fdp = p->filter_datapoint;
708 idx = p->datapoint_idx; /* most recent datapoint's index */
709
710 /* filter_offset: simply use the most recent value */
711 p->filter_offset = fdp[idx].d_offset;
712
713 /* n-1
714 * --- dispersion(i)
715 * filter_dispersion = \ -------------
716 * / (i+1)
717 * --- 2
718 * i=0
719 */
720 wavg = 0;
721 sum = 0;
722 for (i = 0; i < NUM_DATAPOINTS; i++) {
723 sum += dispersion(&fdp[idx]) / (2 << i);
724 wavg += fdp[idx].d_offset;
725 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
726 }
727 wavg /= NUM_DATAPOINTS;
728 p->filter_dispersion = sum;
729#endif
730
731 /* +----- -----+ ^ 1/2
732 * | n-1 |
733 * | --- |
734 * | 1 \ 2 |
735 * filter_jitter = | --- * / (avg-offset_j) |
736 * | n --- |
737 * | j=0 |
738 * +----- -----+
739 * where n is the number of valid datapoints in the filter (n > 1);
740 * if filter_jitter < precision then filter_jitter = precision
741 */
742 sum = 0;
743 for (i = 0; i < NUM_DATAPOINTS; i++) {
744 sum += SQUARE(wavg - fdp[i].d_offset);
745 }
746 sum = SQRT(sum / NUM_DATAPOINTS);
747 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
748
749 VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
750 p->filter_offset,
751 p->filter_dispersion,
752 p->filter_jitter);
753}
754
755static void
756reset_peer_stats(peer_t *p, double offset)
757{
758 int i;
759 bool small_ofs = fabs(offset) < STEP_THRESHOLD;
760
761 /* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
762 * and clear reachable bits, but this proved to be too agressive:
763 * after step (tested with suspending laptop for ~30 secs),
764 * this caused all previous data to be considered invalid,
765 * making us needing to collect full ~8 datapoins per peer
766 * after step in order to start trusting them.
767 * In turn, this was making poll interval decrease even after
768 * step was done. (Poll interval decreases already before step
769 * in this scenario, because we see large offsets and end up with
770 * no good peer to select).
771 */
772
773 for (i = 0; i < NUM_DATAPOINTS; i++) {
774 if (small_ofs) {
775 p->filter_datapoint[i].d_recv_time += offset;
776 if (p->filter_datapoint[i].d_offset != 0) {
777 p->filter_datapoint[i].d_offset -= offset;
778 //bb_error_msg("p->filter_datapoint[%d].d_offset %f -> %f",
779 // i,
780 // p->filter_datapoint[i].d_offset + offset,
781 // p->filter_datapoint[i].d_offset);
782 }
783 } else {
784 p->filter_datapoint[i].d_recv_time = G.cur_time;
785 p->filter_datapoint[i].d_offset = 0;
786 /*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
787 }
788 }
789 if (small_ofs) {
790 p->lastpkt_recv_time += offset;
791 } else {
792 /*p->reachable_bits = 0;*/
793 p->lastpkt_recv_time = G.cur_time;
794 }
795 filter_datapoints(p); /* recalc p->filter_xxx */
796 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
797}
798
799static void
800resolve_peer_hostname(peer_t *p, int loop_on_fail)
801{
802 len_and_sockaddr *lsa;
803
804 again:
805 lsa = host2sockaddr(p->p_hostname, 123);
806 if (!lsa) {
807 /* error message already emitted by host2sockaddr() */
808 if (!loop_on_fail)
809 return;
810//FIXME: do this to avoid infinite looping on typo in a hostname?
811//well... in which case, what is a good value for loop_on_fail?
812 //if (--loop_on_fail == 0)
813 // xfunc_die();
814 sleep(5);
815 goto again;
816 }
817 free(p->p_lsa);
818 free(p->p_dotted);
819 p->p_lsa = lsa;
820 p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
821}
822
823static void
824add_peers(const char *s)
825{
826 llist_t *item;
827 peer_t *p;
828
829 p = xzalloc(sizeof(*p) + strlen(s));
830 strcpy(p->p_hostname, s);
831 resolve_peer_hostname(p, /*loop_on_fail=*/ 1);
832
833 /* Names like N.<country2chars>.pool.ntp.org are randomly resolved
834 * to a pool of machines. Sometimes different N's resolve to the same IP.
835 * It is not useful to have two peers with same IP. We skip duplicates.
836 */
837 for (item = G.ntp_peers; item != NULL; item = item->link) {
838 peer_t *pp = (peer_t *) item->data;
839 if (strcmp(p->p_dotted, pp->p_dotted) == 0) {
840 bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
841 free(p->p_lsa);
842 free(p->p_dotted);
843 free(p);
844 return;
845 }
846 }
847
848 p->p_fd = -1;
849 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
850 p->next_action_time = G.cur_time; /* = set_next(p, 0); */
851 reset_peer_stats(p, STEP_THRESHOLD);
852
853 llist_add_to(&G.ntp_peers, p);
854 G.peer_cnt++;
855}
856
857static int
858do_sendto(int fd,
859 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
860 msg_t *msg, ssize_t len)
861{
862 ssize_t ret;
863
864 errno = 0;
865 if (!from) {
866 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
867 } else {
868 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
869 }
870 if (ret != len) {
871 bb_perror_msg("send failed");
872 return -1;
873 }
874 return 0;
875}
876
877static void
878send_query_to_peer(peer_t *p)
879{
880 /* Why do we need to bind()?
881 * See what happens when we don't bind:
882 *
883 * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
884 * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
885 * gettimeofday({1259071266, 327885}, NULL) = 0
886 * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
887 * ^^^ we sent it from some source port picked by kernel.
888 * time(NULL) = 1259071266
889 * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
890 * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
891 * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
892 * ^^^ this recv will receive packets to any local port!
893 *
894 * Uncomment this and use strace to see it in action:
895 */
896#define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
897
898 if (p->p_fd == -1) {
899 int fd, family;
900 len_and_sockaddr *local_lsa;
901
902 family = p->p_lsa->u.sa.sa_family;
903 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
904 /* local_lsa has "null" address and port 0 now.
905 * bind() ensures we have a *particular port* selected by kernel
906 * and remembered in p->p_fd, thus later recv(p->p_fd)
907 * receives only packets sent to this port.
908 */
909 PROBE_LOCAL_ADDR
910 xbind(fd, &local_lsa->u.sa, local_lsa->len);
911 PROBE_LOCAL_ADDR
912#if ENABLE_FEATURE_IPV6
913 if (family == AF_INET)
914#endif
915 setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY);
916 free(local_lsa);
917 }
918
919 /* Emit message _before_ attempted send. Think of a very short
920 * roundtrip networks: we need to go back to recv loop ASAP,
921 * to reduce delay. Printing messages after send works against that.
922 */
923 VERB1 bb_error_msg("sending query to %s", p->p_dotted);
924
925 /*
926 * Send out a random 64-bit number as our transmit time. The NTP
927 * server will copy said number into the originate field on the
928 * response that it sends us. This is totally legal per the SNTP spec.
929 *
930 * The impact of this is two fold: we no longer send out the current
931 * system time for the world to see (which may aid an attacker), and
932 * it gives us a (not very secure) way of knowing that we're not
933 * getting spoofed by an attacker that can't capture our traffic
934 * but can spoof packets from the NTP server we're communicating with.
935 *
936 * Save the real transmit timestamp locally.
937 */
938 p->p_xmt_msg.m_xmttime.int_partl = rand();
939 p->p_xmt_msg.m_xmttime.fractionl = rand();
940 p->p_xmttime = gettime1900d();
941
942 /* Were doing it only if sendto worked, but
943 * loss of sync detection needs reachable_bits updated
944 * even if sending fails *locally*:
945 * "network is unreachable" because cable was pulled?
946 * We still need to declare "unsync" if this condition persists.
947 */
948 p->reachable_bits <<= 1;
949
950 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
951 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
952 ) {
953 close(p->p_fd);
954 p->p_fd = -1;
955 /*
956 * We know that we sent nothing.
957 * We can retry *soon* without fearing
958 * that we are flooding the peer.
959 */
960 set_next(p, RETRY_INTERVAL);
961 return;
962 }
963
964 set_next(p, RESPONSE_INTERVAL);
965}
966
967
968/* Note that there is no provision to prevent several run_scripts
969 * to be started in quick succession. In fact, it happens rather often
970 * if initial syncronization results in a step.
971 * You will see "step" and then "stratum" script runs, sometimes
972 * as close as only 0.002 seconds apart.
973 * Script should be ready to deal with this.
974 */
975static void run_script(const char *action, double offset)
976{
977 char *argv[3];
978 char *env1, *env2, *env3, *env4;
979
980 G.last_script_run = G.cur_time;
981
982 if (!G.script_name)
983 return;
984
985 argv[0] = (char*) G.script_name;
986 argv[1] = (char*) action;
987 argv[2] = NULL;
988
989 VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
990
991 env1 = xasprintf("%s=%u", "stratum", G.stratum);
992 putenv(env1);
993 env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
994 putenv(env2);
995 env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
996 putenv(env3);
997 env4 = xasprintf("%s=%f", "offset", offset);
998 putenv(env4);
999 /* Other items of potential interest: selected peer,
1000 * rootdelay, reftime, rootdisp, refid, ntp_status,
1001 * last_update_offset, last_update_recv_time, discipline_jitter,
1002 * how many peers have reachable_bits = 0?
1003 */
1004
1005 /* Don't want to wait: it may run hwclock --systohc, and that
1006 * may take some time (seconds): */
1007 /*spawn_and_wait(argv);*/
1008 spawn(argv);
1009
1010 unsetenv("stratum");
1011 unsetenv("freq_drift_ppm");
1012 unsetenv("poll_interval");
1013 unsetenv("offset");
1014 free(env1);
1015 free(env2);
1016 free(env3);
1017 free(env4);
1018}
1019
1020static NOINLINE void
1021step_time(double offset)
1022{
1023 llist_t *item;
1024 double dtime;
1025 struct timeval tvc, tvn;
1026 char buf[sizeof("yyyy-mm-dd hh:mm:ss") + /*paranoia:*/ 4];
1027 time_t tval;
1028
1029 gettimeofday(&tvc, NULL); /* never fails */
1030 dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
1031 d_to_tv(dtime, &tvn);
1032 if (settimeofday(&tvn, NULL) == -1)
1033 bb_perror_msg_and_die("settimeofday");
1034
1035 VERB2 {
1036 tval = tvc.tv_sec;
1037 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1038 bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
1039 }
1040 tval = tvn.tv_sec;
1041 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1042 bb_error_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
1043
1044 /* Correct various fields which contain time-relative values: */
1045
1046 /* Globals: */
1047 G.cur_time += offset;
1048 G.last_update_recv_time += offset;
1049 G.last_script_run += offset;
1050
1051 /* p->lastpkt_recv_time, p->next_action_time and such: */
1052 for (item = G.ntp_peers; item != NULL; item = item->link) {
1053 peer_t *pp = (peer_t *) item->data;
1054 reset_peer_stats(pp, offset);
1055 //bb_error_msg("offset:%+f pp->next_action_time:%f -> %f",
1056 // offset, pp->next_action_time, pp->next_action_time + offset);
1057 pp->next_action_time += offset;
1058 if (pp->p_fd >= 0) {
1059 /* We wait for reply from this peer too.
1060 * But due to step we are doing, reply's data is no longer
1061 * useful (in fact, it'll be bogus). Stop waiting for it.
1062 */
1063 close(pp->p_fd);
1064 pp->p_fd = -1;
1065 set_next(pp, RETRY_INTERVAL);
1066 }
1067 }
1068}
1069
1070static void clamp_pollexp_and_set_MAXSTRAT(void)
1071{
1072 if (G.poll_exp < MINPOLL)
1073 G.poll_exp = MINPOLL;
1074 if (G.poll_exp > BIGPOLL)
1075 G.poll_exp = BIGPOLL;
1076 G.polladj_count = 0;
1077 G.stratum = MAXSTRAT;
1078}
1079
1080
1081/*
1082 * Selection and clustering, and their helpers
1083 */
1084typedef struct {
1085 peer_t *p;
1086 int type;
1087 double edge;
1088 double opt_rd; /* optimization */
1089} point_t;
1090static int
1091compare_point_edge(const void *aa, const void *bb)
1092{
1093 const point_t *a = aa;
1094 const point_t *b = bb;
1095 if (a->edge < b->edge) {
1096 return -1;
1097 }
1098 return (a->edge > b->edge);
1099}
1100typedef struct {
1101 peer_t *p;
1102 double metric;
1103} survivor_t;
1104static int
1105compare_survivor_metric(const void *aa, const void *bb)
1106{
1107 const survivor_t *a = aa;
1108 const survivor_t *b = bb;
1109 if (a->metric < b->metric) {
1110 return -1;
1111 }
1112 return (a->metric > b->metric);
1113}
1114static int
1115fit(peer_t *p, double rd)
1116{
1117 if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
1118 /* One or zero bits in reachable_bits */
1119 VERB4 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
1120 return 0;
1121 }
1122#if 0 /* we filter out such packets earlier */
1123 if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
1124 || p->lastpkt_stratum >= MAXSTRAT
1125 ) {
1126 VERB4 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
1127 return 0;
1128 }
1129#endif
1130 /* rd is root_distance(p) */
1131 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
1132 VERB4 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
1133 return 0;
1134 }
1135//TODO
1136// /* Do we have a loop? */
1137// if (p->refid == p->dstaddr || p->refid == s.refid)
1138// return 0;
1139 return 1;
1140}
1141static peer_t*
1142select_and_cluster(void)
1143{
1144 peer_t *p;
1145 llist_t *item;
1146 int i, j;
1147 int size = 3 * G.peer_cnt;
1148 /* for selection algorithm */
1149 point_t point[size];
1150 int num_points, num_candidates;
1151 double low, high;
1152 int num_falsetickers;
1153 /* for cluster algorithm */
1154 survivor_t survivor[size];
1155 int num_survivors;
1156
1157 /* Selection */
1158
1159 num_points = 0;
1160 item = G.ntp_peers;
1161 while (item != NULL) {
1162 double rd, offset;
1163
1164 p = (peer_t *) item->data;
1165 rd = root_distance(p);
1166 offset = p->filter_offset;
1167 if (!fit(p, rd)) {
1168 item = item->link;
1169 continue;
1170 }
1171
1172 VERB5 bb_error_msg("interval: [%f %f %f] %s",
1173 offset - rd,
1174 offset,
1175 offset + rd,
1176 p->p_dotted
1177 );
1178 point[num_points].p = p;
1179 point[num_points].type = -1;
1180 point[num_points].edge = offset - rd;
1181 point[num_points].opt_rd = rd;
1182 num_points++;
1183 point[num_points].p = p;
1184 point[num_points].type = 0;
1185 point[num_points].edge = offset;
1186 point[num_points].opt_rd = rd;
1187 num_points++;
1188 point[num_points].p = p;
1189 point[num_points].type = 1;
1190 point[num_points].edge = offset + rd;
1191 point[num_points].opt_rd = rd;
1192 num_points++;
1193 item = item->link;
1194 }
1195 num_candidates = num_points / 3;
1196 if (num_candidates == 0) {
1197 VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
1198 return NULL;
1199 }
1200//TODO: sorting does not seem to be done in reference code
1201 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
1202
1203 /* Start with the assumption that there are no falsetickers.
1204 * Attempt to find a nonempty intersection interval containing
1205 * the midpoints of all truechimers.
1206 * If a nonempty interval cannot be found, increase the number
1207 * of assumed falsetickers by one and try again.
1208 * If a nonempty interval is found and the number of falsetickers
1209 * is less than the number of truechimers, a majority has been found
1210 * and the midpoint of each truechimer represents
1211 * the candidates available to the cluster algorithm.
1212 */
1213 num_falsetickers = 0;
1214 while (1) {
1215 int c;
1216 int num_midpoints = 0;
1217
1218 low = 1 << 9;
1219 high = - (1 << 9);
1220 c = 0;
1221 for (i = 0; i < (int) num_points; i++) {
1222 /* We want to do:
1223 * if (point[i].type == -1) c++;
1224 * if (point[i].type == 1) c--;
1225 * and it's simpler to do it this way:
1226 */
1227 c -= point[i].type;
1228 if (c >= num_candidates - num_falsetickers) {
1229 /* If it was c++ and it got big enough... */
1230 low = point[i].edge;
1231 break;
1232 }
1233 if (point[i].type == 0)
1234 num_midpoints++;
1235 }
1236 c = 0;
1237 for (i = num_points-1; i >= 0; i--) {
1238 c += point[i].type;
1239 if (c >= num_candidates - num_falsetickers) {
1240 high = point[i].edge;
1241 break;
1242 }
1243 if (point[i].type == 0)
1244 num_midpoints++;
1245 }
1246 /* If the number of midpoints is greater than the number
1247 * of allowed falsetickers, the intersection contains at
1248 * least one truechimer with no midpoint - bad.
1249 * Also, interval should be nonempty.
1250 */
1251 if (num_midpoints <= num_falsetickers && low < high)
1252 break;
1253 num_falsetickers++;
1254 if (num_falsetickers * 2 >= num_candidates) {
1255 VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
1256 num_falsetickers, num_candidates,
1257 ", no peer selected");
1258 return NULL;
1259 }
1260 }
1261 VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
1262 low, high, num_candidates, num_falsetickers);
1263
1264 /* Clustering */
1265
1266 /* Construct a list of survivors (p, metric)
1267 * from the chime list, where metric is dominated
1268 * first by stratum and then by root distance.
1269 * All other things being equal, this is the order of preference.
1270 */
1271 num_survivors = 0;
1272 for (i = 0; i < num_points; i++) {
1273 if (point[i].edge < low || point[i].edge > high)
1274 continue;
1275 p = point[i].p;
1276 survivor[num_survivors].p = p;
1277 /* x.opt_rd == root_distance(p); */
1278 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
1279 VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
1280 num_survivors, survivor[num_survivors].metric, p->p_dotted);
1281 num_survivors++;
1282 }
1283 /* There must be at least MIN_SELECTED survivors to satisfy the
1284 * correctness assertions. Ordinarily, the Byzantine criteria
1285 * require four survivors, but for the demonstration here, one
1286 * is acceptable.
1287 */
1288 if (num_survivors < MIN_SELECTED) {
1289 VERB3 bb_error_msg("survivors:%d%s",
1290 num_survivors,
1291 ", no peer selected");
1292 return NULL;
1293 }
1294
1295//looks like this is ONLY used by the fact that later we pick survivor[0].
1296//we can avoid sorting then, just find the minimum once!
1297 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1298
1299 /* For each association p in turn, calculate the selection
1300 * jitter p->sjitter as the square root of the sum of squares
1301 * (p->offset - q->offset) over all q associations. The idea is
1302 * to repeatedly discard the survivor with maximum selection
1303 * jitter until a termination condition is met.
1304 */
1305 while (1) {
1306 static int max_idx;
1307 double max_selection_jitter = max_selection_jitter;
1308 double min_jitter = min_jitter;
1309
1310 if (num_survivors <= MIN_CLUSTERED) {
1311 VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
1312 num_survivors, MIN_CLUSTERED);
1313 break;
1314 }
1315
1316 /* To make sure a few survivors are left
1317 * for the clustering algorithm to chew on,
1318 * we stop if the number of survivors
1319 * is less than or equal to MIN_CLUSTERED (3).
1320 */
1321 for (i = 0; i < num_survivors; i++) {
1322 double selection_jitter_sq;
1323
1324 p = survivor[i].p;
1325 if (i == 0 || p->filter_jitter < min_jitter)
1326 min_jitter = p->filter_jitter;
1327
1328 selection_jitter_sq = 0;
1329 for (j = 0; j < num_survivors; j++) {
1330 peer_t *q = survivor[j].p;
1331 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1332 }
1333 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1334 max_selection_jitter = selection_jitter_sq;
1335 max_idx = i;
1336 }
1337 VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
1338 i, selection_jitter_sq);
1339 }
1340 max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
1341 VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1342 max_idx, max_selection_jitter, min_jitter);
1343
1344 /* If the maximum selection jitter is less than the
1345 * minimum peer jitter, then tossing out more survivors
1346 * will not lower the minimum peer jitter, so we might
1347 * as well stop.
1348 */
1349 if (max_selection_jitter < min_jitter) {
1350 VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1351 max_selection_jitter, min_jitter, num_survivors);
1352 break;
1353 }
1354
1355 /* Delete survivor[max_idx] from the list
1356 * and go around again.
1357 */
1358 VERB6 bb_error_msg("dropping survivor %d", max_idx);
1359 num_survivors--;
1360 while (max_idx < num_survivors) {
1361 survivor[max_idx] = survivor[max_idx + 1];
1362 max_idx++;
1363 }
1364 }
1365
1366 if (0) {
1367 /* Combine the offsets of the clustering algorithm survivors
1368 * using a weighted average with weight determined by the root
1369 * distance. Compute the selection jitter as the weighted RMS
1370 * difference between the first survivor and the remaining
1371 * survivors. In some cases the inherent clock jitter can be
1372 * reduced by not using this algorithm, especially when frequent
1373 * clockhopping is involved. bbox: thus we don't do it.
1374 */
1375 double x, y, z, w;
1376 y = z = w = 0;
1377 for (i = 0; i < num_survivors; i++) {
1378 p = survivor[i].p;
1379 x = root_distance(p);
1380 y += 1 / x;
1381 z += p->filter_offset / x;
1382 w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1383 }
1384 //G.cluster_offset = z / y;
1385 //G.cluster_jitter = SQRT(w / y);
1386 }
1387
1388 /* Pick the best clock. If the old system peer is on the list
1389 * and at the same stratum as the first survivor on the list,
1390 * then don't do a clock hop. Otherwise, select the first
1391 * survivor on the list as the new system peer.
1392 */
1393 p = survivor[0].p;
1394 if (G.last_update_peer
1395 && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1396 ) {
1397 /* Starting from 1 is ok here */
1398 for (i = 1; i < num_survivors; i++) {
1399 if (G.last_update_peer == survivor[i].p) {
1400 VERB5 bb_error_msg("keeping old synced peer");
1401 p = G.last_update_peer;
1402 goto keep_old;
1403 }
1404 }
1405 }
1406 G.last_update_peer = p;
1407 keep_old:
1408 VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
1409 p->p_dotted,
1410 p->filter_offset,
1411 G.cur_time - p->lastpkt_recv_time
1412 );
1413 return p;
1414}
1415
1416
1417/*
1418 * Local clock discipline and its helpers
1419 */
1420static void
1421set_new_values(int disc_state, double offset, double recv_time)
1422{
1423 /* Enter new state and set state variables. Note we use the time
1424 * of the last clock filter sample, which must be earlier than
1425 * the current time.
1426 */
1427 VERB4 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
1428 disc_state, offset, recv_time);
1429 G.discipline_state = disc_state;
1430 G.last_update_offset = offset;
1431 G.last_update_recv_time = recv_time;
1432}
1433/* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
1434static NOINLINE int
1435update_local_clock(peer_t *p)
1436{
1437 int rc;
1438 struct timex tmx;
1439 /* Note: can use G.cluster_offset instead: */
1440 double offset = p->filter_offset;
1441 double recv_time = p->lastpkt_recv_time;
1442 double abs_offset;
1443#if !USING_KERNEL_PLL_LOOP
1444 double freq_drift;
1445#endif
1446#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1447 double since_last_update;
1448#endif
1449 double etemp, dtemp;
1450
1451 abs_offset = fabs(offset);
1452
1453#if 0
1454 /* If needed, -S script can do it by looking at $offset
1455 * env var and killing parent */
1456 /* If the offset is too large, give up and go home */
1457 if (abs_offset > PANIC_THRESHOLD) {
1458 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1459 }
1460#endif
1461
1462 /* If this is an old update, for instance as the result
1463 * of a system peer change, avoid it. We never use
1464 * an old sample or the same sample twice.
1465 */
1466 if (recv_time <= G.last_update_recv_time) {
1467 VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
1468 p->p_dotted);
1469 return 0; /* "leave poll interval as is" */
1470 }
1471
1472 /* Clock state machine transition function. This is where the
1473 * action is and defines how the system reacts to large time
1474 * and frequency errors.
1475 */
1476#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1477 since_last_update = recv_time - G.reftime;
1478#endif
1479#if !USING_KERNEL_PLL_LOOP
1480 freq_drift = 0;
1481#endif
1482#if USING_INITIAL_FREQ_ESTIMATION
1483 if (G.discipline_state == STATE_FREQ) {
1484 /* Ignore updates until the stepout threshold */
1485 if (since_last_update < WATCH_THRESHOLD) {
1486 VERB4 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1487 WATCH_THRESHOLD - since_last_update);
1488 return 0; /* "leave poll interval as is" */
1489 }
1490# if !USING_KERNEL_PLL_LOOP
1491 freq_drift = (offset - G.last_update_offset) / since_last_update;
1492# endif
1493 }
1494#endif
1495
1496 /* There are two main regimes: when the
1497 * offset exceeds the step threshold and when it does not.
1498 */
1499 if (abs_offset > STEP_THRESHOLD) {
1500#if 0
1501 double remains;
1502
1503// This "spike state" seems to be useless, peer selection already drops
1504// occassional "bad" datapoints. If we are here, there were _many_
1505// large offsets. When a few first large offsets are seen,
1506// we end up in "no valid datapoints, no peer selected" state.
1507// Only when enough of them are seen (which means it's not a fluke),
1508// we end up here. Looks like _our_ clock is off.
1509 switch (G.discipline_state) {
1510 case STATE_SYNC:
1511 /* The first outlyer: ignore it, switch to SPIK state */
1512 VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1513 p->p_dotted, offset,
1514 "");
1515 G.discipline_state = STATE_SPIK;
1516 return -1; /* "decrease poll interval" */
1517
1518 case STATE_SPIK:
1519 /* Ignore succeeding outlyers until either an inlyer
1520 * is found or the stepout threshold is exceeded.
1521 */
1522 remains = WATCH_THRESHOLD - since_last_update;
1523 if (remains > 0) {
1524 VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1525 p->p_dotted, offset,
1526 ", datapoint ignored");
1527 return -1; /* "decrease poll interval" */
1528 }
1529 /* fall through: we need to step */
1530 } /* switch */
1531#endif
1532
1533 /* Step the time and clamp down the poll interval.
1534 *
1535 * In NSET state an initial frequency correction is
1536 * not available, usually because the frequency file has
1537 * not yet been written. Since the time is outside the
1538 * capture range, the clock is stepped. The frequency
1539 * will be set directly following the stepout interval.
1540 *
1541 * In FSET state the initial frequency has been set
1542 * from the frequency file. Since the time is outside
1543 * the capture range, the clock is stepped immediately,
1544 * rather than after the stepout interval. Guys get
1545 * nervous if it takes 17 minutes to set the clock for
1546 * the first time.
1547 *
1548 * In SPIK state the stepout threshold has expired and
1549 * the phase is still above the step threshold. Note
1550 * that a single spike greater than the step threshold
1551 * is always suppressed, even at the longer poll
1552 * intervals.
1553 */
1554 VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
1555 step_time(offset);
1556 if (option_mask32 & OPT_q) {
1557 /* We were only asked to set time once. Done. */
1558 exit(0);
1559 }
1560
1561 clamp_pollexp_and_set_MAXSTRAT();
1562
1563 run_script("step", offset);
1564
1565 recv_time += offset;
1566
1567#if USING_INITIAL_FREQ_ESTIMATION
1568 if (G.discipline_state == STATE_NSET) {
1569 set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1570 return 1; /* "ok to increase poll interval" */
1571 }
1572#endif
1573 abs_offset = offset = 0;
1574 set_new_values(STATE_SYNC, offset, recv_time);
1575 } else { /* abs_offset <= STEP_THRESHOLD */
1576
1577 /* The ratio is calculated before jitter is updated to make
1578 * poll adjust code more sensitive to large offsets.
1579 */
1580 G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
1581
1582 /* Compute the clock jitter as the RMS of exponentially
1583 * weighted offset differences. Used by the poll adjust code.
1584 */
1585 etemp = SQUARE(G.discipline_jitter);
1586 dtemp = SQUARE(offset - G.last_update_offset);
1587 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1588 if (G.discipline_jitter < G_precision_sec)
1589 G.discipline_jitter = G_precision_sec;
1590
1591 switch (G.discipline_state) {
1592 case STATE_NSET:
1593 if (option_mask32 & OPT_q) {
1594 /* We were only asked to set time once.
1595 * The clock is precise enough, no need to step.
1596 */
1597 exit(0);
1598 }
1599#if USING_INITIAL_FREQ_ESTIMATION
1600 /* This is the first update received and the frequency
1601 * has not been initialized. The first thing to do
1602 * is directly measure the oscillator frequency.
1603 */
1604 set_new_values(STATE_FREQ, offset, recv_time);
1605#else
1606 set_new_values(STATE_SYNC, offset, recv_time);
1607#endif
1608 VERB4 bb_error_msg("transitioning to FREQ, datapoint ignored");
1609 return 0; /* "leave poll interval as is" */
1610
1611#if 0 /* this is dead code for now */
1612 case STATE_FSET:
1613 /* This is the first update and the frequency
1614 * has been initialized. Adjust the phase, but
1615 * don't adjust the frequency until the next update.
1616 */
1617 set_new_values(STATE_SYNC, offset, recv_time);
1618 /* freq_drift remains 0 */
1619 break;
1620#endif
1621
1622#if USING_INITIAL_FREQ_ESTIMATION
1623 case STATE_FREQ:
1624 /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1625 * Correct the phase and frequency and switch to SYNC state.
1626 * freq_drift was already estimated (see code above)
1627 */
1628 set_new_values(STATE_SYNC, offset, recv_time);
1629 break;
1630#endif
1631
1632 default:
1633#if !USING_KERNEL_PLL_LOOP
1634 /* Compute freq_drift due to PLL and FLL contributions.
1635 *
1636 * The FLL and PLL frequency gain constants
1637 * depend on the poll interval and Allan
1638 * intercept. The FLL is not used below one-half
1639 * the Allan intercept. Above that the loop gain
1640 * increases in steps to 1 / AVG.
1641 */
1642 if ((1 << G.poll_exp) > ALLAN / 2) {
1643 etemp = FLL - G.poll_exp;
1644 if (etemp < AVG)
1645 etemp = AVG;
1646 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1647 }
1648 /* For the PLL the integration interval
1649 * (numerator) is the minimum of the update
1650 * interval and poll interval. This allows
1651 * oversampling, but not undersampling.
1652 */
1653 etemp = MIND(since_last_update, (1 << G.poll_exp));
1654 dtemp = (4 * PLL) << G.poll_exp;
1655 freq_drift += offset * etemp / SQUARE(dtemp);
1656#endif
1657 set_new_values(STATE_SYNC, offset, recv_time);
1658 break;
1659 }
1660 if (G.stratum != p->lastpkt_stratum + 1) {
1661 G.stratum = p->lastpkt_stratum + 1;
1662 run_script("stratum", offset);
1663 }
1664 }
1665
1666 G.reftime = G.cur_time;
1667 G.ntp_status = p->lastpkt_status;
1668 G.refid = p->lastpkt_refid;
1669 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1670 dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
1671 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
1672 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1673 VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1674
1675 /* We are in STATE_SYNC now, but did not do adjtimex yet.
1676 * (Any other state does not reach this, they all return earlier)
1677 * By this time, freq_drift and offset are set
1678 * to values suitable for adjtimex.
1679 */
1680#if !USING_KERNEL_PLL_LOOP
1681 /* Calculate the new frequency drift and frequency stability (wander).
1682 * Compute the clock wander as the RMS of exponentially weighted
1683 * frequency differences. This is not used directly, but can,
1684 * along with the jitter, be a highly useful monitoring and
1685 * debugging tool.
1686 */
1687 dtemp = G.discipline_freq_drift + freq_drift;
1688 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1689 etemp = SQUARE(G.discipline_wander);
1690 dtemp = SQUARE(dtemp);
1691 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1692
1693 VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1694 G.discipline_freq_drift,
1695 (long)(G.discipline_freq_drift * 65536e6),
1696 freq_drift,
1697 G.discipline_wander);
1698#endif
1699 VERB4 {
1700 memset(&tmx, 0, sizeof(tmx));
1701 if (adjtimex(&tmx) < 0)
1702 bb_perror_msg_and_die("adjtimex");
1703 bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
1704 tmx.freq, tmx.offset, tmx.status, tmx.constant);
1705 }
1706
1707 memset(&tmx, 0, sizeof(tmx));
1708#if 0
1709//doesn't work, offset remains 0 (!) in kernel:
1710//ntpd: set adjtimex freq:1786097 tmx.offset:77487
1711//ntpd: prev adjtimex freq:1786097 tmx.offset:0
1712//ntpd: cur adjtimex freq:1786097 tmx.offset:0
1713 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1714 /* 65536 is one ppm */
1715 tmx.freq = G.discipline_freq_drift * 65536e6;
1716#endif
1717 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1718 tmx.constant = (int)G.poll_exp - 4;
1719 /* EXPERIMENTAL.
1720 * The below if statement should be unnecessary, but...
1721 * It looks like Linux kernel's PLL is far too gentle in changing
1722 * tmx.freq in response to clock offset. Offset keeps growing
1723 * and eventually we fall back to smaller poll intervals.
1724 * We can make correction more agressive (about x2) by supplying
1725 * PLL time constant which is one less than the real one.
1726 * To be on a safe side, let's do it only if offset is significantly
1727 * larger than jitter.
1728 */
1729 if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
1730 tmx.constant--;
1731 tmx.offset = (long)(offset * 1000000); /* usec */
1732 if (SLEW_THRESHOLD < STEP_THRESHOLD) {
1733 if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
1734 tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
1735 tmx.constant--;
1736 }
1737 if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
1738 tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
1739 tmx.constant--;
1740 }
1741 }
1742 if (tmx.constant < 0)
1743 tmx.constant = 0;
1744
1745 tmx.status = STA_PLL;
1746 if (G.ntp_status & LI_PLUSSEC)
1747 tmx.status |= STA_INS;
1748 if (G.ntp_status & LI_MINUSSEC)
1749 tmx.status |= STA_DEL;
1750
1751 //tmx.esterror = (uint32_t)(clock_jitter * 1e6);
1752 //tmx.maxerror = (uint32_t)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1753 rc = adjtimex(&tmx);
1754 if (rc < 0)
1755 bb_perror_msg_and_die("adjtimex");
1756 /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
1757 * Not sure why. Perhaps it is normal.
1758 */
1759 VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
1760 rc, tmx.freq, tmx.offset, tmx.status);
1761 G.kernel_freq_drift = tmx.freq / 65536;
1762 VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
1763 p->p_dotted,
1764 offset,
1765 p->lastpkt_delay,
1766 G.discipline_jitter,
1767 (double)tmx.freq / 65536,
1768 (int)tmx.constant
1769 );
1770
1771 return 1; /* "ok to increase poll interval" */
1772}
1773
1774
1775/*
1776 * We've got a new reply packet from a peer, process it
1777 * (helpers first)
1778 */
1779static unsigned
1780poll_interval(int upper_bound)
1781{
1782 unsigned interval, r, mask;
1783 interval = 1 << G.poll_exp;
1784 if (interval > upper_bound)
1785 interval = upper_bound;
1786 mask = ((interval-1) >> 4) | 1;
1787 r = rand();
1788 interval += r & mask; /* ~ random(0..1) * interval/16 */
1789 VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
1790 return interval;
1791}
1792static void
1793adjust_poll(int count)
1794{
1795 G.polladj_count += count;
1796 if (G.polladj_count > POLLADJ_LIMIT) {
1797 G.polladj_count = 0;
1798 if (G.poll_exp < MAXPOLL) {
1799 G.poll_exp++;
1800 VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1801 G.discipline_jitter, G.poll_exp);
1802 }
1803 } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
1804 G.polladj_count = 0;
1805 if (G.poll_exp > MINPOLL) {
1806 llist_t *item;
1807
1808 G.poll_exp--;
1809 /* Correct p->next_action_time in each peer
1810 * which waits for sending, so that they send earlier.
1811 * Old pp->next_action_time are on the order
1812 * of t + (1 << old_poll_exp) + small_random,
1813 * we simply need to subtract ~half of that.
1814 */
1815 for (item = G.ntp_peers; item != NULL; item = item->link) {
1816 peer_t *pp = (peer_t *) item->data;
1817 if (pp->p_fd < 0)
1818 pp->next_action_time -= (1 << G.poll_exp);
1819 }
1820 VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1821 G.discipline_jitter, G.poll_exp);
1822 }
1823 } else {
1824 VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
1825 }
1826}
1827static NOINLINE void
1828recv_and_process_peer_pkt(peer_t *p)
1829{
1830 int rc;
1831 ssize_t size;
1832 msg_t msg;
1833 double T1, T2, T3, T4;
1834 double offset;
1835 double prev_delay, delay;
1836 unsigned interval;
1837 datapoint_t *datapoint;
1838 peer_t *q;
1839
1840 offset = 0;
1841
1842 /* We can recvfrom here and check from.IP, but some multihomed
1843 * ntp servers reply from their *other IP*.
1844 * TODO: maybe we should check at least what we can: from.port == 123?
1845 */
1846 recv_again:
1847 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1848 if (size < 0) {
1849 if (errno == EINTR)
1850 /* Signal caught */
1851 goto recv_again;
1852 if (errno == EAGAIN)
1853 /* There was no packet after all
1854 * (poll() returning POLLIN for a fd
1855 * is not a ironclad guarantee that data is there)
1856 */
1857 return;
1858 /*
1859 * If you need a different handling for a specific
1860 * errno, always explain it in comment.
1861 */
1862 bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
1863 }
1864
1865 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1866 bb_error_msg("malformed packet received from %s", p->p_dotted);
1867 return;
1868 }
1869
1870 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1871 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1872 ) {
1873 /* Somebody else's packet */
1874 return;
1875 }
1876
1877 /* We do not expect any more packets from this peer for now.
1878 * Closing the socket informs kernel about it.
1879 * We open a new socket when we send a new query.
1880 */
1881 close(p->p_fd);
1882 p->p_fd = -1;
1883
1884 if ((msg.m_status & LI_ALARM) == LI_ALARM
1885 || msg.m_stratum == 0
1886 || msg.m_stratum > NTP_MAXSTRATUM
1887 ) {
1888 bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
1889 /*
1890 * Stratum 0 responses may have commands in 32-bit m_refid field:
1891 * "DENY", "RSTR" - peer does not like us at all,
1892 * "RATE" - peer is overloaded, reduce polling freq.
1893 * If poll interval is small, increase it.
1894 */
1895 if (G.poll_exp < BIGPOLL)
1896 goto increase_interval;
1897 goto pick_normal_interval;
1898 }
1899
1900// /* Verify valid root distance */
1901// if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
1902// return; /* invalid header values */
1903
1904 /*
1905 * From RFC 2030 (with a correction to the delay math):
1906 *
1907 * Timestamp Name ID When Generated
1908 * ------------------------------------------------------------
1909 * Originate Timestamp T1 time request sent by client
1910 * Receive Timestamp T2 time request received by server
1911 * Transmit Timestamp T3 time reply sent by server
1912 * Destination Timestamp T4 time reply received by client
1913 *
1914 * The roundtrip delay and local clock offset are defined as
1915 *
1916 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
1917 */
1918 T1 = p->p_xmttime;
1919 T2 = lfp_to_d(msg.m_rectime);
1920 T3 = lfp_to_d(msg.m_xmttime);
1921 T4 = G.cur_time;
1922
1923 /* The delay calculation is a special case. In cases where the
1924 * server and client clocks are running at different rates and
1925 * with very fast networks, the delay can appear negative. In
1926 * order to avoid violating the Principle of Least Astonishment,
1927 * the delay is clamped not less than the system precision.
1928 */
1929 delay = (T4 - T1) - (T3 - T2);
1930 if (delay < G_precision_sec)
1931 delay = G_precision_sec;
1932 /*
1933 * If this packet's delay is much bigger than the last one,
1934 * it's better to just ignore it than use its much less precise value.
1935 */
1936 prev_delay = p->p_raw_delay;
1937 p->p_raw_delay = delay;
1938 if (p->reachable_bits && delay > prev_delay * BAD_DELAY_GROWTH) {
1939 bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
1940 goto pick_normal_interval;
1941 }
1942
1943 p->lastpkt_delay = delay;
1944 p->lastpkt_recv_time = T4;
1945 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
1946 p->lastpkt_status = msg.m_status;
1947 p->lastpkt_stratum = msg.m_stratum;
1948 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1949 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1950 p->lastpkt_refid = msg.m_refid;
1951
1952 p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
1953 datapoint = &p->filter_datapoint[p->datapoint_idx];
1954 datapoint->d_recv_time = T4;
1955 datapoint->d_offset = offset = ((T2 - T1) + (T3 - T4)) / 2;
1956 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
1957 if (!p->reachable_bits) {
1958 /* 1st datapoint ever - replicate offset in every element */
1959 int i;
1960 for (i = 0; i < NUM_DATAPOINTS; i++) {
1961 p->filter_datapoint[i].d_offset = offset;
1962 }
1963 }
1964
1965 p->reachable_bits |= 1;
1966 if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
1967 bb_error_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
1968 p->p_dotted,
1969 offset,
1970 p->lastpkt_delay,
1971 p->lastpkt_status,
1972 p->lastpkt_stratum,
1973 p->lastpkt_refid,
1974 p->lastpkt_rootdelay,
1975 p->reachable_bits
1976 /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
1977 * m_reftime, m_orgtime, m_rectime, m_xmttime
1978 */
1979 );
1980 }
1981
1982 /* Muck with statictics and update the clock */
1983 filter_datapoints(p);
1984 q = select_and_cluster();
1985 rc = 0;
1986 if (q) {
1987 if (!(option_mask32 & OPT_w)) {
1988 rc = update_local_clock(q);
1989#if 0
1990//Disabled this because there is a case where largish offsets
1991//are unavoidable: if network round-trip delay is, say, ~0.6s,
1992//error in offset estimation would be ~delay/2 ~= 0.3s.
1993//Thus, offsets will be usually in -0.3...0.3s range.
1994//In this case, this code would keep poll interval small,
1995//but it won't be helping.
1996//BIGOFF check below deals with a case of seeing multi-second offsets.
1997
1998 /* If drift is dangerously large, immediately
1999 * drop poll interval one step down.
2000 */
2001 if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
2002 VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
2003 adjust_poll(-POLLADJ_LIMIT * 3);
2004 rc = 0;
2005 }
2006#endif
2007 }
2008 } else {
2009 /* No peer selected.
2010 * If poll interval is small, increase it.
2011 */
2012 if (G.poll_exp < BIGPOLL)
2013 goto increase_interval;
2014 }
2015
2016 if (rc != 0) {
2017 /* Adjust the poll interval by comparing the current offset
2018 * with the clock jitter. If the offset is less than
2019 * the clock jitter times a constant, then the averaging interval
2020 * is increased, otherwise it is decreased. A bit of hysteresis
2021 * helps calm the dance. Works best using burst mode.
2022 */
2023 if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
2024 /* was += G.poll_exp but it is a bit
2025 * too optimistic for my taste at high poll_exp's */
2026 increase_interval:
2027 adjust_poll(MINPOLL);
2028 } else {
2029 VERB3 if (rc > 0)
2030 bb_error_msg("want smaller interval: offset/jitter = %u",
2031 G.offset_to_jitter_ratio);
2032 adjust_poll(-G.poll_exp * 2);
2033 }
2034 }
2035
2036 /* Decide when to send new query for this peer */
2037 pick_normal_interval:
2038 interval = poll_interval(INT_MAX);
2039 if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
2040 /* If we are synced, offsets are less than SLEW_THRESHOLD,
2041 * or at the very least not much larger than it.
2042 * Now we see a largish one.
2043 * Either this peer is feeling bad, or packet got corrupted,
2044 * or _our_ clock is wrong now and _all_ peers will show similar
2045 * largish offsets too.
2046 * I observed this with laptop suspend stopping clock.
2047 * In any case, it makes sense to make next request soonish:
2048 * cases 1 and 2: get a better datapoint,
2049 * case 3: allows to resync faster.
2050 */
2051 interval = BIGOFF_INTERVAL;
2052 }
2053
2054 set_next(p, interval);
2055}
2056
2057#if ENABLE_FEATURE_NTPD_SERVER
2058static NOINLINE void
2059recv_and_process_client_pkt(void /*int fd*/)
2060{
2061 ssize_t size;
2062 //uint8_t version;
2063 len_and_sockaddr *to;
2064 struct sockaddr *from;
2065 msg_t msg;
2066 uint8_t query_status;
2067 l_fixedpt_t query_xmttime;
2068
2069 to = get_sock_lsa(G_listen_fd);
2070 from = xzalloc(to->len);
2071
2072 size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
2073 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
2074 char *addr;
2075 if (size < 0) {
2076 if (errno == EAGAIN)
2077 goto bail;
2078 bb_perror_msg_and_die("recv");
2079 }
2080 addr = xmalloc_sockaddr2dotted_noport(from);
2081 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
2082 free(addr);
2083 goto bail;
2084 }
2085
2086 /* Respond only to client and symmetric active packets */
2087 if ((msg.m_status & MODE_MASK) != MODE_CLIENT
2088 && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
2089 ) {
2090 goto bail;
2091 }
2092
2093 query_status = msg.m_status;
2094 query_xmttime = msg.m_xmttime;
2095
2096 /* Build a reply packet */
2097 memset(&msg, 0, sizeof(msg));
2098 msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
2099 msg.m_status |= (query_status & VERSION_MASK);
2100 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
2101 MODE_SERVER : MODE_SYM_PAS;
2102 msg.m_stratum = G.stratum;
2103 msg.m_ppoll = G.poll_exp;
2104 msg.m_precision_exp = G_precision_exp;
2105 /* this time was obtained between poll() and recv() */
2106 msg.m_rectime = d_to_lfp(G.cur_time);
2107 msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
2108 if (G.peer_cnt == 0) {
2109 /* we have no peers: "stratum 1 server" mode. reftime = our own time */
2110 G.reftime = G.cur_time;
2111 }
2112 msg.m_reftime = d_to_lfp(G.reftime);
2113 msg.m_orgtime = query_xmttime;
2114 msg.m_rootdelay = d_to_sfp(G.rootdelay);
2115//simple code does not do this, fix simple code!
2116 msg.m_rootdisp = d_to_sfp(G.rootdisp);
2117 //version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
2118 msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
2119
2120 /* We reply from the local address packet was sent to,
2121 * this makes to/from look swapped here: */
2122 do_sendto(G_listen_fd,
2123 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
2124 &msg, size);
2125
2126 bail:
2127 free(to);
2128 free(from);
2129}
2130#endif
2131
2132/* Upstream ntpd's options:
2133 *
2134 * -4 Force DNS resolution of host names to the IPv4 namespace.
2135 * -6 Force DNS resolution of host names to the IPv6 namespace.
2136 * -a Require cryptographic authentication for broadcast client,
2137 * multicast client and symmetric passive associations.
2138 * This is the default.
2139 * -A Do not require cryptographic authentication for broadcast client,
2140 * multicast client and symmetric passive associations.
2141 * This is almost never a good idea.
2142 * -b Enable the client to synchronize to broadcast servers.
2143 * -c conffile
2144 * Specify the name and path of the configuration file,
2145 * default /etc/ntp.conf
2146 * -d Specify debugging mode. This option may occur more than once,
2147 * with each occurrence indicating greater detail of display.
2148 * -D level
2149 * Specify debugging level directly.
2150 * -f driftfile
2151 * Specify the name and path of the frequency file.
2152 * This is the same operation as the "driftfile FILE"
2153 * configuration command.
2154 * -g Normally, ntpd exits with a message to the system log
2155 * if the offset exceeds the panic threshold, which is 1000 s
2156 * by default. This option allows the time to be set to any value
2157 * without restriction; however, this can happen only once.
2158 * If the threshold is exceeded after that, ntpd will exit
2159 * with a message to the system log. This option can be used
2160 * with the -q and -x options. See the tinker command for other options.
2161 * -i jaildir
2162 * Chroot the server to the directory jaildir. This option also implies
2163 * that the server attempts to drop root privileges at startup
2164 * (otherwise, chroot gives very little additional security).
2165 * You may need to also specify a -u option.
2166 * -k keyfile
2167 * Specify the name and path of the symmetric key file,
2168 * default /etc/ntp/keys. This is the same operation
2169 * as the "keys FILE" configuration command.
2170 * -l logfile
2171 * Specify the name and path of the log file. The default
2172 * is the system log file. This is the same operation as
2173 * the "logfile FILE" configuration command.
2174 * -L Do not listen to virtual IPs. The default is to listen.
2175 * -n Don't fork.
2176 * -N To the extent permitted by the operating system,
2177 * run the ntpd at the highest priority.
2178 * -p pidfile
2179 * Specify the name and path of the file used to record the ntpd
2180 * process ID. This is the same operation as the "pidfile FILE"
2181 * configuration command.
2182 * -P priority
2183 * To the extent permitted by the operating system,
2184 * run the ntpd at the specified priority.
2185 * -q Exit the ntpd just after the first time the clock is set.
2186 * This behavior mimics that of the ntpdate program, which is
2187 * to be retired. The -g and -x options can be used with this option.
2188 * Note: The kernel time discipline is disabled with this option.
2189 * -r broadcastdelay
2190 * Specify the default propagation delay from the broadcast/multicast
2191 * server to this client. This is necessary only if the delay
2192 * cannot be computed automatically by the protocol.
2193 * -s statsdir
2194 * Specify the directory path for files created by the statistics
2195 * facility. This is the same operation as the "statsdir DIR"
2196 * configuration command.
2197 * -t key
2198 * Add a key number to the trusted key list. This option can occur
2199 * more than once.
2200 * -u user[:group]
2201 * Specify a user, and optionally a group, to switch to.
2202 * -v variable
2203 * -V variable
2204 * Add a system variable listed by default.
2205 * -x Normally, the time is slewed if the offset is less than the step
2206 * threshold, which is 128 ms by default, and stepped if above
2207 * the threshold. This option sets the threshold to 600 s, which is
2208 * well within the accuracy window to set the clock manually.
2209 * Note: since the slew rate of typical Unix kernels is limited
2210 * to 0.5 ms/s, each second of adjustment requires an amortization
2211 * interval of 2000 s. Thus, an adjustment as much as 600 s
2212 * will take almost 14 days to complete. This option can be used
2213 * with the -g and -q options. See the tinker command for other options.
2214 * Note: The kernel time discipline is disabled with this option.
2215 */
2216
2217/* By doing init in a separate function we decrease stack usage
2218 * in main loop.
2219 */
2220static NOINLINE void ntp_init(char **argv)
2221{
2222 unsigned opts;
2223 llist_t *peers;
2224
2225 srand(getpid());
2226
2227 if (getuid())
2228 bb_error_msg_and_die("%s", bb_msg_you_must_be_root);
2229
2230 /* Set some globals */
2231 G.discipline_jitter = G_precision_sec;
2232 G.stratum = MAXSTRAT;
2233 if (BURSTPOLL != 0)
2234 G.poll_exp = BURSTPOLL; /* speeds up initial sync */
2235 G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
2236
2237 /* Parse options */
2238 peers = NULL;
2239 opt_complementary = "dd:wn" /* -d: counter; -p: list; -w implies -n */
2240 IF_FEATURE_NTPD_SERVER(":Il"); /* -I implies -l */
2241 opts = getopt32(argv,
2242 "nqNx" /* compat */
2243 "wp:*S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
2244 IF_FEATURE_NTPD_SERVER("I:") /* compat */
2245 "d" /* compat */
2246 "46aAbgL", /* compat, ignored */
2247 &peers,&G.script_name,
2248#if ENABLE_FEATURE_NTPD_SERVER
2249 &G.if_name,
2250#endif
2251 &G.verbose);
2252
2253// if (opts & OPT_x) /* disable stepping, only slew is allowed */
2254// G.time_was_stepped = 1;
2255
2256#if ENABLE_FEATURE_NTPD_SERVER
2257 G_listen_fd = -1;
2258 if (opts & OPT_l) {
2259 G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
2260 if (G.if_name) {
2261 if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
2262 xfunc_die();
2263 }
2264 socket_want_pktinfo(G_listen_fd);
2265 setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY);
2266 }
2267#endif
2268 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
2269 if (opts & OPT_N)
2270 setpriority(PRIO_PROCESS, 0, -15);
2271
2272 /* add_peers() calls can retry DNS resolution (possibly forever).
2273 * Daemonize before them, or else boot can stall forever.
2274 */
2275 if (!(opts & OPT_n)) {
2276 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
2277 logmode = LOGMODE_NONE;
2278 }
2279
2280 if (peers) {
2281 while (peers)
2282 add_peers(llist_pop(&peers));
2283 }
2284#if ENABLE_FEATURE_NTPD_CONF
2285 else {
2286 parser_t *parser;
2287 char *token[3];
2288
2289 parser = config_open("/etc/ntp.conf");
2290 while (config_read(parser, token, 3, 1, "# \t", PARSE_NORMAL)) {
2291 if (strcmp(token[0], "server") == 0 && token[1]) {
2292 add_peers(token[1]);
2293 continue;
2294 }
2295 bb_error_msg("skipping %s:%u: unimplemented command '%s'",
2296 "/etc/ntp.conf", parser->lineno, token[0]
2297 );
2298 }
2299 config_close(parser);
2300 }
2301#endif
2302 if (G.peer_cnt == 0) {
2303 if (!(opts & OPT_l))
2304 bb_show_usage();
2305 /* -l but no peers: "stratum 1 server" mode */
2306 G.stratum = 1;
2307 }
2308 /* If network is up, syncronization occurs in ~10 seconds.
2309 * We give "ntpd -q" 10 seconds to get first reply,
2310 * then another 50 seconds to finish syncing.
2311 *
2312 * I tested ntpd 4.2.6p1 and apparently it never exits
2313 * (will try forever), but it does not feel right.
2314 * The goal of -q is to act like ntpdate: set time
2315 * after a reasonably small period of polling, or fail.
2316 */
2317 if (opts & OPT_q) {
2318 option_mask32 |= OPT_qq;
2319 alarm(10);
2320 }
2321
2322 bb_signals(0
2323 | (1 << SIGTERM)
2324 | (1 << SIGINT)
2325 | (1 << SIGALRM)
2326 , record_signo
2327 );
2328 bb_signals(0
2329 | (1 << SIGPIPE)
2330 | (1 << SIGCHLD)
2331 , SIG_IGN
2332 );
2333}
2334
2335int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
2336int ntpd_main(int argc UNUSED_PARAM, char **argv)
2337{
2338#undef G
2339 struct globals G;
2340 struct pollfd *pfd;
2341 peer_t **idx2peer;
2342 unsigned cnt;
2343
2344 memset(&G, 0, sizeof(G));
2345 SET_PTR_TO_GLOBALS(&G);
2346
2347 ntp_init(argv);
2348
2349 /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
2350 cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
2351 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
2352 pfd = xzalloc(sizeof(pfd[0]) * cnt);
2353
2354 /* Countdown: we never sync before we sent INITIAL_SAMPLES+1
2355 * packets to each peer.
2356 * NB: if some peer is not responding, we may end up sending
2357 * fewer packets to it and more to other peers.
2358 * NB2: sync usually happens using INITIAL_SAMPLES packets,
2359 * since last reply does not come back instantaneously.
2360 */
2361 cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
2362
2363 write_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
2364
2365 while (!bb_got_signal) {
2366 llist_t *item;
2367 unsigned i, j;
2368 int nfds, timeout;
2369 double nextaction;
2370
2371 /* Nothing between here and poll() blocks for any significant time */
2372
2373 nextaction = G.cur_time + 3600;
2374
2375 i = 0;
2376#if ENABLE_FEATURE_NTPD_SERVER
2377 if (G_listen_fd != -1) {
2378 pfd[0].fd = G_listen_fd;
2379 pfd[0].events = POLLIN;
2380 i++;
2381 }
2382#endif
2383 /* Pass over peer list, send requests, time out on receives */
2384 for (item = G.ntp_peers; item != NULL; item = item->link) {
2385 peer_t *p = (peer_t *) item->data;
2386
2387 if (p->next_action_time <= G.cur_time) {
2388 if (p->p_fd == -1) {
2389 /* Time to send new req */
2390 if (--cnt == 0) {
2391 VERB4 bb_error_msg("disabling burst mode");
2392 G.polladj_count = 0;
2393 G.poll_exp = MINPOLL;
2394 }
2395 send_query_to_peer(p);
2396 } else {
2397 /* Timed out waiting for reply */
2398 close(p->p_fd);
2399 p->p_fd = -1;
2400 /* If poll interval is small, increase it */
2401 if (G.poll_exp < BIGPOLL)
2402 adjust_poll(MINPOLL);
2403 timeout = poll_interval(NOREPLY_INTERVAL);
2404 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
2405 p->p_dotted, p->reachable_bits, timeout);
2406
2407 /* What if don't see it because it changed its IP? */
2408 if (p->reachable_bits == 0)
2409 resolve_peer_hostname(p, /*loop_on_fail=*/ 0);
2410
2411 set_next(p, timeout);
2412 }
2413 }
2414
2415 if (p->next_action_time < nextaction)
2416 nextaction = p->next_action_time;
2417
2418 if (p->p_fd >= 0) {
2419 /* Wait for reply from this peer */
2420 pfd[i].fd = p->p_fd;
2421 pfd[i].events = POLLIN;
2422 idx2peer[i] = p;
2423 i++;
2424 }
2425 }
2426
2427 timeout = nextaction - G.cur_time;
2428 if (timeout < 0)
2429 timeout = 0;
2430 timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
2431
2432 /* Here we may block */
2433 VERB2 {
2434 if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
2435 /* We wait for at least one reply.
2436 * Poll for it, without wasting time for message.
2437 * Since replies often come under 1 second, this also
2438 * reduces clutter in logs.
2439 */
2440 nfds = poll(pfd, i, 1000);
2441 if (nfds != 0)
2442 goto did_poll;
2443 if (--timeout <= 0)
2444 goto did_poll;
2445 }
2446 bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
2447 }
2448 nfds = poll(pfd, i, timeout * 1000);
2449 did_poll:
2450 gettime1900d(); /* sets G.cur_time */
2451 if (nfds <= 0) {
2452 if (!bb_got_signal /* poll wasn't interrupted by a signal */
2453 && G.cur_time - G.last_script_run > 11*60
2454 ) {
2455 /* Useful for updating battery-backed RTC and such */
2456 run_script("periodic", G.last_update_offset);
2457 gettime1900d(); /* sets G.cur_time */
2458 }
2459 goto check_unsync;
2460 }
2461
2462 /* Process any received packets */
2463 j = 0;
2464#if ENABLE_FEATURE_NTPD_SERVER
2465 if (G.listen_fd != -1) {
2466 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
2467 nfds--;
2468 recv_and_process_client_pkt(/*G.listen_fd*/);
2469 gettime1900d(); /* sets G.cur_time */
2470 }
2471 j = 1;
2472 }
2473#endif
2474 for (; nfds != 0 && j < i; j++) {
2475 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
2476 /*
2477 * At init, alarm was set to 10 sec.
2478 * Now we did get a reply.
2479 * Increase timeout to 50 seconds to finish syncing.
2480 */
2481 if (option_mask32 & OPT_qq) {
2482 option_mask32 &= ~OPT_qq;
2483 alarm(50);
2484 }
2485 nfds--;
2486 recv_and_process_peer_pkt(idx2peer[j]);
2487 gettime1900d(); /* sets G.cur_time */
2488 }
2489 }
2490
2491 check_unsync:
2492 if (G.ntp_peers && G.stratum != MAXSTRAT) {
2493 for (item = G.ntp_peers; item != NULL; item = item->link) {
2494 peer_t *p = (peer_t *) item->data;
2495 if (p->reachable_bits)
2496 goto have_reachable_peer;
2497 }
2498 /* No peer responded for last 8 packets, panic */
2499 clamp_pollexp_and_set_MAXSTRAT();
2500 run_script("unsync", 0.0);
2501 have_reachable_peer: ;
2502 }
2503 } /* while (!bb_got_signal) */
2504
2505 remove_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
2506 kill_myself_with_sig(bb_got_signal);
2507}
2508
2509
2510
2511
2512
2513
2514/*** openntpd-4.6 uses only adjtime, not adjtimex ***/
2515
2516/*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
2517
2518#if 0
2519static double
2520direct_freq(double fp_offset)
2521{
2522#ifdef KERNEL_PLL
2523 /*
2524 * If the kernel is enabled, we need the residual offset to
2525 * calculate the frequency correction.
2526 */
2527 if (pll_control && kern_enable) {
2528 memset(&ntv, 0, sizeof(ntv));
2529 ntp_adjtime(&ntv);
2530#ifdef STA_NANO
2531 clock_offset = ntv.offset / 1e9;
2532#else /* STA_NANO */
2533 clock_offset = ntv.offset / 1e6;
2534#endif /* STA_NANO */
2535 drift_comp = FREQTOD(ntv.freq);
2536 }
2537#endif /* KERNEL_PLL */
2538 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2539 wander_resid = 0;
2540 return drift_comp;
2541}
2542
2543static void
2544set_freq(double freq) /* frequency update */
2545{
2546 char tbuf[80];
2547
2548 drift_comp = freq;
2549
2550#ifdef KERNEL_PLL
2551 /*
2552 * If the kernel is enabled, update the kernel frequency.
2553 */
2554 if (pll_control && kern_enable) {
2555 memset(&ntv, 0, sizeof(ntv));
2556 ntv.modes = MOD_FREQUENCY;
2557 ntv.freq = DTOFREQ(drift_comp);
2558 ntp_adjtime(&ntv);
2559 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2560 report_event(EVNT_FSET, NULL, tbuf);
2561 } else {
2562 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2563 report_event(EVNT_FSET, NULL, tbuf);
2564 }
2565#else /* KERNEL_PLL */
2566 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2567 report_event(EVNT_FSET, NULL, tbuf);
2568#endif /* KERNEL_PLL */
2569}
2570
2571...
2572...
2573...
2574
2575#ifdef KERNEL_PLL
2576 /*
2577 * This code segment works when clock adjustments are made using
2578 * precision time kernel support and the ntp_adjtime() system
2579 * call. This support is available in Solaris 2.6 and later,
2580 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
2581 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
2582 * DECstation 5000/240 and Alpha AXP, additional kernel
2583 * modifications provide a true microsecond clock and nanosecond
2584 * clock, respectively.
2585 *
2586 * Important note: The kernel discipline is used only if the
2587 * step threshold is less than 0.5 s, as anything higher can
2588 * lead to overflow problems. This might occur if some misguided
2589 * lad set the step threshold to something ridiculous.
2590 */
2591 if (pll_control && kern_enable) {
2592
2593#define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2594
2595 /*
2596 * We initialize the structure for the ntp_adjtime()
2597 * system call. We have to convert everything to
2598 * microseconds or nanoseconds first. Do not update the
2599 * system variables if the ext_enable flag is set. In
2600 * this case, the external clock driver will update the
2601 * variables, which will be read later by the local
2602 * clock driver. Afterwards, remember the time and
2603 * frequency offsets for jitter and stability values and
2604 * to update the frequency file.
2605 */
2606 memset(&ntv, 0, sizeof(ntv));
2607 if (ext_enable) {
2608 ntv.modes = MOD_STATUS;
2609 } else {
2610#ifdef STA_NANO
2611 ntv.modes = MOD_BITS | MOD_NANO;
2612#else /* STA_NANO */
2613 ntv.modes = MOD_BITS;
2614#endif /* STA_NANO */
2615 if (clock_offset < 0)
2616 dtemp = -.5;
2617 else
2618 dtemp = .5;
2619#ifdef STA_NANO
2620 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2621 ntv.constant = sys_poll;
2622#else /* STA_NANO */
2623 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2624 ntv.constant = sys_poll - 4;
2625#endif /* STA_NANO */
2626 ntv.esterror = (u_int32)(clock_jitter * 1e6);
2627 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2628 ntv.status = STA_PLL;
2629
2630 /*
2631 * Enable/disable the PPS if requested.
2632 */
2633 if (pps_enable) {
2634 if (!(pll_status & STA_PPSTIME))
2635 report_event(EVNT_KERN,
2636 NULL, "PPS enabled");
2637 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2638 } else {
2639 if (pll_status & STA_PPSTIME)
2640 report_event(EVNT_KERN,
2641 NULL, "PPS disabled");
2642 ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
2643 }
2644 if (sys_leap == LEAP_ADDSECOND)
2645 ntv.status |= STA_INS;
2646 else if (sys_leap == LEAP_DELSECOND)
2647 ntv.status |= STA_DEL;
2648 }
2649
2650 /*
2651 * Pass the stuff to the kernel. If it squeals, turn off
2652 * the pps. In any case, fetch the kernel offset,
2653 * frequency and jitter.
2654 */
2655 if (ntp_adjtime(&ntv) == TIME_ERROR) {
2656 if (!(ntv.status & STA_PPSSIGNAL))
2657 report_event(EVNT_KERN, NULL,
2658 "PPS no signal");
2659 }
2660 pll_status = ntv.status;
2661#ifdef STA_NANO
2662 clock_offset = ntv.offset / 1e9;
2663#else /* STA_NANO */
2664 clock_offset = ntv.offset / 1e6;
2665#endif /* STA_NANO */
2666 clock_frequency = FREQTOD(ntv.freq);
2667
2668 /*
2669 * If the kernel PPS is lit, monitor its performance.
2670 */
2671 if (ntv.status & STA_PPSTIME) {
2672#ifdef STA_NANO
2673 clock_jitter = ntv.jitter / 1e9;
2674#else /* STA_NANO */
2675 clock_jitter = ntv.jitter / 1e6;
2676#endif /* STA_NANO */
2677 }
2678
2679#if defined(STA_NANO) && NTP_API == 4
2680 /*
2681 * If the TAI changes, update the kernel TAI.
2682 */
2683 if (loop_tai != sys_tai) {
2684 loop_tai = sys_tai;
2685 ntv.modes = MOD_TAI;
2686 ntv.constant = sys_tai;
2687 ntp_adjtime(&ntv);
2688 }
2689#endif /* STA_NANO */
2690 }
2691#endif /* KERNEL_PLL */
2692#endif
2693