blob: aca79c95ad4d7013eb5e3f1f46fbbd12b8010ccd [file] [log] [blame]
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001/*
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 tarball for details.
7 *
8 * Parts of OpenNTPD clock syncronization code is replaced by
Denys Vlasenkobfc2a322010-01-01 18:12:06 +01009 * code which is based on ntp-4.2.6, whuch carries the following
Denys Vlasenkodd6673b2010-01-01 16:46:17 +010010 * 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#include "libbb.h"
31#include <math.h>
32#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
33#include <sys/timex.h>
34#ifndef IPTOS_LOWDELAY
35# define IPTOS_LOWDELAY 0x10
36#endif
37#ifndef IP_PKTINFO
38# error "Sorry, your kernel has to support IP_PKTINFO"
39#endif
40
41
Denys Vlasenkobfc2a322010-01-01 18:12:06 +010042/* Verbosity control (max level of -dddd options accepted).
43 * max 5 is very talkative (and bloated). 2 is non-bloated,
44 * production level setting.
45 */
Denys Vlasenko61313112010-01-01 19:56:16 +010046#define MAX_VERBOSE 2
Denys Vlasenkobfc2a322010-01-01 18:12:06 +010047
48
Denys Vlasenko65d722b2010-01-11 02:14:04 +010049/* High-level description of the algorithm:
50 *
51 * We start running with very small poll_exp, BURSTPOLL,
52 * in order to quickly accumulate INITIAL_SAMLPES datapoints
53 * for each peer. Then, time is stepped if the offset is larger
54 * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
55 * poll_exp to MINPOLL and enter frequency measurement step:
56 * we collect new datapoints but ignore them for WATCH_THRESHOLD
57 * seconds. After WATCH_THRESHOLD seconds we look at accumulated
58 * offset and estimate frequency drift.
59 *
Denys Vlasenko5b9a9102010-01-17 01:05:58 +010060 * (frequency measurement step seems to not be strictly needed,
61 * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
62 * define set to 0)
63 *
Denys Vlasenko65d722b2010-01-11 02:14:04 +010064 * After this, we enter "steady state": we collect a datapoint,
65 * we select the best peer, if this datapoint is not a new one
66 * (IOW: if this datapoint isn't for selected peer), sleep
67 * and collect another one; otherwise, use its offset to update
68 * frequency drift, if offset is somewhat large, reduce poll_exp,
69 * otherwise increase poll_exp.
70 *
71 * If offset is larger than STEP_THRESHOLD, which shouldn't normally
72 * happen, we assume that something "bad" happened (computer
73 * was hibernated, someone set totally wrong date, etc),
74 * then the time is stepped, all datapoints are discarded,
75 * and we go back to steady state.
76 */
77
Denys Vlasenkodd6673b2010-01-01 16:46:17 +010078#define RETRY_INTERVAL 5 /* on error, retry in N secs */
Denys Vlasenko0b002812010-01-03 08:59:59 +010079#define RESPONSE_INTERVAL 15 /* wait for reply up to N secs */
Denys Vlasenko65d722b2010-01-11 02:14:04 +010080#define INITIAL_SAMLPES 4 /* how many samples do we want for init */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +010081
Denys Vlasenkodd6673b2010-01-01 16:46:17 +010082/* Clock discipline parameters and constants */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +010083
84/* Step threshold (sec). std ntpd uses 0.128.
85 * Using exact power of 2 (1/8) results in smaller code */
86#define STEP_THRESHOLD 0.125
87#define WATCH_THRESHOLD 128 /* stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +010088/* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +010089//UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
Denys Vlasenko12628b72010-01-11 01:31:59 +010090
91#define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
92#define BURSTPOLL 0 /* initial poll */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +010093#define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
Denys Vlasenko12628b72010-01-11 01:31:59 +010094#define BIGPOLL 10 /* drop to lower poll at any trouble (10: 17 min) */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +010095#define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
96/* Actively lower poll when we see such big offsets.
97 * With STEP_THRESHOLD = 0.125, it means we try to sync more aggressively
98 * if offset increases over 0.03 sec */
99#define POLLDOWN_OFFSET (STEP_THRESHOLD / 4)
100#define MINDISP 0.01 /* minimum dispersion (sec) */
101#define MAXDISP 16 /* maximum dispersion (sec) */
Denys Vlasenko12628b72010-01-11 01:31:59 +0100102#define MAXSTRAT 16 /* maximum stratum (infinity metric) */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100103#define MAXDIST 1 /* distance threshold (sec) */
Denys Vlasenko12628b72010-01-11 01:31:59 +0100104#define MIN_SELECTED 1 /* minimum intersection survivors */
105#define MIN_CLUSTERED 3 /* minimum cluster survivors */
106
107#define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100108
109/* Poll-adjust threshold.
110 * When we see that offset is small enough compared to discipline jitter,
Denys Vlasenkobfc2a322010-01-01 18:12:06 +0100111 * we grow a counter: += MINPOLL. When it goes over POLLADJ_LIMIT,
Denys Vlasenko61313112010-01-01 19:56:16 +0100112 * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
113 * and when it goes below -POLLADJ_LIMIT, we poll_exp--
Denys Vlasenko65d722b2010-01-11 02:14:04 +0100114 * (bumped from 30 to 36 since otherwise I often see poll_exp going *2* steps down)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100115 */
Denys Vlasenko65d722b2010-01-11 02:14:04 +0100116#define POLLADJ_LIMIT 36
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100117/* If offset < POLLADJ_GATE * discipline_jitter, then we can increase
118 * poll interval (we think we can't improve timekeeping
119 * by staying at smaller poll).
120 */
Denys Vlasenko61313112010-01-01 19:56:16 +0100121#define POLLADJ_GATE 4
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100122/* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
Denys Vlasenko61313112010-01-01 19:56:16 +0100123#define ALLAN 512
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100124/* PLL loop gain */
Denys Vlasenko61313112010-01-01 19:56:16 +0100125#define PLL 65536
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100126/* FLL loop gain [why it depends on MAXPOLL??] */
Denys Vlasenko61313112010-01-01 19:56:16 +0100127#define FLL (MAXPOLL + 1)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100128/* Parameter averaging constant */
Denys Vlasenko61313112010-01-01 19:56:16 +0100129#define AVG 4
130
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100131
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100132enum {
133 NTP_VERSION = 4,
134 NTP_MAXSTRATUM = 15,
135
136 NTP_DIGESTSIZE = 16,
137 NTP_MSGSIZE_NOAUTH = 48,
138 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
139
140 /* Status Masks */
141 MODE_MASK = (7 << 0),
142 VERSION_MASK = (7 << 3),
143 VERSION_SHIFT = 3,
144 LI_MASK = (3 << 6),
145
146 /* Leap Second Codes (high order two bits of m_status) */
147 LI_NOWARNING = (0 << 6), /* no warning */
148 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
149 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
150 LI_ALARM = (3 << 6), /* alarm condition */
151
152 /* Mode values */
153 MODE_RES0 = 0, /* reserved */
154 MODE_SYM_ACT = 1, /* symmetric active */
155 MODE_SYM_PAS = 2, /* symmetric passive */
156 MODE_CLIENT = 3, /* client */
157 MODE_SERVER = 4, /* server */
158 MODE_BROADCAST = 5, /* broadcast */
159 MODE_RES1 = 6, /* reserved for NTP control message */
160 MODE_RES2 = 7, /* reserved for private use */
161};
162
163//TODO: better base selection
164#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
165
166#define NUM_DATAPOINTS 8
167
168typedef struct {
169 uint32_t int_partl;
170 uint32_t fractionl;
171} l_fixedpt_t;
172
173typedef struct {
174 uint16_t int_parts;
175 uint16_t fractions;
176} s_fixedpt_t;
177
178typedef struct {
179 uint8_t m_status; /* status of local clock and leap info */
180 uint8_t m_stratum;
181 uint8_t m_ppoll; /* poll value */
182 int8_t m_precision_exp;
183 s_fixedpt_t m_rootdelay;
184 s_fixedpt_t m_rootdisp;
185 uint32_t m_refid;
186 l_fixedpt_t m_reftime;
187 l_fixedpt_t m_orgtime;
188 l_fixedpt_t m_rectime;
189 l_fixedpt_t m_xmttime;
190 uint32_t m_keyid;
191 uint8_t m_digest[NTP_DIGESTSIZE];
192} msg_t;
193
194typedef struct {
195 double d_recv_time;
196 double d_offset;
197 double d_dispersion;
198} datapoint_t;
199
200typedef struct {
201 len_and_sockaddr *p_lsa;
202 char *p_dotted;
203 /* when to send new query (if p_fd == -1)
204 * or when receive times out (if p_fd >= 0): */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100205 int p_fd;
206 int datapoint_idx;
207 uint32_t lastpkt_refid;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100208 uint8_t lastpkt_status;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100209 uint8_t lastpkt_stratum;
Denys Vlasenko0b002812010-01-03 08:59:59 +0100210 uint8_t reachable_bits;
211 double next_action_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100212 double p_xmttime;
213 double lastpkt_recv_time;
214 double lastpkt_delay;
215 double lastpkt_rootdelay;
216 double lastpkt_rootdisp;
217 /* produced by filter algorithm: */
218 double filter_offset;
219 double filter_dispersion;
220 double filter_jitter;
221 datapoint_t filter_datapoint[NUM_DATAPOINTS];
222 /* last sent packet: */
223 msg_t p_xmt_msg;
224} peer_t;
225
226
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100227#define USING_KERNEL_PLL_LOOP 1
228#define USING_INITIAL_FREQ_ESTIMATION 0
229
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100230enum {
231 OPT_n = (1 << 0),
232 OPT_q = (1 << 1),
233 OPT_N = (1 << 2),
234 OPT_x = (1 << 3),
235 /* Insert new options above this line. */
236 /* Non-compat options: */
Denys Vlasenko4168fdd2010-01-04 00:19:13 +0100237 OPT_w = (1 << 4),
238 OPT_p = (1 << 5),
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100239 OPT_S = (1 << 6),
240 OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100241};
242
243struct globals {
Denys Vlasenko0b002812010-01-03 08:59:59 +0100244 double cur_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100245 /* total round trip delay to currently selected reference clock */
246 double rootdelay;
247 /* reference timestamp: time when the system clock was last set or corrected */
248 double reftime;
249 /* total dispersion to currently selected reference clock */
250 double rootdisp;
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100251
252 double last_script_run;
253 char *script_name;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100254 llist_t *ntp_peers;
255#if ENABLE_FEATURE_NTPD_SERVER
256 int listen_fd;
257#endif
258 unsigned verbose;
259 unsigned peer_cnt;
260 /* refid: 32-bit code identifying the particular server or reference clock
261 * in stratum 0 packets this is a four-character ASCII string,
262 * called the kiss code, used for debugging and monitoring
263 * in stratum 1 packets this is a four-character ASCII string
264 * assigned to the reference clock by IANA. Example: "GPS "
265 * in stratum 2+ packets, it's IPv4 address or 4 first bytes of MD5 hash of IPv6
266 */
267 uint32_t refid;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100268 uint8_t ntp_status;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100269 /* precision is defined as the larger of the resolution and time to
270 * read the clock, in log2 units. For instance, the precision of a
271 * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
272 * system clock hardware representation is to the nanosecond.
273 *
274 * Delays, jitters of various kinds are clamper down to precision.
275 *
276 * If precision_sec is too large, discipline_jitter gets clamped to it
277 * and if offset is much smaller than discipline_jitter, poll interval
278 * grows even though we really can benefit from staying at smaller one,
279 * collecting non-lagged datapoits and correcting the offset.
280 * (Lagged datapoits exist when poll_exp is large but we still have
281 * systematic offset error - the time distance between datapoints
282 * is significat and older datapoints have smaller offsets.
283 * This makes our offset estimation a bit smaller than reality)
284 * Due to this effect, setting G_precision_sec close to
285 * STEP_THRESHOLD isn't such a good idea - offsets may grow
286 * too big and we will step. I observed it with -6.
287 *
288 * OTOH, setting precision too small would result in futile attempts
289 * to syncronize to the unachievable precision.
290 *
291 * -6 is 1/64 sec, -7 is 1/128 sec and so on.
292 */
293#define G_precision_exp -8
294#define G_precision_sec (1.0 / (1 << (- G_precision_exp)))
295 uint8_t stratum;
296 /* Bool. After set to 1, never goes back to 0: */
Denys Vlasenko0b002812010-01-03 08:59:59 +0100297 smallint adjtimex_was_done;
298 smallint initial_poll_complete;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100299
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100300#define STATE_NSET 0 /* initial state, "nothing is set" */
301//#define STATE_FSET 1 /* frequency set from file */
302#define STATE_SPIK 2 /* spike detected */
303//#define STATE_FREQ 3 /* initial frequency */
304#define STATE_SYNC 4 /* clock synchronized (normal operation) */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100305 uint8_t discipline_state; // doc calls it c.state
306 uint8_t poll_exp; // s.poll
307 int polladj_count; // c.count
Denys Vlasenko61313112010-01-01 19:56:16 +0100308 long kernel_freq_drift;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100309 peer_t *last_update_peer;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100310 double last_update_offset; // c.last
Denys Vlasenko61313112010-01-01 19:56:16 +0100311 double last_update_recv_time; // s.t
312 double discipline_jitter; // c.jitter
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100313 //double cluster_offset; // s.offset
314 //double cluster_jitter; // s.jitter
Denys Vlasenko61313112010-01-01 19:56:16 +0100315#if !USING_KERNEL_PLL_LOOP
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100316 double discipline_freq_drift; // c.freq
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100317 /* Maybe conditionally calculate wander? it's used only for logging */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100318 double discipline_wander; // c.wander
Denys Vlasenko61313112010-01-01 19:56:16 +0100319#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100320};
321#define G (*ptr_to_globals)
322
323static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
324
325
Denys Vlasenkobfc2a322010-01-01 18:12:06 +0100326#define VERB1 if (MAX_VERBOSE && G.verbose)
327#define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
328#define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
329#define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
330#define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
331
332
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100333static double LOG2D(int a)
334{
335 if (a < 0)
336 return 1.0 / (1UL << -a);
337 return 1UL << a;
338}
339static ALWAYS_INLINE double SQUARE(double x)
340{
341 return x * x;
342}
343static ALWAYS_INLINE double MAXD(double a, double b)
344{
345 if (a > b)
346 return a;
347 return b;
348}
349static ALWAYS_INLINE double MIND(double a, double b)
350{
351 if (a < b)
352 return a;
353 return b;
354}
Denys Vlasenkod498ff02010-01-03 21:06:27 +0100355static NOINLINE double my_SQRT(double X)
356{
357 union {
358 float f;
359 int32_t i;
360 } v;
361 double invsqrt;
362 double Xhalf = X * 0.5;
363
364 /* Fast and good approximation to 1/sqrt(X), black magic */
365 v.f = X;
366 /*v.i = 0x5f3759df - (v.i >> 1);*/
367 v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
368 invsqrt = v.f; /* better than 0.2% accuracy */
369
370 /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
371 * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
372 * f'(x) = -2/(x*x*x)
373 * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
374 * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
375 */
376 invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
377 /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
378 /* With 4 iterations, more than half results will be exact,
379 * at 6th iterations result stabilizes with about 72% results exact.
380 * We are well satisfied with 0.05% accuracy.
381 */
382
383 return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
384}
385static ALWAYS_INLINE double SQRT(double X)
386{
387 /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
388 if (sizeof(float) != 4)
389 return sqrt(X);
390
Denys Vlasenko2d3253d2010-01-03 21:52:46 +0100391 /* This avoids needing libm, saves about 0.5k on x86-32 */
Denys Vlasenkod498ff02010-01-03 21:06:27 +0100392 return my_SQRT(X);
393}
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100394
395static double
396gettime1900d(void)
397{
398 struct timeval tv;
399 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenko0b002812010-01-03 08:59:59 +0100400 G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
401 return G.cur_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100402}
403
404static void
405d_to_tv(double d, struct timeval *tv)
406{
407 tv->tv_sec = (long)d;
408 tv->tv_usec = (d - tv->tv_sec) * 1000000;
409}
410
411static double
412lfp_to_d(l_fixedpt_t lfp)
413{
414 double ret;
415 lfp.int_partl = ntohl(lfp.int_partl);
416 lfp.fractionl = ntohl(lfp.fractionl);
417 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
418 return ret;
419}
420static double
421sfp_to_d(s_fixedpt_t sfp)
422{
423 double ret;
424 sfp.int_parts = ntohs(sfp.int_parts);
425 sfp.fractions = ntohs(sfp.fractions);
426 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
427 return ret;
428}
429#if ENABLE_FEATURE_NTPD_SERVER
430static l_fixedpt_t
431d_to_lfp(double d)
432{
433 l_fixedpt_t lfp;
434 lfp.int_partl = (uint32_t)d;
435 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
436 lfp.int_partl = htonl(lfp.int_partl);
437 lfp.fractionl = htonl(lfp.fractionl);
438 return lfp;
439}
440static s_fixedpt_t
441d_to_sfp(double d)
442{
443 s_fixedpt_t sfp;
444 sfp.int_parts = (uint16_t)d;
445 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
446 sfp.int_parts = htons(sfp.int_parts);
447 sfp.fractions = htons(sfp.fractions);
448 return sfp;
449}
450#endif
451
452static double
Denys Vlasenko0b002812010-01-03 08:59:59 +0100453dispersion(const datapoint_t *dp)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100454{
Denys Vlasenko0b002812010-01-03 08:59:59 +0100455 return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100456}
457
458static double
Denys Vlasenko0b002812010-01-03 08:59:59 +0100459root_distance(peer_t *p)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100460{
461 /* The root synchronization distance is the maximum error due to
462 * all causes of the local clock relative to the primary server.
463 * It is defined as half the total delay plus total dispersion
464 * plus peer jitter.
465 */
466 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
467 + p->lastpkt_rootdisp
468 + p->filter_dispersion
Denys Vlasenko0b002812010-01-03 08:59:59 +0100469 + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100470 + p->filter_jitter;
471}
472
473static void
474set_next(peer_t *p, unsigned t)
475{
Denys Vlasenko0b002812010-01-03 08:59:59 +0100476 p->next_action_time = G.cur_time + t;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100477}
478
479/*
480 * Peer clock filter and its helpers
481 */
482static void
Denys Vlasenko0b002812010-01-03 08:59:59 +0100483filter_datapoints(peer_t *p)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100484{
485 int i, idx;
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100486 int got_newest;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100487 double minoff, maxoff, wavg, sum, w;
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100488 double x = x; /* for compiler */
489 double oldest_off = oldest_off;
490 double oldest_age = oldest_age;
491 double newest_off = newest_off;
492 double newest_age = newest_age;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100493
494 minoff = maxoff = p->filter_datapoint[0].d_offset;
495 for (i = 1; i < NUM_DATAPOINTS; i++) {
496 if (minoff > p->filter_datapoint[i].d_offset)
497 minoff = p->filter_datapoint[i].d_offset;
498 if (maxoff < p->filter_datapoint[i].d_offset)
499 maxoff = p->filter_datapoint[i].d_offset;
500 }
501
502 idx = p->datapoint_idx; /* most recent datapoint */
503 /* Average offset:
504 * Drop two outliers and take weighted average of the rest:
505 * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
506 * we use older6/32, not older6/64 since sum of weights should be 1:
507 * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
508 */
509 wavg = 0;
510 w = 0.5;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100511 /* n-1
512 * --- dispersion(i)
513 * filter_dispersion = \ -------------
514 * / (i+1)
515 * --- 2
516 * i=0
517 */
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100518 got_newest = 0;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100519 sum = 0;
520 for (i = 0; i < NUM_DATAPOINTS; i++) {
521 VERB4 {
522 bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
523 i,
524 p->filter_datapoint[idx].d_offset,
Denys Vlasenko0b002812010-01-03 08:59:59 +0100525 p->filter_datapoint[idx].d_dispersion, dispersion(&p->filter_datapoint[idx]),
526 G.cur_time - p->filter_datapoint[idx].d_recv_time,
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100527 (minoff == p->filter_datapoint[idx].d_offset || maxoff == p->filter_datapoint[idx].d_offset)
528 ? " (outlier by offset)" : ""
529 );
530 }
531
Denys Vlasenko0b002812010-01-03 08:59:59 +0100532 sum += dispersion(&p->filter_datapoint[idx]) / (2 << i);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100533
534 if (minoff == p->filter_datapoint[idx].d_offset) {
Denys Vlasenkoe4844b82010-01-01 21:59:49 +0100535 minoff -= 1; /* so that we don't match it ever again */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100536 } else
537 if (maxoff == p->filter_datapoint[idx].d_offset) {
538 maxoff += 1;
539 } else {
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100540 oldest_off = p->filter_datapoint[idx].d_offset;
Denys Vlasenko0b002812010-01-03 08:59:59 +0100541 oldest_age = G.cur_time - p->filter_datapoint[idx].d_recv_time;
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100542 if (!got_newest) {
543 got_newest = 1;
544 newest_off = oldest_off;
545 newest_age = oldest_age;
546 }
547 x = oldest_off * w;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100548 wavg += x;
549 w /= 2;
550 }
551
552 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
553 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100554 p->filter_dispersion = sum;
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100555 wavg += x; /* add another older6/64 to form older6/32 */
556 /* Fix systematic underestimation with large poll intervals.
557 * Imagine that we still have a bit of uncorrected drift,
558 * and poll interval is big (say, 100 sec). Offsets form a progression:
559 * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
560 * The algorithm above drops 0.0 and 0.7 as outliers,
561 * and then we have this estimation, ~25% off from 0.7:
562 * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
563 */
Denys Vlasenko0b002812010-01-03 08:59:59 +0100564 x = oldest_age - newest_age;
565 if (x != 0) {
566 x = newest_age / x; /* in above example, 100 / (600 - 100) */
567 if (x < 1) { /* paranoia check */
568 x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
569 wavg += x;
570 }
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100571 }
572 p->filter_offset = wavg;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100573
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100574 /* +----- -----+ ^ 1/2
575 * | n-1 |
576 * | --- |
577 * | 1 \ 2 |
578 * filter_jitter = | --- * / (avg-offset_j) |
579 * | n --- |
580 * | j=0 |
581 * +----- -----+
582 * where n is the number of valid datapoints in the filter (n > 1);
583 * if filter_jitter < precision then filter_jitter = precision
584 */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100585 sum = 0;
586 for (i = 0; i < NUM_DATAPOINTS; i++) {
587 sum += SQUARE(wavg - p->filter_datapoint[i].d_offset);
588 }
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100589 sum = SQRT(sum / NUM_DATAPOINTS);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100590 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
591
Denys Vlasenkod9109e32010-01-02 00:36:43 +0100592 VERB3 bb_error_msg("filter offset:%f(corr:%e) disp:%f jitter:%f",
593 p->filter_offset, x,
594 p->filter_dispersion,
595 p->filter_jitter);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100596
597}
598
599static void
Denys Vlasenko0b002812010-01-03 08:59:59 +0100600reset_peer_stats(peer_t *p, double offset)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100601{
602 int i;
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100603 bool small_ofs = fabs(offset) < 16 * STEP_THRESHOLD;
604
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100605 for (i = 0; i < NUM_DATAPOINTS; i++) {
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100606 if (small_ofs) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100607 p->filter_datapoint[i].d_recv_time -= offset;
608 if (p->filter_datapoint[i].d_offset != 0) {
609 p->filter_datapoint[i].d_offset -= offset;
610 }
611 } else {
Denys Vlasenko0b002812010-01-03 08:59:59 +0100612 p->filter_datapoint[i].d_recv_time = G.cur_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100613 p->filter_datapoint[i].d_offset = 0;
614 p->filter_datapoint[i].d_dispersion = MAXDISP;
615 }
616 }
Denys Vlasenko5b9a9102010-01-17 01:05:58 +0100617 if (small_ofs) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100618 p->lastpkt_recv_time -= offset;
619 } else {
Denys Vlasenko0b002812010-01-03 08:59:59 +0100620 p->reachable_bits = 0;
621 p->lastpkt_recv_time = G.cur_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100622 }
Denys Vlasenko0b002812010-01-03 08:59:59 +0100623 filter_datapoints(p); /* recalc p->filter_xxx */
624 p->next_action_time -= offset;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100625 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
626}
627
628static void
629add_peers(char *s)
630{
631 peer_t *p;
632
633 p = xzalloc(sizeof(*p));
634 p->p_lsa = xhost2sockaddr(s, 123);
635 p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
636 p->p_fd = -1;
637 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
Denys Vlasenko0b002812010-01-03 08:59:59 +0100638 p->next_action_time = G.cur_time; /* = set_next(p, 0); */
639 reset_peer_stats(p, 16 * STEP_THRESHOLD);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100640
641 llist_add_to(&G.ntp_peers, p);
642 G.peer_cnt++;
643}
644
645static int
646do_sendto(int fd,
647 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
648 msg_t *msg, ssize_t len)
649{
650 ssize_t ret;
651
652 errno = 0;
653 if (!from) {
654 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
655 } else {
656 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
657 }
658 if (ret != len) {
659 bb_perror_msg("send failed");
660 return -1;
661 }
662 return 0;
663}
664
Denys Vlasenko0b002812010-01-03 08:59:59 +0100665static void
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100666send_query_to_peer(peer_t *p)
667{
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100668 /* Why do we need to bind()?
669 * See what happens when we don't bind:
670 *
671 * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
672 * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
673 * gettimeofday({1259071266, 327885}, NULL) = 0
674 * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
675 * ^^^ we sent it from some source port picked by kernel.
676 * time(NULL) = 1259071266
677 * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
678 * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
679 * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
680 * ^^^ this recv will receive packets to any local port!
681 *
682 * Uncomment this and use strace to see it in action:
683 */
684#define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100685
686 if (p->p_fd == -1) {
687 int fd, family;
688 len_and_sockaddr *local_lsa;
689
690 family = p->p_lsa->u.sa.sa_family;
691 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
692 /* local_lsa has "null" address and port 0 now.
693 * bind() ensures we have a *particular port* selected by kernel
694 * and remembered in p->p_fd, thus later recv(p->p_fd)
695 * receives only packets sent to this port.
696 */
697 PROBE_LOCAL_ADDR
698 xbind(fd, &local_lsa->u.sa, local_lsa->len);
699 PROBE_LOCAL_ADDR
700#if ENABLE_FEATURE_IPV6
701 if (family == AF_INET)
702#endif
703 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
704 free(local_lsa);
705 }
706
707 /*
708 * Send out a random 64-bit number as our transmit time. The NTP
709 * server will copy said number into the originate field on the
710 * response that it sends us. This is totally legal per the SNTP spec.
711 *
712 * The impact of this is two fold: we no longer send out the current
713 * system time for the world to see (which may aid an attacker), and
714 * it gives us a (not very secure) way of knowing that we're not
715 * getting spoofed by an attacker that can't capture our traffic
716 * but can spoof packets from the NTP server we're communicating with.
717 *
718 * Save the real transmit timestamp locally.
719 */
720 p->p_xmt_msg.m_xmttime.int_partl = random();
721 p->p_xmt_msg.m_xmttime.fractionl = random();
722 p->p_xmttime = gettime1900d();
723
724 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
725 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
726 ) {
727 close(p->p_fd);
728 p->p_fd = -1;
729 set_next(p, RETRY_INTERVAL);
Denys Vlasenko0b002812010-01-03 08:59:59 +0100730 return;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100731 }
732
Denys Vlasenko0b002812010-01-03 08:59:59 +0100733 p->reachable_bits <<= 1;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100734 VERB1 bb_error_msg("sent query to %s", p->p_dotted);
Denys Vlasenko0b002812010-01-03 08:59:59 +0100735 set_next(p, RESPONSE_INTERVAL);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100736}
737
738
Denys Vlasenko12628b72010-01-11 01:31:59 +0100739static void run_script(const char *action, double offset)
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100740{
741 char *argv[3];
Denys Vlasenko12628b72010-01-11 01:31:59 +0100742 char *env1, *env2, *env3, *env4;
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100743
744 if (!G.script_name)
745 return;
746
747 argv[0] = (char*) G.script_name;
748 argv[1] = (char*) action;
749 argv[2] = NULL;
750
751 VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
752
Denys Vlasenkoae473352010-01-07 11:51:13 +0100753 env1 = xasprintf("%s=%u", "stratum", G.stratum);
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100754 putenv(env1);
Denys Vlasenkoae473352010-01-07 11:51:13 +0100755 env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100756 putenv(env2);
Denys Vlasenkoae473352010-01-07 11:51:13 +0100757 env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
758 putenv(env3);
Denys Vlasenko12628b72010-01-11 01:31:59 +0100759 env4 = xasprintf("%s=%f", "offset", offset);
760 putenv(env4);
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100761 /* Other items of potential interest: selected peer,
Denys Vlasenkoae473352010-01-07 11:51:13 +0100762 * rootdelay, reftime, rootdisp, refid, ntp_status,
Denys Vlasenko12628b72010-01-11 01:31:59 +0100763 * last_update_offset, last_update_recv_time, discipline_jitter,
764 * how many peers have reachable_bits = 0?
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100765 */
766
Denys Vlasenko6959f6b2010-01-07 08:31:46 +0100767 /* Don't want to wait: it may run hwclock --systohc, and that
768 * may take some time (seconds): */
769 /*wait4pid(spawn(argv));*/
770 spawn(argv);
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100771
772 unsetenv("stratum");
773 unsetenv("freq_drift_ppm");
Denys Vlasenkoae473352010-01-07 11:51:13 +0100774 unsetenv("poll_interval");
Denys Vlasenko12628b72010-01-11 01:31:59 +0100775 unsetenv("offset");
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100776 free(env1);
777 free(env2);
Denys Vlasenkoae473352010-01-07 11:51:13 +0100778 free(env3);
Denys Vlasenko12628b72010-01-11 01:31:59 +0100779 free(env4);
Denys Vlasenkoae473352010-01-07 11:51:13 +0100780
781 G.last_script_run = G.cur_time;
Denys Vlasenkoede737b2010-01-06 12:27:47 +0100782}
783
Denys Vlasenko0b002812010-01-03 08:59:59 +0100784static NOINLINE void
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100785step_time(double offset)
786{
Denys Vlasenko0b002812010-01-03 08:59:59 +0100787 llist_t *item;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100788 double dtime;
789 struct timeval tv;
790 char buf[80];
791 time_t tval;
792
793 gettimeofday(&tv, NULL); /* never fails */
794 dtime = offset + tv.tv_sec;
795 dtime += 1.0e-6 * tv.tv_usec;
796 d_to_tv(dtime, &tv);
797
798 if (settimeofday(&tv, NULL) == -1)
799 bb_perror_msg_and_die("settimeofday");
800
801 tval = tv.tv_sec;
802 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
803
804 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
Denys Vlasenko0b002812010-01-03 08:59:59 +0100805
806 /* Correct various fields which contain time-relative values: */
807
808 /* p->lastpkt_recv_time, p->next_action_time and such: */
809 for (item = G.ntp_peers; item != NULL; item = item->link) {
810 peer_t *pp = (peer_t *) item->data;
811 reset_peer_stats(pp, offset);
812 }
813 /* Globals: */
814 G.cur_time -= offset;
815 G.last_update_recv_time -= offset;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100816}
817
818
819/*
820 * Selection and clustering, and their helpers
821 */
822typedef struct {
823 peer_t *p;
824 int type;
825 double edge;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100826 double opt_rd; /* optimization */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100827} point_t;
828static int
829compare_point_edge(const void *aa, const void *bb)
830{
831 const point_t *a = aa;
832 const point_t *b = bb;
833 if (a->edge < b->edge) {
834 return -1;
835 }
836 return (a->edge > b->edge);
837}
838typedef struct {
839 peer_t *p;
840 double metric;
841} survivor_t;
842static int
843compare_survivor_metric(const void *aa, const void *bb)
844{
845 const survivor_t *a = aa;
846 const survivor_t *b = bb;
Denys Vlasenko510f56a2010-01-03 12:00:26 +0100847 if (a->metric < b->metric) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100848 return -1;
Denys Vlasenko510f56a2010-01-03 12:00:26 +0100849 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100850 return (a->metric > b->metric);
851}
852static int
853fit(peer_t *p, double rd)
854{
Denys Vlasenko0b002812010-01-03 08:59:59 +0100855 if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
856 /* One or zero bits in reachable_bits */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100857 VERB3 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
858 return 0;
859 }
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100860#if 0 /* we filter out such packets earlier */
861 if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100862 || p->lastpkt_stratum >= MAXSTRAT
863 ) {
864 VERB3 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
865 return 0;
866 }
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +0100867#endif
Denys Vlasenko0b002812010-01-03 08:59:59 +0100868 /* rd is root_distance(p) */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100869 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
870 VERB3 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
871 return 0;
872 }
873//TODO
874// /* Do we have a loop? */
875// if (p->refid == p->dstaddr || p->refid == s.refid)
876// return 0;
877 return 1;
878}
879static peer_t*
Denys Vlasenko0b002812010-01-03 08:59:59 +0100880select_and_cluster(void)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100881{
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100882 peer_t *p;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100883 llist_t *item;
884 int i, j;
885 int size = 3 * G.peer_cnt;
886 /* for selection algorithm */
887 point_t point[size];
888 unsigned num_points, num_candidates;
889 double low, high;
890 unsigned num_falsetickers;
891 /* for cluster algorithm */
892 survivor_t survivor[size];
893 unsigned num_survivors;
894
895 /* Selection */
896
897 num_points = 0;
898 item = G.ntp_peers;
Denys Vlasenko0b002812010-01-03 08:59:59 +0100899 if (G.initial_poll_complete) while (item != NULL) {
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100900 double rd, offset;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100901
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100902 p = (peer_t *) item->data;
903 rd = root_distance(p);
904 offset = p->filter_offset;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100905 if (!fit(p, rd)) {
906 item = item->link;
907 continue;
908 }
909
910 VERB4 bb_error_msg("interval: [%f %f %f] %s",
911 offset - rd,
912 offset,
913 offset + rd,
914 p->p_dotted
915 );
916 point[num_points].p = p;
917 point[num_points].type = -1;
918 point[num_points].edge = offset - rd;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100919 point[num_points].opt_rd = rd;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100920 num_points++;
921 point[num_points].p = p;
922 point[num_points].type = 0;
923 point[num_points].edge = offset;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100924 point[num_points].opt_rd = rd;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100925 num_points++;
926 point[num_points].p = p;
927 point[num_points].type = 1;
928 point[num_points].edge = offset + rd;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +0100929 point[num_points].opt_rd = rd;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100930 num_points++;
931 item = item->link;
932 }
933 num_candidates = num_points / 3;
934 if (num_candidates == 0) {
935 VERB3 bb_error_msg("no valid datapoints, no peer selected");
Denys Vlasenko0b002812010-01-03 08:59:59 +0100936 return NULL;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +0100937 }
938//TODO: sorting does not seem to be done in reference code
939 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
940
941 /* Start with the assumption that there are no falsetickers.
942 * Attempt to find a nonempty intersection interval containing
943 * the midpoints of all truechimers.
944 * If a nonempty interval cannot be found, increase the number
945 * of assumed falsetickers by one and try again.
946 * If a nonempty interval is found and the number of falsetickers
947 * is less than the number of truechimers, a majority has been found
948 * and the midpoint of each truechimer represents
949 * the candidates available to the cluster algorithm.
950 */
951 num_falsetickers = 0;
952 while (1) {
953 int c;
954 unsigned num_midpoints = 0;
955
956 low = 1 << 9;
957 high = - (1 << 9);
958 c = 0;
959 for (i = 0; i < num_points; i++) {
960 /* We want to do:
961 * if (point[i].type == -1) c++;
962 * if (point[i].type == 1) c--;
963 * and it's simpler to do it this way:
964 */
965 c -= point[i].type;
966 if (c >= num_candidates - num_falsetickers) {
967 /* If it was c++ and it got big enough... */
968 low = point[i].edge;
969 break;
970 }
971 if (point[i].type == 0)
972 num_midpoints++;
973 }
974 c = 0;
975 for (i = num_points-1; i >= 0; i--) {
976 c += point[i].type;
977 if (c >= num_candidates - num_falsetickers) {
978 high = point[i].edge;
979 break;
980 }
981 if (point[i].type == 0)
982 num_midpoints++;
983 }
984 /* If the number of midpoints is greater than the number
985 * of allowed falsetickers, the intersection contains at
986 * least one truechimer with no midpoint - bad.
987 * Also, interval should be nonempty.
988 */
989 if (num_midpoints <= num_falsetickers && low < high)
990 break;
991 num_falsetickers++;
992 if (num_falsetickers * 2 >= num_candidates) {
993 VERB3 bb_error_msg("too many falsetickers:%d (candidates:%d), no peer selected",
994 num_falsetickers, num_candidates);
995 return NULL;
996 }
997 }
998 VERB3 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
999 low, high, num_candidates, num_falsetickers);
1000
1001 /* Clustering */
1002
1003 /* Construct a list of survivors (p, metric)
1004 * from the chime list, where metric is dominated
1005 * first by stratum and then by root distance.
1006 * All other things being equal, this is the order of preference.
1007 */
1008 num_survivors = 0;
1009 for (i = 0; i < num_points; i++) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001010 if (point[i].edge < low || point[i].edge > high)
1011 continue;
1012 p = point[i].p;
1013 survivor[num_survivors].p = p;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001014 /* x.opt_rd == root_distance(p); */
1015 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001016 VERB4 bb_error_msg("survivor[%d] metric:%f peer:%s",
1017 num_survivors, survivor[num_survivors].metric, p->p_dotted);
1018 num_survivors++;
1019 }
1020 /* There must be at least MIN_SELECTED survivors to satisfy the
1021 * correctness assertions. Ordinarily, the Byzantine criteria
1022 * require four survivors, but for the demonstration here, one
1023 * is acceptable.
1024 */
1025 if (num_survivors < MIN_SELECTED) {
1026 VERB3 bb_error_msg("num_survivors %d < %d, no peer selected",
1027 num_survivors, MIN_SELECTED);
1028 return NULL;
1029 }
1030
1031//looks like this is ONLY used by the fact that later we pick survivor[0].
1032//we can avoid sorting then, just find the minimum once!
1033 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1034
1035 /* For each association p in turn, calculate the selection
1036 * jitter p->sjitter as the square root of the sum of squares
1037 * (p->offset - q->offset) over all q associations. The idea is
1038 * to repeatedly discard the survivor with maximum selection
1039 * jitter until a termination condition is met.
1040 */
1041 while (1) {
1042 unsigned max_idx = max_idx;
1043 double max_selection_jitter = max_selection_jitter;
1044 double min_jitter = min_jitter;
1045
1046 if (num_survivors <= MIN_CLUSTERED) {
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001047 VERB3 bb_error_msg("num_survivors %d <= %d, not discarding more",
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001048 num_survivors, MIN_CLUSTERED);
1049 break;
1050 }
1051
1052 /* To make sure a few survivors are left
1053 * for the clustering algorithm to chew on,
1054 * we stop if the number of survivors
1055 * is less than or equal to MIN_CLUSTERED (3).
1056 */
1057 for (i = 0; i < num_survivors; i++) {
1058 double selection_jitter_sq;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001059
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001060 p = survivor[i].p;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001061 if (i == 0 || p->filter_jitter < min_jitter)
1062 min_jitter = p->filter_jitter;
1063
1064 selection_jitter_sq = 0;
1065 for (j = 0; j < num_survivors; j++) {
1066 peer_t *q = survivor[j].p;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001067 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1068 }
1069 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1070 max_selection_jitter = selection_jitter_sq;
1071 max_idx = i;
1072 }
1073 VERB5 bb_error_msg("survivor %d selection_jitter^2:%f",
1074 i, selection_jitter_sq);
1075 }
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001076 max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001077 VERB4 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1078 max_idx, max_selection_jitter, min_jitter);
1079
1080 /* If the maximum selection jitter is less than the
1081 * minimum peer jitter, then tossing out more survivors
1082 * will not lower the minimum peer jitter, so we might
1083 * as well stop.
1084 */
1085 if (max_selection_jitter < min_jitter) {
1086 VERB3 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1087 max_selection_jitter, min_jitter, num_survivors);
1088 break;
1089 }
1090
1091 /* Delete survivor[max_idx] from the list
1092 * and go around again.
1093 */
1094 VERB5 bb_error_msg("dropping survivor %d", max_idx);
1095 num_survivors--;
1096 while (max_idx < num_survivors) {
1097 survivor[max_idx] = survivor[max_idx + 1];
1098 max_idx++;
1099 }
1100 }
1101
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001102 if (0) {
1103 /* Combine the offsets of the clustering algorithm survivors
1104 * using a weighted average with weight determined by the root
1105 * distance. Compute the selection jitter as the weighted RMS
1106 * difference between the first survivor and the remaining
1107 * survivors. In some cases the inherent clock jitter can be
1108 * reduced by not using this algorithm, especially when frequent
1109 * clockhopping is involved. bbox: thus we don't do it.
1110 */
1111 double x, y, z, w;
1112 y = z = w = 0;
1113 for (i = 0; i < num_survivors; i++) {
1114 p = survivor[i].p;
1115 x = root_distance(p);
1116 y += 1 / x;
1117 z += p->filter_offset / x;
1118 w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1119 }
1120 //G.cluster_offset = z / y;
1121 //G.cluster_jitter = SQRT(w / y);
1122 }
1123
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001124 /* Pick the best clock. If the old system peer is on the list
1125 * and at the same stratum as the first survivor on the list,
1126 * then don't do a clock hop. Otherwise, select the first
1127 * survivor on the list as the new system peer.
1128 */
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001129 p = survivor[0].p;
1130 if (G.last_update_peer
1131 && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1132 ) {
1133 /* Starting from 1 is ok here */
1134 for (i = 1; i < num_survivors; i++) {
1135 if (G.last_update_peer == survivor[i].p) {
1136 VERB4 bb_error_msg("keeping old synced peer");
1137 p = G.last_update_peer;
1138 goto keep_old;
1139 }
1140 }
1141 }
1142 G.last_update_peer = p;
1143 keep_old:
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001144 VERB3 bb_error_msg("selected peer %s filter_offset:%f age:%f",
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001145 p->p_dotted,
1146 p->filter_offset,
1147 G.cur_time - p->lastpkt_recv_time
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001148 );
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001149 return p;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001150}
1151
1152
1153/*
1154 * Local clock discipline and its helpers
1155 */
1156static void
1157set_new_values(int disc_state, double offset, double recv_time)
1158{
1159 /* Enter new state and set state variables. Note we use the time
1160 * of the last clock filter sample, which must be earlier than
1161 * the current time.
1162 */
Denys Vlasenkod9109e32010-01-02 00:36:43 +01001163 VERB3 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001164 disc_state, offset, recv_time);
1165 G.discipline_state = disc_state;
1166 G.last_update_offset = offset;
1167 G.last_update_recv_time = recv_time;
1168}
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001169/* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
Denys Vlasenko0b002812010-01-03 08:59:59 +01001170static NOINLINE int
1171update_local_clock(peer_t *p)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001172{
1173 int rc;
1174 long old_tmx_offset;
1175 struct timex tmx;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001176 /* Note: can use G.cluster_offset instead: */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001177 double offset = p->filter_offset;
1178 double recv_time = p->lastpkt_recv_time;
1179 double abs_offset;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001180#if !USING_KERNEL_PLL_LOOP
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001181 double freq_drift;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001182#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001183 double since_last_update;
1184 double etemp, dtemp;
1185
1186 abs_offset = fabs(offset);
1187
Denys Vlasenko12628b72010-01-11 01:31:59 +01001188#if 0
1189 /* If needed, -S script can detect this by looking at $offset
1190 * env var and kill parent */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001191 /* If the offset is too large, give up and go home */
1192 if (abs_offset > PANIC_THRESHOLD) {
1193 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1194 }
Denys Vlasenko12628b72010-01-11 01:31:59 +01001195#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001196
1197 /* If this is an old update, for instance as the result
1198 * of a system peer change, avoid it. We never use
1199 * an old sample or the same sample twice.
1200 */
1201 if (recv_time <= G.last_update_recv_time) {
1202 VERB3 bb_error_msg("same or older datapoint: %f >= %f, not using it",
1203 G.last_update_recv_time, recv_time);
1204 return 0; /* "leave poll interval as is" */
1205 }
1206
1207 /* Clock state machine transition function. This is where the
1208 * action is and defines how the system reacts to large time
1209 * and frequency errors.
1210 */
1211 since_last_update = recv_time - G.reftime;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001212#if !USING_KERNEL_PLL_LOOP
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001213 freq_drift = 0;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001214#endif
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001215#if USING_INITIAL_FREQ_ESTIMATION
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001216 if (G.discipline_state == STATE_FREQ) {
1217 /* Ignore updates until the stepout threshold */
1218 if (since_last_update < WATCH_THRESHOLD) {
1219 VERB3 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1220 WATCH_THRESHOLD - since_last_update);
1221 return 0; /* "leave poll interval as is" */
1222 }
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001223# if !USING_KERNEL_PLL_LOOP
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001224 freq_drift = (offset - G.last_update_offset) / since_last_update;
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001225# endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001226 }
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001227#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001228
1229 /* There are two main regimes: when the
1230 * offset exceeds the step threshold and when it does not.
1231 */
1232 if (abs_offset > STEP_THRESHOLD) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001233 switch (G.discipline_state) {
1234 case STATE_SYNC:
1235 /* The first outlyer: ignore it, switch to SPIK state */
1236 VERB3 bb_error_msg("offset:%f - spike detected", offset);
1237 G.discipline_state = STATE_SPIK;
1238 return -1; /* "decrease poll interval" */
1239
1240 case STATE_SPIK:
1241 /* Ignore succeeding outlyers until either an inlyer
1242 * is found or the stepout threshold is exceeded.
1243 */
1244 if (since_last_update < WATCH_THRESHOLD) {
1245 VERB3 bb_error_msg("spike detected, datapoint ignored, %f sec remains",
1246 WATCH_THRESHOLD - since_last_update);
1247 return -1; /* "decrease poll interval" */
1248 }
1249 /* fall through: we need to step */
1250 } /* switch */
1251
1252 /* Step the time and clamp down the poll interval.
1253 *
1254 * In NSET state an initial frequency correction is
1255 * not available, usually because the frequency file has
1256 * not yet been written. Since the time is outside the
1257 * capture range, the clock is stepped. The frequency
1258 * will be set directly following the stepout interval.
1259 *
1260 * In FSET state the initial frequency has been set
1261 * from the frequency file. Since the time is outside
1262 * the capture range, the clock is stepped immediately,
1263 * rather than after the stepout interval. Guys get
1264 * nervous if it takes 17 minutes to set the clock for
1265 * the first time.
1266 *
1267 * In SPIK state the stepout threshold has expired and
1268 * the phase is still above the step threshold. Note
1269 * that a single spike greater than the step threshold
1270 * is always suppressed, even at the longer poll
1271 * intervals.
1272 */
1273 VERB3 bb_error_msg("stepping time by %f; poll_exp=MINPOLL", offset);
1274 step_time(offset);
1275 if (option_mask32 & OPT_q) {
1276 /* We were only asked to set time once. Done. */
1277 exit(0);
1278 }
1279
1280 G.polladj_count = 0;
1281 G.poll_exp = MINPOLL;
1282 G.stratum = MAXSTRAT;
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001283
Denys Vlasenko12628b72010-01-11 01:31:59 +01001284 run_script("step", offset);
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001285
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001286#if USING_INITIAL_FREQ_ESTIMATION
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001287 if (G.discipline_state == STATE_NSET) {
1288 set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1289 return 1; /* "ok to increase poll interval" */
1290 }
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001291#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001292 set_new_values(STATE_SYNC, /*offset:*/ 0, recv_time);
1293
1294 } else { /* abs_offset <= STEP_THRESHOLD */
1295
Denys Vlasenko0b002812010-01-03 08:59:59 +01001296 if (G.poll_exp < MINPOLL && G.initial_poll_complete) {
1297 VERB3 bb_error_msg("small offset:%f, disabling burst mode", offset);
1298 G.polladj_count = 0;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001299 G.poll_exp = MINPOLL;
1300 }
1301
1302 /* Compute the clock jitter as the RMS of exponentially
1303 * weighted offset differences. Used by the poll adjust code.
1304 */
1305 etemp = SQUARE(G.discipline_jitter);
1306 dtemp = SQUARE(MAXD(fabs(offset - G.last_update_offset), G_precision_sec));
1307 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1308 VERB3 bb_error_msg("discipline jitter=%f", G.discipline_jitter);
1309
1310 switch (G.discipline_state) {
1311 case STATE_NSET:
1312 if (option_mask32 & OPT_q) {
1313 /* We were only asked to set time once.
1314 * The clock is precise enough, no need to step.
1315 */
1316 exit(0);
1317 }
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001318#if USING_INITIAL_FREQ_ESTIMATION
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001319 /* This is the first update received and the frequency
1320 * has not been initialized. The first thing to do
1321 * is directly measure the oscillator frequency.
1322 */
1323 set_new_values(STATE_FREQ, offset, recv_time);
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001324#else
1325 set_new_values(STATE_SYNC, offset, recv_time);
1326#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001327 VERB3 bb_error_msg("transitioning to FREQ, datapoint ignored");
Denys Vlasenko0b002812010-01-03 08:59:59 +01001328 return 0; /* "leave poll interval as is" */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001329
1330#if 0 /* this is dead code for now */
1331 case STATE_FSET:
1332 /* This is the first update and the frequency
1333 * has been initialized. Adjust the phase, but
1334 * don't adjust the frequency until the next update.
1335 */
1336 set_new_values(STATE_SYNC, offset, recv_time);
1337 /* freq_drift remains 0 */
1338 break;
1339#endif
1340
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001341#if USING_INITIAL_FREQ_ESTIMATION
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001342 case STATE_FREQ:
1343 /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1344 * Correct the phase and frequency and switch to SYNC state.
1345 * freq_drift was already estimated (see code above)
1346 */
1347 set_new_values(STATE_SYNC, offset, recv_time);
1348 break;
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001349#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001350
1351 default:
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001352#if !USING_KERNEL_PLL_LOOP
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001353 /* Compute freq_drift due to PLL and FLL contributions.
1354 *
1355 * The FLL and PLL frequency gain constants
1356 * depend on the poll interval and Allan
1357 * intercept. The FLL is not used below one-half
1358 * the Allan intercept. Above that the loop gain
1359 * increases in steps to 1 / AVG.
1360 */
1361 if ((1 << G.poll_exp) > ALLAN / 2) {
1362 etemp = FLL - G.poll_exp;
1363 if (etemp < AVG)
1364 etemp = AVG;
1365 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1366 }
1367 /* For the PLL the integration interval
1368 * (numerator) is the minimum of the update
1369 * interval and poll interval. This allows
1370 * oversampling, but not undersampling.
1371 */
1372 etemp = MIND(since_last_update, (1 << G.poll_exp));
1373 dtemp = (4 * PLL) << G.poll_exp;
1374 freq_drift += offset * etemp / SQUARE(dtemp);
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001375#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001376 set_new_values(STATE_SYNC, offset, recv_time);
1377 break;
1378 }
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001379 if (G.stratum != p->lastpkt_stratum + 1) {
1380 G.stratum = p->lastpkt_stratum + 1;
Denys Vlasenko12628b72010-01-11 01:31:59 +01001381 run_script("stratum", offset);
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001382 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001383 }
1384
Denys Vlasenko0b002812010-01-03 08:59:59 +01001385 G.reftime = G.cur_time;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001386 G.ntp_status = p->lastpkt_status;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001387 G.refid = p->lastpkt_refid;
1388 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001389 dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
Denys Vlasenko0b002812010-01-03 08:59:59 +01001390 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001391 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1392 VERB3 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1393
1394 /* We are in STATE_SYNC now, but did not do adjtimex yet.
1395 * (Any other state does not reach this, they all return earlier)
1396 * By this time, freq_drift and G.last_update_offset are set
1397 * to values suitable for adjtimex.
Denys Vlasenko61313112010-01-01 19:56:16 +01001398 */
1399#if !USING_KERNEL_PLL_LOOP
1400 /* Calculate the new frequency drift and frequency stability (wander).
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001401 * Compute the clock wander as the RMS of exponentially weighted
1402 * frequency differences. This is not used directly, but can,
1403 * along with the jitter, be a highly useful monitoring and
1404 * debugging tool.
1405 */
1406 dtemp = G.discipline_freq_drift + freq_drift;
Denys Vlasenko61313112010-01-01 19:56:16 +01001407 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001408 etemp = SQUARE(G.discipline_wander);
1409 dtemp = SQUARE(dtemp);
1410 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1411
Denys Vlasenko61313112010-01-01 19:56:16 +01001412 VERB3 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1413 G.discipline_freq_drift,
1414 (long)(G.discipline_freq_drift * 65536e6),
1415 freq_drift,
1416 G.discipline_wander);
1417#endif
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001418 VERB3 {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001419 memset(&tmx, 0, sizeof(tmx));
1420 if (adjtimex(&tmx) < 0)
1421 bb_perror_msg_and_die("adjtimex");
1422 VERB3 bb_error_msg("p adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1423 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1424 }
1425
1426 old_tmx_offset = 0;
1427 if (!G.adjtimex_was_done) {
1428 G.adjtimex_was_done = 1;
1429 /* When we use adjtimex for the very first time,
1430 * we need to ADD to pre-existing tmx.offset - it may be !0
1431 */
1432 memset(&tmx, 0, sizeof(tmx));
1433 if (adjtimex(&tmx) < 0)
1434 bb_perror_msg_and_die("adjtimex");
1435 old_tmx_offset = tmx.offset;
1436 }
1437 memset(&tmx, 0, sizeof(tmx));
1438#if 0
Denys Vlasenko61313112010-01-01 19:56:16 +01001439//doesn't work, offset remains 0 (!) in kernel:
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001440//ntpd: set adjtimex freq:1786097 tmx.offset:77487
1441//ntpd: prev adjtimex freq:1786097 tmx.offset:0
1442//ntpd: cur adjtimex freq:1786097 tmx.offset:0
1443 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1444 /* 65536 is one ppm */
1445 tmx.freq = G.discipline_freq_drift * 65536e6;
1446 tmx.offset = G.last_update_offset * 1000000; /* usec */
1447#endif
1448 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1449 tmx.offset = (G.last_update_offset * 1000000) /* usec */
1450 /* + (G.last_update_offset < 0 ? -0.5 : 0.5) - too small to bother */
1451 + old_tmx_offset; /* almost always 0 */
1452 tmx.status = STA_PLL;
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001453 if (G.ntp_status & LI_PLUSSEC)
1454 tmx.status |= STA_INS;
1455 if (G.ntp_status & LI_MINUSSEC)
1456 tmx.status |= STA_DEL;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001457 tmx.constant = G.poll_exp - 4;
1458 //tmx.esterror = (u_int32)(clock_jitter * 1e6);
1459 //tmx.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001460 rc = adjtimex(&tmx);
1461 if (rc < 0)
1462 bb_perror_msg_and_die("adjtimex");
Denys Vlasenkod9109e32010-01-02 00:36:43 +01001463 /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
1464 * Not sure why. Perhaps it is normal.
1465 */
1466 VERB3 bb_error_msg("adjtimex:%d freq:%ld offset:%ld constant:%ld status:0x%x",
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001467 rc, tmx.freq, tmx.offset, tmx.constant, tmx.status);
Denys Vlasenko61313112010-01-01 19:56:16 +01001468#if 0
Denys Vlasenkod9109e32010-01-02 00:36:43 +01001469 VERB3 {
Denys Vlasenko61313112010-01-01 19:56:16 +01001470 /* always gives the same output as above msg */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001471 memset(&tmx, 0, sizeof(tmx));
1472 if (adjtimex(&tmx) < 0)
1473 bb_perror_msg_and_die("adjtimex");
1474 VERB3 bb_error_msg("c adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1475 tmx.freq, tmx.offset, tmx.constant, tmx.status);
Denys Vlasenkod9109e32010-01-02 00:36:43 +01001476 }
Denys Vlasenko61313112010-01-01 19:56:16 +01001477#endif
Denys Vlasenko12628b72010-01-11 01:31:59 +01001478 G.kernel_freq_drift = tmx.freq / 65536;
Denys Vlasenko9b20adc2010-01-17 02:51:33 +01001479 VERB2 bb_error_msg("update peer:%s, offset:%f, clock drift:%ld ppm",
1480 p->p_dotted, G.last_update_offset, G.kernel_freq_drift);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001481
1482 return 1; /* "ok to increase poll interval" */
1483}
1484
1485
1486/*
1487 * We've got a new reply packet from a peer, process it
1488 * (helpers first)
1489 */
1490static unsigned
1491retry_interval(void)
1492{
1493 /* Local problem, want to retry soon */
1494 unsigned interval, r;
1495 interval = RETRY_INTERVAL;
1496 r = random();
1497 interval += r % (unsigned)(RETRY_INTERVAL / 4);
1498 VERB3 bb_error_msg("chose retry interval:%u", interval);
1499 return interval;
1500}
1501static unsigned
Denys Vlasenko0b002812010-01-03 08:59:59 +01001502poll_interval(int exponent)
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001503{
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001504 unsigned interval, r;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001505 exponent = G.poll_exp + exponent;
1506 if (exponent < 0)
1507 exponent = 0;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001508 interval = 1 << exponent;
1509 r = random();
1510 interval += ((r & (interval-1)) >> 4) + ((r >> 8) & 1); /* + 1/16 of interval, max */
1511 VERB3 bb_error_msg("chose poll interval:%u (poll_exp:%d exp:%d)", interval, G.poll_exp, exponent);
1512 return interval;
1513}
Denys Vlasenko0b002812010-01-03 08:59:59 +01001514static NOINLINE void
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001515recv_and_process_peer_pkt(peer_t *p)
1516{
1517 int rc;
1518 ssize_t size;
1519 msg_t msg;
1520 double T1, T2, T3, T4;
1521 unsigned interval;
1522 datapoint_t *datapoint;
1523 peer_t *q;
1524
1525 /* We can recvfrom here and check from.IP, but some multihomed
1526 * ntp servers reply from their *other IP*.
1527 * TODO: maybe we should check at least what we can: from.port == 123?
1528 */
1529 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1530 if (size == -1) {
1531 bb_perror_msg("recv(%s) error", p->p_dotted);
1532 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
1533 || errno == ENETUNREACH || errno == ENETDOWN
1534 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
1535 || errno == EAGAIN
1536 ) {
1537//TODO: always do this?
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001538 interval = retry_interval();
1539 goto set_next_and_close_sock;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001540 }
1541 xfunc_die();
1542 }
1543
1544 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1545 bb_error_msg("malformed packet received from %s", p->p_dotted);
1546 goto bail;
1547 }
1548
1549 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1550 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1551 ) {
1552 goto bail;
1553 }
1554
1555 if ((msg.m_status & LI_ALARM) == LI_ALARM
1556 || msg.m_stratum == 0
1557 || msg.m_stratum > NTP_MAXSTRATUM
1558 ) {
1559// TODO: stratum 0 responses may have commands in 32-bit m_refid field:
1560// "DENY", "RSTR" - peer does not like us at all
1561// "RATE" - peer is overloaded, reduce polling freq
1562 interval = poll_interval(0);
1563 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001564 goto set_next_and_close_sock;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001565 }
1566
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001567// /* Verify valid root distance */
1568// if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
1569// return; /* invalid header values */
1570
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001571 p->lastpkt_status = msg.m_status;
1572 p->lastpkt_stratum = msg.m_stratum;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001573 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1574 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1575 p->lastpkt_refid = msg.m_refid;
1576
1577 /*
1578 * From RFC 2030 (with a correction to the delay math):
1579 *
1580 * Timestamp Name ID When Generated
1581 * ------------------------------------------------------------
1582 * Originate Timestamp T1 time request sent by client
1583 * Receive Timestamp T2 time request received by server
1584 * Transmit Timestamp T3 time reply sent by server
1585 * Destination Timestamp T4 time reply received by client
1586 *
1587 * The roundtrip delay and local clock offset are defined as
1588 *
1589 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
1590 */
1591 T1 = p->p_xmttime;
1592 T2 = lfp_to_d(msg.m_rectime);
1593 T3 = lfp_to_d(msg.m_xmttime);
Denys Vlasenko0b002812010-01-03 08:59:59 +01001594 T4 = G.cur_time;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001595
1596 p->lastpkt_recv_time = T4;
1597
1598 VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
Denys Vlasenko0b002812010-01-03 08:59:59 +01001599 p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001600 datapoint = &p->filter_datapoint[p->datapoint_idx];
1601 datapoint->d_recv_time = T4;
1602 datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
1603 /* The delay calculation is a special case. In cases where the
1604 * server and client clocks are running at different rates and
1605 * with very fast networks, the delay can appear negative. In
1606 * order to avoid violating the Principle of Least Astonishment,
1607 * the delay is clamped not less than the system precision.
1608 */
1609 p->lastpkt_delay = (T4 - T1) - (T3 - T2);
Denys Vlasenkoa9aaeda2010-01-01 22:23:27 +01001610 if (p->lastpkt_delay < G_precision_sec)
1611 p->lastpkt_delay = G_precision_sec;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001612 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001613 if (!p->reachable_bits) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001614 /* 1st datapoint ever - replicate offset in every element */
1615 int i;
1616 for (i = 1; i < NUM_DATAPOINTS; i++) {
1617 p->filter_datapoint[i].d_offset = datapoint->d_offset;
1618 }
1619 }
1620
Denys Vlasenko0b002812010-01-03 08:59:59 +01001621 p->reachable_bits |= 1;
Denys Vlasenko074e8dc2010-01-04 23:58:13 +01001622 if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001623 bb_error_msg("reply from %s: reach 0x%02x offset %f delay %f status 0x%02x strat %d refid 0x%08x rootdelay %f",
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001624 p->p_dotted,
Denys Vlasenko0b002812010-01-03 08:59:59 +01001625 p->reachable_bits,
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001626 datapoint->d_offset,
1627 p->lastpkt_delay,
1628 p->lastpkt_status,
1629 p->lastpkt_stratum,
1630 p->lastpkt_refid,
1631 p->lastpkt_rootdelay
1632 /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
1633 * m_reftime, m_orgtime, m_rectime, m_xmttime
1634 */
1635 );
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001636 }
1637
1638 /* Muck with statictics and update the clock */
Denys Vlasenko0b002812010-01-03 08:59:59 +01001639 filter_datapoints(p);
1640 q = select_and_cluster();
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001641 rc = -1;
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001642 if (q) {
1643 rc = 0;
Denys Vlasenko12628b72010-01-11 01:31:59 +01001644 if (!(option_mask32 & OPT_w)) {
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001645 rc = update_local_clock(q);
Denys Vlasenko12628b72010-01-11 01:31:59 +01001646 /* If drift is dangerously large, immediately
1647 * drop poll interval one step down.
1648 */
Denys Vlasenko5b9a9102010-01-17 01:05:58 +01001649 if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
Denys Vlasenko65d722b2010-01-11 02:14:04 +01001650 VERB3 bb_error_msg("offset:%f > POLLDOWN_OFFSET", q->filter_offset);
Denys Vlasenko12628b72010-01-11 01:31:59 +01001651 goto poll_down;
1652 }
1653 }
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001654 }
Denys Vlasenko12628b72010-01-11 01:31:59 +01001655 /* else: no peer selected, rc = -1: we want to poll more often */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001656
1657 if (rc != 0) {
1658 /* Adjust the poll interval by comparing the current offset
1659 * with the clock jitter. If the offset is less than
1660 * the clock jitter times a constant, then the averaging interval
1661 * is increased, otherwise it is decreased. A bit of hysteresis
1662 * helps calm the dance. Works best using burst mode.
1663 */
1664 VERB4 if (rc > 0) {
1665 bb_error_msg("offset:%f POLLADJ_GATE*discipline_jitter:%f poll:%s",
1666 q->filter_offset, POLLADJ_GATE * G.discipline_jitter,
1667 fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter
1668 ? "grows" : "falls"
1669 );
1670 }
1671 if (rc > 0 && fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter) {
Denys Vlasenkobfc2a322010-01-01 18:12:06 +01001672 /* was += G.poll_exp but it is a bit
1673 * too optimistic for my taste at high poll_exp's */
1674 G.polladj_count += MINPOLL;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001675 if (G.polladj_count > POLLADJ_LIMIT) {
1676 G.polladj_count = 0;
1677 if (G.poll_exp < MAXPOLL) {
1678 G.poll_exp++;
1679 VERB3 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1680 G.discipline_jitter, G.poll_exp);
1681 }
1682 } else {
1683 VERB3 bb_error_msg("polladj: incr:%d", G.polladj_count);
1684 }
1685 } else {
1686 G.polladj_count -= G.poll_exp * 2;
Denys Vlasenko12628b72010-01-11 01:31:59 +01001687 if (G.polladj_count < -POLLADJ_LIMIT || G.poll_exp >= BIGPOLL) {
1688 poll_down:
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001689 G.polladj_count = 0;
1690 if (G.poll_exp > MINPOLL) {
Denys Vlasenko2e36eb82010-01-02 01:50:16 +01001691 llist_t *item;
1692
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001693 G.poll_exp--;
Denys Vlasenko2e36eb82010-01-02 01:50:16 +01001694 /* Correct p->next_action_time in each peer
1695 * which waits for sending, so that they send earlier.
1696 * Old pp->next_action_time are on the order
1697 * of t + (1 << old_poll_exp) + small_random,
1698 * we simply need to subtract ~half of that.
1699 */
1700 for (item = G.ntp_peers; item != NULL; item = item->link) {
1701 peer_t *pp = (peer_t *) item->data;
1702 if (pp->p_fd < 0)
1703 pp->next_action_time -= (1 << G.poll_exp);
1704 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001705 VERB3 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1706 G.discipline_jitter, G.poll_exp);
1707 }
1708 } else {
1709 VERB3 bb_error_msg("polladj: decr:%d", G.polladj_count);
1710 }
1711 }
1712 }
1713
1714 /* Decide when to send new query for this peer */
1715 interval = poll_interval(0);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001716
Denys Vlasenko4168fdd2010-01-04 00:19:13 +01001717 set_next_and_close_sock:
1718 set_next(p, interval);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001719 /* We do not expect any more packets from this peer for now.
1720 * Closing the socket informs kernel about it.
1721 * We open a new socket when we send a new query.
1722 */
1723 close(p->p_fd);
1724 p->p_fd = -1;
1725 bail:
1726 return;
1727}
1728
1729#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko0b002812010-01-03 08:59:59 +01001730static NOINLINE void
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001731recv_and_process_client_pkt(void /*int fd*/)
1732{
1733 ssize_t size;
1734 uint8_t version;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001735 len_and_sockaddr *to;
1736 struct sockaddr *from;
1737 msg_t msg;
1738 uint8_t query_status;
1739 l_fixedpt_t query_xmttime;
1740
1741 to = get_sock_lsa(G.listen_fd);
1742 from = xzalloc(to->len);
1743
1744 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
1745 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1746 char *addr;
1747 if (size < 0) {
1748 if (errno == EAGAIN)
1749 goto bail;
1750 bb_perror_msg_and_die("recv");
1751 }
1752 addr = xmalloc_sockaddr2dotted_noport(from);
1753 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
1754 free(addr);
1755 goto bail;
1756 }
1757
1758 query_status = msg.m_status;
1759 query_xmttime = msg.m_xmttime;
1760
1761 /* Build a reply packet */
1762 memset(&msg, 0, sizeof(msg));
Denys Vlasenko1ee5afd2010-01-02 15:57:07 +01001763 msg.m_status = G.stratum < MAXSTRAT ? G.ntp_status : LI_ALARM;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001764 msg.m_status |= (query_status & VERSION_MASK);
1765 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
1766 MODE_SERVER : MODE_SYM_PAS;
1767 msg.m_stratum = G.stratum;
1768 msg.m_ppoll = G.poll_exp;
1769 msg.m_precision_exp = G_precision_exp;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001770 /* this time was obtained between poll() and recv() */
1771 msg.m_rectime = d_to_lfp(G.cur_time);
1772 msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001773 msg.m_reftime = d_to_lfp(G.reftime);
1774 msg.m_orgtime = query_xmttime;
1775 msg.m_rootdelay = d_to_sfp(G.rootdelay);
1776//simple code does not do this, fix simple code!
1777 msg.m_rootdisp = d_to_sfp(G.rootdisp);
1778 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
1779 msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
1780
1781 /* We reply from the local address packet was sent to,
1782 * this makes to/from look swapped here: */
1783 do_sendto(G.listen_fd,
1784 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
1785 &msg, size);
1786
1787 bail:
1788 free(to);
1789 free(from);
1790}
1791#endif
1792
1793/* Upstream ntpd's options:
1794 *
1795 * -4 Force DNS resolution of host names to the IPv4 namespace.
1796 * -6 Force DNS resolution of host names to the IPv6 namespace.
1797 * -a Require cryptographic authentication for broadcast client,
1798 * multicast client and symmetric passive associations.
1799 * This is the default.
1800 * -A Do not require cryptographic authentication for broadcast client,
1801 * multicast client and symmetric passive associations.
1802 * This is almost never a good idea.
1803 * -b Enable the client to synchronize to broadcast servers.
1804 * -c conffile
1805 * Specify the name and path of the configuration file,
1806 * default /etc/ntp.conf
1807 * -d Specify debugging mode. This option may occur more than once,
1808 * with each occurrence indicating greater detail of display.
1809 * -D level
1810 * Specify debugging level directly.
1811 * -f driftfile
1812 * Specify the name and path of the frequency file.
1813 * This is the same operation as the "driftfile FILE"
1814 * configuration command.
1815 * -g Normally, ntpd exits with a message to the system log
1816 * if the offset exceeds the panic threshold, which is 1000 s
1817 * by default. This option allows the time to be set to any value
1818 * without restriction; however, this can happen only once.
1819 * If the threshold is exceeded after that, ntpd will exit
1820 * with a message to the system log. This option can be used
1821 * with the -q and -x options. See the tinker command for other options.
1822 * -i jaildir
1823 * Chroot the server to the directory jaildir. This option also implies
1824 * that the server attempts to drop root privileges at startup
1825 * (otherwise, chroot gives very little additional security).
1826 * You may need to also specify a -u option.
1827 * -k keyfile
1828 * Specify the name and path of the symmetric key file,
1829 * default /etc/ntp/keys. This is the same operation
1830 * as the "keys FILE" configuration command.
1831 * -l logfile
1832 * Specify the name and path of the log file. The default
1833 * is the system log file. This is the same operation as
1834 * the "logfile FILE" configuration command.
1835 * -L Do not listen to virtual IPs. The default is to listen.
1836 * -n Don't fork.
1837 * -N To the extent permitted by the operating system,
1838 * run the ntpd at the highest priority.
1839 * -p pidfile
1840 * Specify the name and path of the file used to record the ntpd
1841 * process ID. This is the same operation as the "pidfile FILE"
1842 * configuration command.
1843 * -P priority
1844 * To the extent permitted by the operating system,
1845 * run the ntpd at the specified priority.
1846 * -q Exit the ntpd just after the first time the clock is set.
1847 * This behavior mimics that of the ntpdate program, which is
1848 * to be retired. The -g and -x options can be used with this option.
1849 * Note: The kernel time discipline is disabled with this option.
1850 * -r broadcastdelay
1851 * Specify the default propagation delay from the broadcast/multicast
1852 * server to this client. This is necessary only if the delay
1853 * cannot be computed automatically by the protocol.
1854 * -s statsdir
1855 * Specify the directory path for files created by the statistics
1856 * facility. This is the same operation as the "statsdir DIR"
1857 * configuration command.
1858 * -t key
1859 * Add a key number to the trusted key list. This option can occur
1860 * more than once.
1861 * -u user[:group]
1862 * Specify a user, and optionally a group, to switch to.
1863 * -v variable
1864 * -V variable
1865 * Add a system variable listed by default.
1866 * -x Normally, the time is slewed if the offset is less than the step
1867 * threshold, which is 128 ms by default, and stepped if above
1868 * the threshold. This option sets the threshold to 600 s, which is
1869 * well within the accuracy window to set the clock manually.
1870 * Note: since the slew rate of typical Unix kernels is limited
1871 * to 0.5 ms/s, each second of adjustment requires an amortization
1872 * interval of 2000 s. Thus, an adjustment as much as 600 s
1873 * will take almost 14 days to complete. This option can be used
1874 * with the -g and -q options. See the tinker command for other options.
1875 * Note: The kernel time discipline is disabled with this option.
1876 */
1877
1878/* By doing init in a separate function we decrease stack usage
1879 * in main loop.
1880 */
1881static NOINLINE void ntp_init(char **argv)
1882{
1883 unsigned opts;
1884 llist_t *peers;
1885
1886 srandom(getpid());
1887
1888 if (getuid())
1889 bb_error_msg_and_die(bb_msg_you_must_be_root);
1890
1891 /* Set some globals */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001892 G.stratum = MAXSTRAT;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001893 if (BURSTPOLL != 0)
1894 G.poll_exp = BURSTPOLL; /* speeds up initial sync */
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001895 G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001896
1897 /* Parse options */
1898 peers = NULL;
Denys Vlasenko074e8dc2010-01-04 23:58:13 +01001899 opt_complementary = "dd:p::wn"; /* d: counter; p: list; -w implies -n */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001900 opts = getopt32(argv,
1901 "nqNx" /* compat */
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001902 "wp:S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001903 "d" /* compat */
1904 "46aAbgL", /* compat, ignored */
Denys Vlasenkoede737b2010-01-06 12:27:47 +01001905 &peers, &G.script_name, &G.verbose);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001906 if (!(opts & (OPT_p|OPT_l)))
1907 bb_show_usage();
1908// if (opts & OPT_x) /* disable stepping, only slew is allowed */
1909// G.time_was_stepped = 1;
1910 while (peers)
1911 add_peers(llist_pop(&peers));
1912 if (!(opts & OPT_n)) {
1913 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
1914 logmode = LOGMODE_NONE;
1915 }
1916#if ENABLE_FEATURE_NTPD_SERVER
1917 G.listen_fd = -1;
1918 if (opts & OPT_l) {
1919 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
1920 socket_want_pktinfo(G.listen_fd);
1921 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
1922 }
1923#endif
1924 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
1925 if (opts & OPT_N)
1926 setpriority(PRIO_PROCESS, 0, -15);
1927
1928 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
Denys Vlasenko6959f6b2010-01-07 08:31:46 +01001929 /* Removed SIGHUP here: */
1930 bb_signals((1 << SIGPIPE) | (1 << SIGCHLD), SIG_IGN);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001931}
1932
1933int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
1934int ntpd_main(int argc UNUSED_PARAM, char **argv)
1935{
Denys Vlasenko0b002812010-01-03 08:59:59 +01001936#undef G
1937 struct globals G;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001938 struct pollfd *pfd;
1939 peer_t **idx2peer;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001940 unsigned cnt;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001941
Denys Vlasenko0b002812010-01-03 08:59:59 +01001942 memset(&G, 0, sizeof(G));
1943 SET_PTR_TO_GLOBALS(&G);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001944
1945 ntp_init(argv);
1946
Denys Vlasenko0b002812010-01-03 08:59:59 +01001947 /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
1948 cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
1949 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
1950 pfd = xzalloc(sizeof(pfd[0]) * cnt);
1951
Denys Vlasenko65d722b2010-01-11 02:14:04 +01001952 /* Countdown: we never sync before we sent INITIAL_SAMLPES+1
1953 * packets to each peer.
Denys Vlasenko0b002812010-01-03 08:59:59 +01001954 * NB: if some peer is not responding, we may end up sending
1955 * fewer packets to it and more to other peers.
Denys Vlasenko65d722b2010-01-11 02:14:04 +01001956 * NB2: sync usually happens using INITIAL_SAMLPES packets,
1957 * since last reply does not come back instantaneously.
Denys Vlasenko0b002812010-01-03 08:59:59 +01001958 */
Denys Vlasenko65d722b2010-01-11 02:14:04 +01001959 cnt = G.peer_cnt * (INITIAL_SAMLPES + 1);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001960
1961 while (!bb_got_signal) {
1962 llist_t *item;
1963 unsigned i, j;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001964 int nfds, timeout;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001965 double nextaction;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001966
1967 /* Nothing between here and poll() blocks for any significant time */
1968
Denys Vlasenko0b002812010-01-03 08:59:59 +01001969 nextaction = G.cur_time + 3600;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001970
1971 i = 0;
1972#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko0b002812010-01-03 08:59:59 +01001973 if (G.listen_fd != -1) {
1974 pfd[0].fd = G.listen_fd;
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001975 pfd[0].events = POLLIN;
1976 i++;
1977 }
1978#endif
1979 /* Pass over peer list, send requests, time out on receives */
Denys Vlasenko0b002812010-01-03 08:59:59 +01001980 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001981 peer_t *p = (peer_t *) item->data;
1982
Denys Vlasenko0b002812010-01-03 08:59:59 +01001983 if (p->next_action_time <= G.cur_time) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001984 if (p->p_fd == -1) {
1985 /* Time to send new req */
Denys Vlasenko0b002812010-01-03 08:59:59 +01001986 if (--cnt == 0) {
1987 G.initial_poll_complete = 1;
1988 }
1989 send_query_to_peer(p);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001990 } else {
1991 /* Timed out waiting for reply */
1992 close(p->p_fd);
1993 p->p_fd = -1;
Denys Vlasenko0b002812010-01-03 08:59:59 +01001994 timeout = poll_interval(-2); /* -2: try a bit sooner */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001995 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
Denys Vlasenko0b002812010-01-03 08:59:59 +01001996 p->p_dotted, p->reachable_bits, timeout);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01001997 set_next(p, timeout);
1998 }
1999 }
2000
2001 if (p->next_action_time < nextaction)
2002 nextaction = p->next_action_time;
2003
2004 if (p->p_fd >= 0) {
2005 /* Wait for reply from this peer */
2006 pfd[i].fd = p->p_fd;
2007 pfd[i].events = POLLIN;
2008 idx2peer[i] = p;
2009 i++;
2010 }
2011 }
2012
Denys Vlasenko0b002812010-01-03 08:59:59 +01002013 timeout = nextaction - G.cur_time;
2014 if (timeout < 0)
2015 timeout = 0;
2016 timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002017
2018 /* Here we may block */
Denys Vlasenkoae473352010-01-07 11:51:13 +01002019 VERB2 bb_error_msg("poll %us, sockets:%u, poll interval:%us", timeout, i, 1 << G.poll_exp);
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002020 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko0b002812010-01-03 08:59:59 +01002021 gettime1900d(); /* sets G.cur_time */
Denys Vlasenkoede737b2010-01-06 12:27:47 +01002022 if (nfds <= 0) {
2023 if (G.adjtimex_was_done
2024 && G.cur_time - G.last_script_run > 11*60
2025 ) {
2026 /* Useful for updating battery-backed RTC and such */
Denys Vlasenko12628b72010-01-11 01:31:59 +01002027 run_script("periodic", G.last_update_offset);
Denys Vlasenko06667f22010-01-06 13:05:08 +01002028 gettime1900d(); /* sets G.cur_time */
Denys Vlasenkoede737b2010-01-06 12:27:47 +01002029 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002030 continue;
Denys Vlasenkoede737b2010-01-06 12:27:47 +01002031 }
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002032
2033 /* Process any received packets */
2034 j = 0;
2035#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko0b002812010-01-03 08:59:59 +01002036 if (G.listen_fd != -1) {
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002037 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
2038 nfds--;
Denys Vlasenko0b002812010-01-03 08:59:59 +01002039 recv_and_process_client_pkt(/*G.listen_fd*/);
2040 gettime1900d(); /* sets G.cur_time */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002041 }
2042 j = 1;
2043 }
2044#endif
2045 for (; nfds != 0 && j < i; j++) {
2046 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
2047 nfds--;
2048 recv_and_process_peer_pkt(idx2peer[j]);
Denys Vlasenko0b002812010-01-03 08:59:59 +01002049 gettime1900d(); /* sets G.cur_time */
Denys Vlasenkodd6673b2010-01-01 16:46:17 +01002050 }
2051 }
2052 } /* while (!bb_got_signal) */
2053
2054 kill_myself_with_sig(bb_got_signal);
2055}
2056
2057
2058
2059
2060
2061
2062/*** openntpd-4.6 uses only adjtime, not adjtimex ***/
2063
2064/*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
2065
2066#if 0
2067static double
2068direct_freq(double fp_offset)
2069{
2070
2071#ifdef KERNEL_PLL
2072 /*
2073 * If the kernel is enabled, we need the residual offset to
2074 * calculate the frequency correction.
2075 */
2076 if (pll_control && kern_enable) {
2077 memset(&ntv, 0, sizeof(ntv));
2078 ntp_adjtime(&ntv);
2079#ifdef STA_NANO
2080 clock_offset = ntv.offset / 1e9;
2081#else /* STA_NANO */
2082 clock_offset = ntv.offset / 1e6;
2083#endif /* STA_NANO */
2084 drift_comp = FREQTOD(ntv.freq);
2085 }
2086#endif /* KERNEL_PLL */
2087 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2088 wander_resid = 0;
2089 return drift_comp;
2090}
2091
2092static void
2093set_freq(double freq) /* frequency update */
2094{
2095 char tbuf[80];
2096
2097 drift_comp = freq;
2098
2099#ifdef KERNEL_PLL
2100 /*
2101 * If the kernel is enabled, update the kernel frequency.
2102 */
2103 if (pll_control && kern_enable) {
2104 memset(&ntv, 0, sizeof(ntv));
2105 ntv.modes = MOD_FREQUENCY;
2106 ntv.freq = DTOFREQ(drift_comp);
2107 ntp_adjtime(&ntv);
2108 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2109 report_event(EVNT_FSET, NULL, tbuf);
2110 } else {
2111 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2112 report_event(EVNT_FSET, NULL, tbuf);
2113 }
2114#else /* KERNEL_PLL */
2115 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2116 report_event(EVNT_FSET, NULL, tbuf);
2117#endif /* KERNEL_PLL */
2118}
2119
2120...
2121...
2122...
2123
2124#ifdef KERNEL_PLL
2125 /*
2126 * This code segment works when clock adjustments are made using
2127 * precision time kernel support and the ntp_adjtime() system
2128 * call. This support is available in Solaris 2.6 and later,
2129 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
2130 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
2131 * DECstation 5000/240 and Alpha AXP, additional kernel
2132 * modifications provide a true microsecond clock and nanosecond
2133 * clock, respectively.
2134 *
2135 * Important note: The kernel discipline is used only if the
2136 * step threshold is less than 0.5 s, as anything higher can
2137 * lead to overflow problems. This might occur if some misguided
2138 * lad set the step threshold to something ridiculous.
2139 */
2140 if (pll_control && kern_enable) {
2141
2142#define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2143
2144 /*
2145 * We initialize the structure for the ntp_adjtime()
2146 * system call. We have to convert everything to
2147 * microseconds or nanoseconds first. Do not update the
2148 * system variables if the ext_enable flag is set. In
2149 * this case, the external clock driver will update the
2150 * variables, which will be read later by the local
2151 * clock driver. Afterwards, remember the time and
2152 * frequency offsets for jitter and stability values and
2153 * to update the frequency file.
2154 */
2155 memset(&ntv, 0, sizeof(ntv));
2156 if (ext_enable) {
2157 ntv.modes = MOD_STATUS;
2158 } else {
2159#ifdef STA_NANO
2160 ntv.modes = MOD_BITS | MOD_NANO;
2161#else /* STA_NANO */
2162 ntv.modes = MOD_BITS;
2163#endif /* STA_NANO */
2164 if (clock_offset < 0)
2165 dtemp = -.5;
2166 else
2167 dtemp = .5;
2168#ifdef STA_NANO
2169 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2170 ntv.constant = sys_poll;
2171#else /* STA_NANO */
2172 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2173 ntv.constant = sys_poll - 4;
2174#endif /* STA_NANO */
2175 ntv.esterror = (u_int32)(clock_jitter * 1e6);
2176 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2177 ntv.status = STA_PLL;
2178
2179 /*
2180 * Enable/disable the PPS if requested.
2181 */
2182 if (pps_enable) {
2183 if (!(pll_status & STA_PPSTIME))
2184 report_event(EVNT_KERN,
2185 NULL, "PPS enabled");
2186 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2187 } else {
2188 if (pll_status & STA_PPSTIME)
2189 report_event(EVNT_KERN,
2190 NULL, "PPS disabled");
2191 ntv.status &= ~(STA_PPSTIME |
2192 STA_PPSFREQ);
2193 }
2194 if (sys_leap == LEAP_ADDSECOND)
2195 ntv.status |= STA_INS;
2196 else if (sys_leap == LEAP_DELSECOND)
2197 ntv.status |= STA_DEL;
2198 }
2199
2200 /*
2201 * Pass the stuff to the kernel. If it squeals, turn off
2202 * the pps. In any case, fetch the kernel offset,
2203 * frequency and jitter.
2204 */
2205 if (ntp_adjtime(&ntv) == TIME_ERROR) {
2206 if (!(ntv.status & STA_PPSSIGNAL))
2207 report_event(EVNT_KERN, NULL,
2208 "PPS no signal");
2209 }
2210 pll_status = ntv.status;
2211#ifdef STA_NANO
2212 clock_offset = ntv.offset / 1e9;
2213#else /* STA_NANO */
2214 clock_offset = ntv.offset / 1e6;
2215#endif /* STA_NANO */
2216 clock_frequency = FREQTOD(ntv.freq);
2217
2218 /*
2219 * If the kernel PPS is lit, monitor its performance.
2220 */
2221 if (ntv.status & STA_PPSTIME) {
2222#ifdef STA_NANO
2223 clock_jitter = ntv.jitter / 1e9;
2224#else /* STA_NANO */
2225 clock_jitter = ntv.jitter / 1e6;
2226#endif /* STA_NANO */
2227 }
2228
2229#if defined(STA_NANO) && NTP_API == 4
2230 /*
2231 * If the TAI changes, update the kernel TAI.
2232 */
2233 if (loop_tai != sys_tai) {
2234 loop_tai = sys_tai;
2235 ntv.modes = MOD_TAI;
2236 ntv.constant = sys_tai;
2237 ntp_adjtime(&ntv);
2238 }
2239#endif /* STA_NANO */
2240 }
2241#endif /* KERNEL_PLL */
2242#endif