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