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