1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108#include "libbb.h"
109#include <math.h>
110#include <netinet/ip.h>
111#include <sys/timex.h>
112#ifndef IPTOS_DSCP_AF21
113# define IPTOS_DSCP_AF21 0x48
114#endif
115
116#if defined(__FreeBSD__)
117
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
125
126
127
128#define MAX_VERBOSE 3
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163#define INITIAL_SAMPLES 3
164#define MIN_FREQHOLD 10
165#define BAD_DELAY_GROWTH 4
166
167#define RETRY_INTERVAL 32
168#define NOREPLY_INTERVAL 512
169#define RESPONSE_INTERVAL 16
170#define HOSTNAME_INTERVAL 4
171#define DNS_ERRORS_CAP 0x3f
172
173
174
175#define STEP_THRESHOLD 1
176
177
178
179#define SLEW_THRESHOLD 0.5
180
181
182
183
184
185
186
187
188
189#define BIGOFF STEP_THRESHOLD
190#define BIGOFF_INTERVAL (1 << 7)
191
192#define FREQ_TOLERANCE 0.000015
193#define BURSTPOLL 0
194#define MINPOLL 5
195
196
197
198#define BIGPOLL 9
199#define MAXPOLL 12
200
201
202
203
204
205#define MINDISP 0.01
206#define MAXDISP 16
207#define MAXSTRAT 16
208#define MAXDIST 1
209#define MIN_SELECTED 1
210#define MIN_CLUSTERED 3
211
212
213#define USING_KERNEL_PLL_LOOP 1
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230#define POLLADJ_LIMIT 40
231
232
233
234
235#define POLLADJ_GATE 4
236#define TIMECONST_HACK_GATE 2
237
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
254 MODE_MASK = (7 << 0),
255 VERSION_MASK = (7 << 3),
256 VERSION_SHIFT = 3,
257 LI_MASK = (3 << 6),
258
259
260 LI_NOWARNING = (0 << 6),
261 LI_PLUSSEC = (1 << 6),
262 LI_MINUSSEC = (2 << 6),
263 LI_ALARM = (3 << 6),
264
265
266 MODE_RES0 = 0,
267 MODE_SYM_ACT = 1,
268 MODE_SYM_PAS = 2,
269 MODE_CLIENT = 3,
270 MODE_SERVER = 4,
271 MODE_BROADCAST = 5,
272 MODE_RES1 = 6,
273 MODE_RES2 = 7,
274};
275
276
277#define OFFSET_1900_1970 2208988800UL
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;
293 uint8_t m_stratum;
294 uint8_t m_ppoll;
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;
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
344
345 double next_action_time;
346 double p_xmttime;
347 double p_raw_delay;
348
349
350 double lastpkt_recv_time;
351 double lastpkt_delay;
352 double lastpkt_rootdelay;
353 double lastpkt_rootdisp;
354
355 double filter_offset;
356 double filter_dispersion;
357 double filter_jitter;
358 datapoint_t filter_datapoint[NUM_DATAPOINTS];
359
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
371
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
378 OPT_qq = (1 << 31),
379};
380
381struct globals {
382 double cur_time;
383
384 double rootdelay;
385
386 double reftime;
387
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
403
404
405
406
407
408
409
410#if ENABLE_FEATURE_NTPD_SERVER
411 uint32_t refid;
412#endif
413 uint8_t ntp_status;
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440#define G_precision_exp -9
441
442
443
444
445
446
447#define G_precision_sec 0.002
448 uint8_t stratum;
449
450
451 uint8_t poll_exp;
452 int polladj_count;
453 int FREQHOLD_cnt;
454 long kernel_freq_drift;
455 peer_t *last_update_peer;
456 double last_update_offset;
457 double last_update_recv_time;
458 double discipline_jitter;
459
460
461
462 unsigned offset_to_jitter_ratio;
463
464
465#if !USING_KERNEL_PLL_LOOP
466 double discipline_freq_drift;
467
468 double discipline_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
515 v.f = X;
516
517 v.i = 0x5f375a86 - (v.i >> 1);
518 invsqrt = v.f;
519
520
521
522
523
524
525
526 invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt);
527
528
529
530
531
532
533 return X * invsqrt;
534}
535static ALWAYS_INLINE double SQRT(double X)
536{
537
538 if (sizeof(float) != 4)
539 return sqrt(X);
540
541
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 void
555d_to_tv(struct timeval *tv, double d)
556{
557 tv->tv_sec = (long)d;
558 tv->tv_usec = (d - tv->tv_sec) * 1000000;
559}
560
561static NOINLINE double
562lfp_to_d(l_fixedpt_t lfp)
563{
564 double ret;
565 lfp.int_partl = ntohl(lfp.int_partl);
566 lfp.fractionl = ntohl(lfp.fractionl);
567 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
568 return ret;
569}
570static NOINLINE double
571sfp_to_d(s_fixedpt_t sfp)
572{
573 double ret;
574 sfp.int_parts = ntohs(sfp.int_parts);
575 sfp.fractions = ntohs(sfp.fractions);
576 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
577 return ret;
578}
579#if ENABLE_FEATURE_NTPD_SERVER
580static NOINLINE void
581d_to_lfp(l_fixedpt_t *lfp, double d)
582{
583 uint32_t intl;
584 uint32_t frac;
585 intl = (uint32_t)d;
586 frac = (uint32_t)((d - intl) * UINT_MAX);
587 lfp->int_partl = htonl(intl);
588 lfp->fractionl = htonl(frac);
589}
590static NOINLINE void
591d_to_sfp(s_fixedpt_t *sfp, double d)
592{
593 uint16_t ints;
594 uint16_t frac;
595 ints = (uint16_t)d;
596 frac = (uint16_t)((d - ints) * USHRT_MAX);
597 sfp->int_parts = htons(ints);
598 sfp->fractions = htons(frac);
599}
600#endif
601
602static double
603dispersion(const datapoint_t *dp)
604{
605 return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
606}
607
608static double
609root_distance(peer_t *p)
610{
611
612
613
614
615
616 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
617 + p->lastpkt_rootdisp
618 + p->filter_dispersion
619 + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
620 + p->filter_jitter;
621}
622
623static void
624set_next(peer_t *p, unsigned t)
625{
626 p->next_action_time = G.cur_time + t;
627}
628
629
630
631
632static void
633filter_datapoints(peer_t *p)
634{
635 int i, idx;
636 double sum, wavg;
637 datapoint_t *fdp;
638
639
640
641
642
643
644 fdp = p->filter_datapoint;
645 idx = p->datapoint_idx;
646
647
648 p->filter_offset = fdp[idx].d_offset;
649
650
651
652
653
654
655
656
657 wavg = 0;
658 sum = 0;
659 for (i = 0; i < NUM_DATAPOINTS; i++) {
660 sum += dispersion(&fdp[idx]) / (2 << i);
661 wavg += fdp[idx].d_offset;
662 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
663 }
664 wavg /= NUM_DATAPOINTS;
665 p->filter_dispersion = sum;
666
667
668
669
670
671
672
673
674
675
676
677
678 sum = 0;
679 for (i = 0; i < NUM_DATAPOINTS; i++) {
680 sum += SQUARE(wavg - fdp[i].d_offset);
681 }
682 sum = SQRT(sum / NUM_DATAPOINTS);
683 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
684
685 VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
686 p->filter_offset,
687 p->filter_dispersion,
688 p->filter_jitter);
689}
690
691static void
692reset_peer_stats(peer_t *p, double offset)
693{
694 int i;
695 bool small_ofs = fabs(offset) < STEP_THRESHOLD;
696
697
698
699
700
701
702
703
704
705
706
707
708
709 for (i = 0; i < NUM_DATAPOINTS; i++) {
710 if (small_ofs) {
711 p->filter_datapoint[i].d_recv_time += offset;
712 if (p->filter_datapoint[i].d_offset != 0) {
713 p->filter_datapoint[i].d_offset -= offset;
714
715
716
717
718 }
719 } else {
720 p->filter_datapoint[i].d_recv_time = G.cur_time;
721 p->filter_datapoint[i].d_offset = 0;
722
723 }
724 }
725 if (small_ofs) {
726 p->lastpkt_recv_time += offset;
727 } else {
728
729 p->lastpkt_recv_time = G.cur_time;
730 }
731 filter_datapoints(p);
732 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
733}
734
735#if ENABLE_FEATURE_NTPD_SERVER
736static uint32_t calculate_refid(len_and_sockaddr *lsa)
737{
738# if ENABLE_FEATURE_IPV6
739 if (lsa->u.sa.sa_family == AF_INET6) {
740 md5_ctx_t md5;
741 uint32_t res[MD5_OUTSIZE / 4];
742
743 md5_begin(&md5);
744 md5_hash(&md5, &lsa->u.sin6.sin6_addr, sizeof(lsa->u.sin6.sin6_addr));
745 md5_end(&md5, res);
746 return res[0];
747 }
748# endif
749 return lsa->u.sin.sin_addr.s_addr;
750}
751#endif
752
753static len_and_sockaddr*
754resolve_peer_hostname(peer_t *p)
755{
756 len_and_sockaddr *lsa = host2sockaddr(p->p_hostname, 123);
757 if (lsa) {
758 free(p->p_lsa);
759 free(p->p_dotted);
760 p->p_lsa = lsa;
761 p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
762 VERB1 if (strcmp(p->p_hostname, p->p_dotted) != 0)
763 bb_error_msg("'%s' is %s", p->p_hostname, p->p_dotted);
764#if ENABLE_FEATURE_NTPD_SERVER
765 p->p_refid = calculate_refid(p->p_lsa);
766#endif
767 p->dns_errors = 0;
768 return lsa;
769 }
770 p->dns_errors = ((p->dns_errors << 1) | 1) & DNS_ERRORS_CAP;
771 return lsa;
772}
773
774#if !ENABLE_FEATURE_NTP_AUTH
775#define add_peers(s, key_entry) \
776 add_peers(s)
777#endif
778static void
779add_peers(const char *s, key_entry_t *key_entry)
780{
781 llist_t *item;
782 peer_t *p;
783
784 p = xzalloc(sizeof(*p) + strlen(s));
785 strcpy(p->p_hostname, s);
786 p->p_fd = -1;
787 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
788 p->next_action_time = G.cur_time;
789 reset_peer_stats(p, STEP_THRESHOLD);
790
791
792
793
794
795 if (resolve_peer_hostname(p)) {
796 for (item = G.ntp_peers; item != NULL; item = item->link) {
797 peer_t *pp = (peer_t *) item->data;
798 if (pp->p_dotted && strcmp(p->p_dotted, pp->p_dotted) == 0) {
799 bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
800 free(p->p_lsa);
801 free(p->p_dotted);
802 free(p);
803 return;
804 }
805 }
806 }
807
808 IF_FEATURE_NTP_AUTH(p->key_entry = key_entry;)
809 llist_add_to(&G.ntp_peers, p);
810 G.peer_cnt++;
811}
812
813static int
814do_sendto(int fd,
815 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
816 msg_t *msg, ssize_t len)
817{
818 ssize_t ret;
819
820 errno = 0;
821 if (!from) {
822 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
823 } else {
824 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
825 }
826 if (ret != len) {
827 bb_simple_perror_msg("send failed");
828 return -1;
829 }
830 return 0;
831}
832
833#if ENABLE_FEATURE_NTP_AUTH
834static void
835hash(key_entry_t *key_entry, const msg_t *msg, uint8_t *output)
836{
837 union {
838 md5_ctx_t m;
839 sha1_ctx_t s;
840 } ctx;
841 unsigned hash_size = sizeof(*msg) - sizeof(msg->m_keyid) - sizeof(msg->m_digest);
842
843 switch (key_entry->type) {
844 case HASH_MD5:
845 md5_begin(&ctx.m);
846 md5_hash(&ctx.m, key_entry->key, key_entry->key_length);
847 md5_hash(&ctx.m, msg, hash_size);
848 md5_end(&ctx.m, output);
849 break;
850 default:
851 sha1_begin(&ctx.s);
852 sha1_hash(&ctx.s, key_entry->key, key_entry->key_length);
853 sha1_hash(&ctx.s, msg, hash_size);
854 sha1_end(&ctx.s, output);
855 break;
856 }
857}
858
859static void
860hash_peer(peer_t *p)
861{
862 p->p_xmt_msg.m_keyid = htonl(p->key_entry->id);
863 hash(p->key_entry, &p->p_xmt_msg, p->p_xmt_msg.m_digest);
864}
865
866static int
867hashes_differ(peer_t *p, const msg_t *msg)
868{
869 uint8_t digest[NTP_SHA1_DIGESTSIZE];
870 hash(p->key_entry, msg, digest);
871 return memcmp(digest, msg->m_digest, p->key_entry->msg_size - NTP_MSGSIZE_NOAUTH - KEYID_SIZE);
872}
873#endif
874
875static void
876send_query_to_peer(peer_t *p)
877{
878 if (!p->p_lsa)
879 return;
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897#define PROBE_LOCAL_ADDR
898
899 if (p->p_fd == -1) {
900 int fd, family;
901 len_and_sockaddr *local_lsa;
902
903 family = p->p_lsa->u.sa.sa_family;
904 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
905
906
907
908
909
910 PROBE_LOCAL_ADDR
911 xbind(fd, &local_lsa->u.sa, local_lsa->len);
912 PROBE_LOCAL_ADDR
913#if ENABLE_FEATURE_IPV6
914 if (family == AF_INET)
915#endif
916 setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
917 free(local_lsa);
918 }
919
920
921
922
923
924 VERB1 bb_error_msg("sending query to %s", p->p_dotted);
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939 p->p_xmt_msg.m_xmttime.int_partl = rand();
940 p->p_xmt_msg.m_xmttime.fractionl = rand();
941 p->p_xmttime = gettime1900d();
942
943
944
945
946
947
948
949 p->reachable_bits <<= 1;
950
951#if ENABLE_FEATURE_NTP_AUTH
952 if (p->key_entry)
953 hash_peer(p);
954 if (do_sendto(p->p_fd, NULL, &p->p_lsa->u.sa, p->p_lsa->len,
955 &p->p_xmt_msg, !p->key_entry ? NTP_MSGSIZE_NOAUTH : p->key_entry->msg_size) == -1
956 )
957#else
958 if (do_sendto(p->p_fd, NULL, &p->p_lsa->u.sa, p->p_lsa->len,
959 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
960 )
961#endif
962 {
963 close(p->p_fd);
964 p->p_fd = -1;
965
966
967
968
969
970 set_next(p, RETRY_INTERVAL);
971 return;
972 }
973
974 set_next(p, RESPONSE_INTERVAL);
975}
976
977
978
979
980
981
982
983
984static void run_script(const char *action, double offset)
985{
986 char *argv[3];
987 char *env1, *env2, *env3, *env4;
988
989 G.last_script_run = G.cur_time;
990
991 if (!G.script_name)
992 return;
993
994 argv[0] = (char*) G.script_name;
995 argv[1] = (char*) action;
996 argv[2] = NULL;
997
998 VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
999
1000 env1 = xasprintf("%s=%u", "stratum", G.stratum);
1001 putenv(env1);
1002 env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
1003 putenv(env2);
1004 env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
1005 putenv(env3);
1006 env4 = xasprintf("%s=%f", "offset", offset);
1007 putenv(env4);
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017 spawn(argv);
1018
1019 unsetenv("stratum");
1020 unsetenv("freq_drift_ppm");
1021 unsetenv("poll_interval");
1022 unsetenv("offset");
1023 free(env1);
1024 free(env2);
1025 free(env3);
1026 free(env4);
1027}
1028
1029static NOINLINE void
1030step_time(double offset)
1031{
1032 llist_t *item;
1033 double dtime;
1034 struct timeval tvc, tvn;
1035 char buf[sizeof("yyyy-mm-dd hh:mm:ss") + 4];
1036 time_t tval;
1037
1038 xgettimeofday(&tvc);
1039 dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
1040 d_to_tv(&tvn, dtime);
1041 xsettimeofday(&tvn);
1042
1043 VERB2 {
1044 tval = tvc.tv_sec;
1045 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1046 bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
1047 }
1048 tval = tvn.tv_sec;
1049 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1050 bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
1051
1052
1053
1054
1055
1056 G.cur_time += offset;
1057 G.last_update_recv_time += offset;
1058 G.last_script_run += offset;
1059
1060
1061 for (item = G.ntp_peers; item != NULL; item = item->link) {
1062 peer_t *pp = (peer_t *) item->data;
1063 reset_peer_stats(pp, offset);
1064
1065
1066 pp->next_action_time += offset;
1067 if (pp->p_fd >= 0) {
1068
1069
1070
1071
1072 close(pp->p_fd);
1073 pp->p_fd = -1;
1074 set_next(pp, RETRY_INTERVAL);
1075 }
1076 }
1077}
1078
1079static void clamp_pollexp_and_set_MAXSTRAT(void)
1080{
1081 if (G.poll_exp < MINPOLL)
1082 G.poll_exp = MINPOLL;
1083 if (G.poll_exp > BIGPOLL)
1084 G.poll_exp = BIGPOLL;
1085 G.polladj_count = 0;
1086 G.stratum = MAXSTRAT;
1087}
1088
1089
1090
1091
1092
1093typedef struct {
1094 peer_t *p;
1095 int type;
1096 double edge;
1097 double opt_rd;
1098} point_t;
1099static int
1100compare_point_edge(const void *aa, const void *bb)
1101{
1102 const point_t *a = aa;
1103 const point_t *b = bb;
1104 if (a->edge < b->edge) {
1105 return -1;
1106 }
1107 return (a->edge > b->edge);
1108}
1109typedef struct {
1110 peer_t *p;
1111 double metric;
1112} survivor_t;
1113static int
1114compare_survivor_metric(const void *aa, const void *bb)
1115{
1116 const survivor_t *a = aa;
1117 const survivor_t *b = bb;
1118 if (a->metric < b->metric) {
1119 return -1;
1120 }
1121 return (a->metric > b->metric);
1122}
1123static int
1124fit(peer_t *p, double rd)
1125{
1126 if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
1127
1128 VERB4 bb_error_msg("peer %s unfit for selection: "
1129 "unreachable", p->p_dotted);
1130 return 0;
1131 }
1132#if 0
1133 if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
1134 || p->lastpkt_stratum >= MAXSTRAT
1135 ) {
1136 VERB4 bb_error_msg("peer %s unfit for selection: "
1137 "bad status/stratum", p->p_dotted);
1138 return 0;
1139 }
1140#endif
1141
1142 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
1143 VERB3 bb_error_msg("peer %s unfit for selection: "
1144 "root distance %f too high, jitter:%f",
1145 p->p_dotted, rd, p->filter_jitter
1146 );
1147 return 0;
1148 }
1149
1150
1151
1152
1153 return 1;
1154}
1155static NOINLINE peer_t*
1156select_and_cluster(void)
1157{
1158 peer_t *p;
1159 llist_t *item;
1160 int i, j;
1161 int size = 3 * G.peer_cnt;
1162
1163 point_t point[size];
1164 unsigned num_points, num_candidates;
1165 double low, high;
1166 unsigned num_falsetickers;
1167
1168 survivor_t survivor[size];
1169 unsigned num_survivors;
1170
1171
1172
1173 num_points = 0;
1174 item = G.ntp_peers;
1175 while (item != NULL) {
1176 double rd, offset;
1177
1178 p = (peer_t *) item->data;
1179 rd = root_distance(p);
1180 offset = p->filter_offset;
1181 if (!fit(p, rd)) {
1182 item = item->link;
1183 continue;
1184 }
1185
1186 VERB5 bb_error_msg("interval: [%f %f %f] %s",
1187 offset - rd,
1188 offset,
1189 offset + rd,
1190 p->p_dotted
1191 );
1192 point[num_points].p = p;
1193 point[num_points].type = -1;
1194 point[num_points].edge = offset - rd;
1195 point[num_points].opt_rd = rd;
1196 num_points++;
1197 point[num_points].p = p;
1198 point[num_points].type = 0;
1199 point[num_points].edge = offset;
1200 point[num_points].opt_rd = rd;
1201 num_points++;
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 item = item->link;
1208 }
1209 num_candidates = num_points / 3;
1210 if (num_candidates == 0) {
1211 VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
1212 return NULL;
1213 }
1214
1215 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227 num_falsetickers = 0;
1228 while (1) {
1229 int c;
1230 unsigned num_midpoints = 0;
1231
1232 low = 1 << 9;
1233 high = - (1 << 9);
1234 c = 0;
1235 for (i = 0; i < num_points; i++) {
1236
1237
1238
1239
1240
1241 c -= point[i].type;
1242 if (c >= num_candidates - num_falsetickers) {
1243
1244 low = point[i].edge;
1245 break;
1246 }
1247 if (point[i].type == 0)
1248 num_midpoints++;
1249 }
1250 c = 0;
1251 for (i = num_points-1; i >= 0; i--) {
1252 c += point[i].type;
1253 if (c >= num_candidates - num_falsetickers) {
1254 high = point[i].edge;
1255 break;
1256 }
1257 if (point[i].type == 0)
1258 num_midpoints++;
1259 }
1260
1261
1262
1263
1264
1265 if (num_midpoints <= num_falsetickers && low < high)
1266 break;
1267 num_falsetickers++;
1268 if (num_falsetickers * 2 >= num_candidates) {
1269 VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
1270 num_falsetickers, num_candidates,
1271 ", no peer selected");
1272 return NULL;
1273 }
1274 }
1275 VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
1276 low, high, num_candidates, num_falsetickers);
1277
1278
1279
1280
1281
1282
1283
1284
1285 num_survivors = 0;
1286 for (i = 0; i < num_points; i++) {
1287 if (point[i].edge < low || point[i].edge > high)
1288 continue;
1289 p = point[i].p;
1290 survivor[num_survivors].p = p;
1291
1292 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
1293 VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
1294 num_survivors, survivor[num_survivors].metric, p->p_dotted);
1295 num_survivors++;
1296 }
1297
1298
1299
1300
1301
1302 if (num_survivors < MIN_SELECTED) {
1303 VERB3 bb_error_msg("survivors:%d%s",
1304 num_survivors,
1305 ", no peer selected");
1306 return NULL;
1307 }
1308
1309
1310
1311 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1312
1313
1314
1315
1316
1317
1318
1319 while (1) {
1320 unsigned max_idx = max_idx;
1321 double max_selection_jitter = max_selection_jitter;
1322 double min_jitter = min_jitter;
1323
1324 if (num_survivors <= MIN_CLUSTERED) {
1325 VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
1326 num_survivors, MIN_CLUSTERED);
1327 break;
1328 }
1329
1330
1331
1332
1333
1334
1335 for (i = 0; i < num_survivors; i++) {
1336 double selection_jitter_sq;
1337
1338 p = survivor[i].p;
1339 if (i == 0 || p->filter_jitter < min_jitter)
1340 min_jitter = p->filter_jitter;
1341
1342 selection_jitter_sq = 0;
1343 for (j = 0; j < num_survivors; j++) {
1344 peer_t *q = survivor[j].p;
1345 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1346 }
1347 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1348 max_selection_jitter = selection_jitter_sq;
1349 max_idx = i;
1350 }
1351 VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
1352 i, selection_jitter_sq);
1353 }
1354 max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
1355 VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1356 max_idx, max_selection_jitter, min_jitter);
1357
1358
1359
1360
1361
1362
1363 if (max_selection_jitter < min_jitter) {
1364 VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1365 max_selection_jitter, min_jitter, num_survivors);
1366 break;
1367 }
1368
1369
1370
1371
1372 VERB6 bb_error_msg("dropping survivor %d", max_idx);
1373 num_survivors--;
1374 while (max_idx < num_survivors) {
1375 survivor[max_idx] = survivor[max_idx + 1];
1376 max_idx++;
1377 }
1378 }
1379
1380 if (0) {
1381
1382
1383
1384
1385
1386
1387
1388
1389 double x, y, z, w;
1390 y = z = w = 0;
1391 for (i = 0; i < num_survivors; i++) {
1392 p = survivor[i].p;
1393 x = root_distance(p);
1394 y += 1 / x;
1395 z += p->filter_offset / x;
1396 w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1397 }
1398
1399
1400 }
1401
1402
1403
1404
1405
1406
1407 p = survivor[0].p;
1408 if (G.last_update_peer
1409 && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1410 ) {
1411
1412 for (i = 1; i < num_survivors; i++) {
1413 if (G.last_update_peer == survivor[i].p) {
1414 VERB5 bb_simple_error_msg("keeping old synced peer");
1415 p = G.last_update_peer;
1416 goto keep_old;
1417 }
1418 }
1419 }
1420 G.last_update_peer = p;
1421 keep_old:
1422 VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
1423 p->p_dotted,
1424 p->filter_offset,
1425 G.cur_time - p->lastpkt_recv_time
1426 );
1427 return p;
1428}
1429
1430
1431
1432
1433
1434static void
1435set_new_values(double offset, double recv_time)
1436{
1437
1438
1439
1440
1441 VERB4 bb_error_msg("last update offset=%f recv_time=%f",
1442 offset, recv_time);
1443 G.last_update_offset = offset;
1444 G.last_update_recv_time = recv_time;
1445}
1446
1447static NOINLINE int
1448update_local_clock(peer_t *p)
1449{
1450 int rc;
1451 struct timex tmx;
1452
1453 double offset = p->filter_offset;
1454 double recv_time = p->lastpkt_recv_time;
1455 double abs_offset;
1456#if !USING_KERNEL_PLL_LOOP
1457 double freq_drift;
1458 double since_last_update;
1459#endif
1460 double etemp, dtemp;
1461
1462 abs_offset = fabs(offset);
1463
1464#if 0
1465
1466
1467
1468 if (abs_offset > PANIC_THRESHOLD) {
1469 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1470 }
1471#endif
1472
1473
1474
1475
1476
1477 if (recv_time <= G.last_update_recv_time) {
1478 VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
1479 p->p_dotted);
1480 return 0;
1481 }
1482
1483
1484
1485
1486
1487#if !USING_KERNEL_PLL_LOOP
1488 since_last_update = recv_time - G.reftime;
1489 freq_drift = 0;
1490#endif
1491
1492
1493
1494
1495 if (abs_offset > STEP_THRESHOLD) {
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517 VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
1518 step_time(offset);
1519 if (option_mask32 & OPT_q) {
1520
1521 exit(0);
1522 }
1523
1524 clamp_pollexp_and_set_MAXSTRAT();
1525
1526 run_script("step", offset);
1527
1528 recv_time += offset;
1529
1530 abs_offset = offset = 0;
1531 set_new_values(offset, recv_time);
1532 } else {
1533
1534 if (option_mask32 & OPT_q) {
1535
1536
1537
1538 exit(0);
1539 }
1540
1541
1542
1543
1544 G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
1545
1546
1547
1548
1549 etemp = SQUARE(G.discipline_jitter);
1550 dtemp = SQUARE(offset - G.last_update_offset);
1551 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1552 if (G.discipline_jitter < G_precision_sec)
1553 G.discipline_jitter = G_precision_sec;
1554
1555#if !USING_KERNEL_PLL_LOOP
1556
1557
1558
1559
1560
1561
1562
1563
1564 if ((1 << G.poll_exp) > ALLAN / 2) {
1565 etemp = FLL - G.poll_exp;
1566 if (etemp < AVG)
1567 etemp = AVG;
1568 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1569 }
1570
1571
1572
1573
1574
1575 etemp = MIND(since_last_update, (1 << G.poll_exp));
1576 dtemp = (4 * PLL) << G.poll_exp;
1577 freq_drift += offset * etemp / SQUARE(dtemp);
1578#endif
1579 set_new_values(offset, recv_time);
1580 if (G.stratum != p->lastpkt_stratum + 1) {
1581 G.stratum = p->lastpkt_stratum + 1;
1582 run_script("stratum", offset);
1583 }
1584 }
1585
1586 G.reftime = G.cur_time;
1587 G.ntp_status = p->lastpkt_status;
1588#if ENABLE_FEATURE_NTPD_SERVER
1589
1590 G.refid = p->p_refid;
1591#endif
1592 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1593 dtemp = p->filter_jitter;
1594 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
1595 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1596 VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1597
1598
1599
1600
1601#if !USING_KERNEL_PLL_LOOP
1602
1603
1604
1605
1606
1607
1608 dtemp = G.discipline_freq_drift + freq_drift;
1609 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1610 etemp = SQUARE(G.discipline_wander);
1611 dtemp = SQUARE(dtemp);
1612 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1613
1614 VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1615 G.discipline_freq_drift,
1616 (long)(G.discipline_freq_drift * 65536e6),
1617 freq_drift,
1618 G.discipline_wander);
1619#endif
1620 VERB4 {
1621 memset(&tmx, 0, sizeof(tmx));
1622 if (adjtimex(&tmx) < 0)
1623 bb_simple_perror_msg_and_die("adjtimex");
1624 bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
1625 tmx.freq, tmx.offset, tmx.status, tmx.constant);
1626 }
1627
1628 memset(&tmx, 0, sizeof(tmx));
1629#if 0
1630
1631
1632
1633
1634 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1635
1636 tmx.freq = G.discipline_freq_drift * 65536e6;
1637#endif
1638 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;
1639
1640 tmx.offset = (long)(offset * 1000000);
1641 if (SLEW_THRESHOLD < STEP_THRESHOLD) {
1642 if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
1643 tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
1644 }
1645 if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
1646 tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
1647 }
1648 }
1649
1650 tmx.status = STA_PLL;
1651 if (G.FREQHOLD_cnt != 0) {
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664 if (G.FREQHOLD_cnt < 0) {
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704 unsigned off_032 = abs((int)(tmx.offset >> 15));
1705 G.FREQHOLD_cnt = 1 + MIN_FREQHOLD + off_032;
1706 }
1707 G.FREQHOLD_cnt--;
1708 tmx.status |= STA_FREQHOLD;
1709 }
1710 if (G.ntp_status & LI_PLUSSEC)
1711 tmx.status |= STA_INS;
1712 if (G.ntp_status & LI_MINUSSEC)
1713 tmx.status |= STA_DEL;
1714
1715 tmx.constant = (int)G.poll_exp - 4;
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726 if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
1727 tmx.constant--;
1728 if (tmx.constant < 0)
1729 tmx.constant = 0;
1730
1731
1732
1733 rc = adjtimex(&tmx);
1734 if (rc < 0)
1735 bb_simple_perror_msg_and_die("adjtimex");
1736
1737
1738
1739 VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
1740 rc, tmx.freq, tmx.offset, tmx.status);
1741 G.kernel_freq_drift = tmx.freq / 65536;
1742 VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
1743 p->p_dotted,
1744 offset,
1745 p->p_raw_delay,
1746 G.discipline_jitter,
1747 (double)tmx.freq / 65536,
1748 (int)tmx.constant
1749 );
1750
1751 return 1;
1752}
1753
1754
1755
1756
1757
1758static unsigned
1759poll_interval(int upper_bound)
1760{
1761 unsigned interval, r, mask;
1762 interval = 1 << G.poll_exp;
1763 if (interval > upper_bound)
1764 interval = upper_bound;
1765 mask = ((interval-1) >> 4) | 1;
1766 r = rand();
1767 interval += r & mask;
1768 VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
1769 return interval;
1770}
1771static void
1772adjust_poll(int count)
1773{
1774 G.polladj_count += count;
1775 if (G.polladj_count > POLLADJ_LIMIT) {
1776 G.polladj_count = 0;
1777 if (G.poll_exp < MAXPOLL) {
1778 G.poll_exp++;
1779 VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1780 G.discipline_jitter, G.poll_exp);
1781 }
1782 } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
1783 G.polladj_count = 0;
1784 if (G.poll_exp > MINPOLL) {
1785 llist_t *item;
1786
1787 G.poll_exp--;
1788
1789
1790
1791
1792
1793
1794 for (item = G.ntp_peers; item != NULL; item = item->link) {
1795 peer_t *pp = (peer_t *) item->data;
1796 if (pp->p_fd < 0)
1797 pp->next_action_time -= (1 << G.poll_exp);
1798 }
1799 VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1800 G.discipline_jitter, G.poll_exp);
1801 }
1802 } else {
1803 VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
1804 }
1805}
1806static NOINLINE void
1807recv_and_process_peer_pkt(peer_t *p)
1808{
1809 int rc;
1810 ssize_t size;
1811 msg_t msg;
1812 double T1, T2, T3, T4;
1813 double offset;
1814 double prev_delay, delay;
1815 unsigned interval;
1816 datapoint_t *datapoint;
1817 peer_t *q;
1818
1819 offset = 0;
1820
1821
1822
1823
1824
1825
1826
1827 if (p->p_fd < 0)
1828 return;
1829
1830
1831
1832
1833
1834 recv_again:
1835 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1836 if (size < 0) {
1837 if (errno == EINTR)
1838
1839 goto recv_again;
1840 if (errno == EAGAIN)
1841
1842
1843
1844
1845 return;
1846
1847
1848
1849
1850 bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
1851 }
1852
1853#if ENABLE_FEATURE_NTP_AUTH
1854 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH) {
1855 bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
1856 return;
1857 }
1858 if (p->key_entry && hashes_differ(p, &msg)) {
1859 bb_error_msg("invalid cryptographic hash received from %s", p->p_dotted);
1860 return;
1861 }
1862#else
1863 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH) {
1864 bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
1865 return;
1866 }
1867#endif
1868
1869 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1870 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1871 ) {
1872
1873 return;
1874 }
1875
1876
1877
1878
1879
1880 close(p->p_fd);
1881 p->p_fd = -1;
1882
1883 if ((msg.m_status & LI_ALARM) == LI_ALARM
1884 || msg.m_stratum == 0
1885 || msg.m_stratum > NTP_MAXSTRATUM
1886 ) {
1887 bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
1888
1889
1890
1891
1892
1893
1894 if (G.poll_exp < BIGPOLL)
1895 goto increase_interval;
1896 goto pick_normal_interval;
1897 }
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917 T1 = p->p_xmttime;
1918 T2 = lfp_to_d(msg.m_rectime);
1919 T3 = lfp_to_d(msg.m_xmttime);
1920 T4 = G.cur_time;
1921 delay = (T4 - T1) - (T3 - T2);
1922
1923
1924
1925
1926
1927 prev_delay = p->p_raw_delay;
1928 p->p_raw_delay = (delay < 0 ? 0.0 : delay);
1929 if (p->reachable_bits
1930 && delay > prev_delay * BAD_DELAY_GROWTH
1931 && delay > 1.0 / (8 * 1024)
1932 ) {
1933 bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
1934 goto pick_normal_interval;
1935 }
1936
1937
1938
1939
1940
1941
1942
1943 if (delay < G_precision_sec)
1944 delay = G_precision_sec;
1945 p->lastpkt_delay = delay;
1946 p->lastpkt_recv_time = T4;
1947 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
1948 p->lastpkt_status = msg.m_status;
1949 p->lastpkt_stratum = msg.m_stratum;
1950 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1951 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1952 p->lastpkt_refid = msg.m_refid;
1953
1954 p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
1955 datapoint = &p->filter_datapoint[p->datapoint_idx];
1956 datapoint->d_recv_time = T4;
1957 datapoint->d_offset = offset = ((T2 - T1) + (T3 - T4)) / 2;
1958 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
1959 if (!p->reachable_bits) {
1960
1961 int i;
1962 for (i = 0; i < NUM_DATAPOINTS; i++) {
1963 p->filter_datapoint[i].d_offset = offset;
1964 }
1965 }
1966
1967 p->reachable_bits |= 1;
1968 if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
1969 bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
1970 p->p_dotted,
1971 offset,
1972 p->p_raw_delay,
1973 p->lastpkt_status,
1974 p->lastpkt_stratum,
1975 p->lastpkt_refid,
1976 p->lastpkt_rootdelay,
1977 p->reachable_bits
1978
1979
1980
1981 );
1982 }
1983
1984
1985 filter_datapoints(p);
1986 q = select_and_cluster();
1987 rc = 0;
1988 if (q) {
1989 if (!(option_mask32 & OPT_w)) {
1990 rc = update_local_clock(q);
1991#if 0
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003 if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
2004 VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
2005 adjust_poll(-POLLADJ_LIMIT * 3);
2006 rc = 0;
2007 }
2008#endif
2009 }
2010 } else {
2011
2012
2013
2014 if (G.poll_exp < BIGPOLL)
2015 goto increase_interval;
2016 }
2017
2018 if (rc != 0) {
2019
2020
2021
2022
2023
2024
2025 if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
2026
2027
2028 increase_interval:
2029 adjust_poll(MINPOLL);
2030 } else {
2031 VERB3 if (rc > 0)
2032 bb_error_msg("want smaller interval: offset/jitter = %u",
2033 G.offset_to_jitter_ratio);
2034 adjust_poll(-G.poll_exp * 2);
2035 }
2036 }
2037
2038
2039 pick_normal_interval:
2040 interval = poll_interval(INT_MAX);
2041 if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053 interval = BIGOFF_INTERVAL;
2054 }
2055
2056 set_next(p, interval);
2057}
2058
2059#if ENABLE_FEATURE_NTPD_SERVER
2060static NOINLINE void
2061recv_and_process_client_pkt(void )
2062{
2063 ssize_t size;
2064
2065 len_and_sockaddr *to;
2066 struct sockaddr *from;
2067 msg_t msg;
2068 uint8_t query_status;
2069 l_fixedpt_t query_xmttime;
2070
2071 to = get_sock_lsa(G_listen_fd);
2072 from = xzalloc(to->len);
2073
2074 size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
2075
2076
2077
2078
2079
2080
2081
2082# if ENABLE_FEATURE_NTP_AUTH
2083 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH)
2084# else
2085 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH)
2086# endif
2087 {
2088 char *addr;
2089 if (size < 0) {
2090 if (errno == EAGAIN)
2091 goto bail;
2092 bb_simple_perror_msg_and_die("recv");
2093 }
2094 addr = xmalloc_sockaddr2dotted_noport(from);
2095 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
2096 free(addr);
2097 goto bail;
2098 }
2099
2100
2101 if ((msg.m_status & MODE_MASK) != MODE_CLIENT
2102 && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
2103 ) {
2104 goto bail;
2105 }
2106
2107 query_status = msg.m_status;
2108 query_xmttime = msg.m_xmttime;
2109
2110
2111 memset(&msg, 0, sizeof(msg));
2112 msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
2113 msg.m_status |= (query_status & VERSION_MASK);
2114 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
2115 MODE_SERVER : MODE_SYM_PAS;
2116 msg.m_stratum = G.stratum;
2117 msg.m_ppoll = G.poll_exp;
2118 msg.m_precision_exp = G_precision_exp;
2119
2120 d_to_lfp(&msg.m_rectime, G.cur_time);
2121 d_to_lfp(&msg.m_xmttime, gettime1900d());
2122 if (G.peer_cnt == 0) {
2123
2124 G.reftime = G.cur_time;
2125 }
2126 d_to_lfp(&msg.m_reftime, G.reftime);
2127 msg.m_orgtime = query_xmttime;
2128 d_to_sfp(&msg.m_rootdelay, G.rootdelay);
2129
2130 d_to_sfp(&msg.m_rootdisp, G.rootdisp);
2131
2132 msg.m_refid = G.refid;
2133
2134
2135
2136 do_sendto(G_listen_fd,
2137 &to->u.sa, from, to->len,
2138 &msg, size);
2139 VERB3 {
2140 char *addr;
2141 addr = xmalloc_sockaddr2dotted_noport(from);
2142 bb_error_msg("responded to query from %s", addr);
2143 free(addr);
2144 }
2145
2146 bail:
2147 free(to);
2148 free(from);
2149}
2150#endif
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236#if ENABLE_FEATURE_NTP_AUTH
2237static key_entry_t *
2238find_key_entry(llist_t *key_entries, unsigned id)
2239{
2240 while (key_entries) {
2241 key_entry_t *cur = (key_entry_t*) key_entries->data;
2242 if (cur->id == id)
2243 return cur;
2244 key_entries = key_entries->link;
2245 }
2246 bb_error_msg_and_die("key %u is not defined", id);
2247}
2248#endif
2249
2250
2251
2252
2253static NOINLINE void ntp_init(char **argv)
2254{
2255 unsigned opts;
2256 llist_t *peers;
2257#if ENABLE_FEATURE_NTP_AUTH
2258 llist_t *key_entries;
2259 char *key_file_path;
2260#endif
2261
2262 srand(getpid());
2263
2264
2265 G.discipline_jitter = G_precision_sec;
2266 G.stratum = MAXSTRAT;
2267 if (BURSTPOLL != 0)
2268 G.poll_exp = BURSTPOLL;
2269 G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d();
2270 G.FREQHOLD_cnt = -1;
2271
2272
2273 peers = NULL;
2274 IF_FEATURE_NTP_AUTH(key_entries = NULL;)
2275 opts = getopt32(argv, "^"
2276 "nqNx"
2277 IF_FEATURE_NTP_AUTH("k:")
2278 "wp:*S:"IF_FEATURE_NTPD_SERVER("l")
2279 IF_FEATURE_NTPD_SERVER("I:")
2280 "d"
2281 "46aAbgL"
2282 "\0"
2283 "=0"
2284 ":dd:wn"
2285 IF_FEATURE_NTPD_SERVER(":Il")
2286 IF_FEATURE_NTP_AUTH(, &key_file_path)
2287 , &peers, &G.script_name
2288 IF_FEATURE_NTPD_SERVER(, &G.if_name)
2289 , &G.verbose
2290 );
2291
2292
2293
2294
2295#if ENABLE_FEATURE_NTPD_SERVER
2296 G_listen_fd = -1;
2297 if (opts & OPT_l) {
2298 G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
2299 if (G.if_name) {
2300 if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
2301 xfunc_die();
2302 }
2303 socket_want_pktinfo(G_listen_fd);
2304 setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
2305 }
2306#endif
2307
2308 if (opts & OPT_N)
2309 setpriority(PRIO_PROCESS, 0, -15);
2310
2311 if (!(opts & OPT_n)) {
2312 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
2313 logmode = LOGMODE_NONE;
2314 }
2315
2316#if ENABLE_FEATURE_NTP_AUTH
2317 if (opts & OPT_k) {
2318 char *tokens[4];
2319 parser_t *parser;
2320
2321 parser = config_open(key_file_path);
2322 while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL | PARSE_MIN_DIE) == 3) {
2323 key_entry_t *key_entry;
2324 char buffer[40];
2325 smalluint hash_type;
2326 smalluint msg_size;
2327 smalluint key_length;
2328 char *key;
2329
2330 if ((tokens[1][0] | 0x20) == 'm')
2331
2332 hash_type = HASH_MD5;
2333 else
2334 if (strncasecmp(tokens[1], "sha", 3) == 0)
2335
2336 hash_type = HASH_SHA1;
2337 else
2338 bb_simple_error_msg_and_die("only MD5 and SHA1 keys supported");
2339
2340
2341
2342
2343
2344
2345
2346
2347 key_length = strnlen(tokens[2], sizeof(buffer)+1);
2348 if (key_length >= sizeof(buffer)+1) {
2349 err:
2350 bb_error_msg_and_die("malformed key at line %u", parser->lineno);
2351 }
2352 if (hash_type == HASH_MD5) {
2353 key = tokens[2];
2354 msg_size = NTP_MSGSIZE_MD5_AUTH;
2355 } else
2356 if (!(key_length & 1)) {
2357 key_length >>= 1;
2358 if (!hex2bin(buffer, tokens[2], key_length))
2359 goto err;
2360 key = buffer;
2361 msg_size = NTP_MSGSIZE_SHA1_AUTH;
2362 } else {
2363 goto err;
2364 }
2365 key_entry = xzalloc(sizeof(*key_entry) + key_length);
2366 key_entry->type = hash_type;
2367 key_entry->msg_size = msg_size;
2368 key_entry->key_length = key_length;
2369 memcpy(key_entry->key, key, key_length);
2370 key_entry->id = xatou_range(tokens[0], 1, MAX_KEY_NUMBER);
2371 llist_add_to(&key_entries, key_entry);
2372 }
2373 config_close(parser);
2374 }
2375#endif
2376 if (peers) {
2377#if ENABLE_FEATURE_NTP_AUTH
2378 while (peers) {
2379 char *peer = llist_pop(&peers);
2380 key_entry_t *key_entry = NULL;
2381 if (strncmp(peer, "keyno:", 6) == 0) {
2382 char *end;
2383 int key_id;
2384 peer += 6;
2385 end = strchr(peer, ':');
2386 if (!end) bb_show_usage();
2387 *end = '\0';
2388 key_id = xatou_range(peer, 1, MAX_KEY_NUMBER);
2389 *end = ':';
2390 key_entry = find_key_entry(key_entries, key_id);
2391 peer = end + 1;
2392 }
2393 add_peers(peer, key_entry);
2394 }
2395#else
2396 while (peers)
2397 add_peers(llist_pop(&peers), NULL);
2398#endif
2399 }
2400#if ENABLE_FEATURE_NTPD_CONF
2401 else {
2402 parser_t *parser;
2403 char *token[3 + 2*ENABLE_FEATURE_NTP_AUTH];
2404
2405 parser = config_open("/etc/ntp.conf");
2406 while (config_read(parser, token, 3 + 2*ENABLE_FEATURE_NTP_AUTH, 1, "# \t", PARSE_NORMAL)) {
2407 if (strcmp(token[0], "server") == 0 && token[1]) {
2408# if ENABLE_FEATURE_NTP_AUTH
2409 key_entry_t *key_entry = NULL;
2410 if (token[2] && token[3] && strcmp(token[2], "key") == 0) {
2411 unsigned key_id = xatou_range(token[3], 1, MAX_KEY_NUMBER);
2412 key_entry = find_key_entry(key_entries, key_id);
2413 }
2414 add_peers(token[1], key_entry);
2415# else
2416 add_peers(token[1], NULL);
2417# endif
2418 continue;
2419 }
2420 bb_error_msg("skipping %s:%u: unimplemented command '%s'",
2421 "/etc/ntp.conf", parser->lineno, token[0]
2422 );
2423 }
2424 config_close(parser);
2425 }
2426#endif
2427 if (G.peer_cnt == 0) {
2428 if (!(opts & OPT_l))
2429 bb_show_usage();
2430
2431 G.stratum = 1;
2432 }
2433
2434 if (!(opts & OPT_n))
2435 write_pidfile_std_path_and_ext("ntpd");
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446 if (opts & OPT_q) {
2447 option_mask32 |= OPT_qq;
2448 alarm(10);
2449 }
2450
2451 bb_signals(0
2452 | (1 << SIGTERM)
2453 | (1 << SIGINT)
2454 | (1 << SIGALRM)
2455 , record_signo
2456 );
2457 bb_signals(0
2458 | (1 << SIGPIPE)
2459 | (1 << SIGCHLD)
2460 , SIG_IGN
2461 );
2462
2463}
2464
2465int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
2466int ntpd_main(int argc UNUSED_PARAM, char **argv)
2467{
2468#undef G
2469 struct globals G;
2470 struct pollfd *pfd;
2471 peer_t **idx2peer;
2472 unsigned cnt;
2473
2474 memset(&G, 0, sizeof(G));
2475 SET_PTR_TO_GLOBALS(&G);
2476
2477 ntp_init(argv);
2478
2479
2480 cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
2481 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
2482 pfd = xzalloc(sizeof(pfd[0]) * cnt);
2483
2484
2485
2486
2487
2488
2489
2490
2491 cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
2492
2493 while (!bb_got_signal) {
2494 llist_t *item;
2495 unsigned i, j;
2496 int nfds, timeout;
2497 double nextaction;
2498
2499
2500
2501 nextaction = G.last_script_run + (11*60);
2502 if (nextaction < G.cur_time + 1)
2503 nextaction = G.cur_time + 1;
2504
2505 i = 0;
2506#if ENABLE_FEATURE_NTPD_SERVER
2507 if (G_listen_fd != -1) {
2508 pfd[0].fd = G_listen_fd;
2509 pfd[0].events = POLLIN;
2510 i++;
2511 }
2512#endif
2513
2514 for (item = G.ntp_peers; item != NULL; item = item->link) {
2515 peer_t *p = (peer_t *) item->data;
2516
2517 if (p->next_action_time <= G.cur_time) {
2518 if (p->p_fd == -1) {
2519
2520 if (--cnt == 0) {
2521 VERB4 bb_simple_error_msg("disabling burst mode");
2522 G.polladj_count = 0;
2523 G.poll_exp = MINPOLL;
2524 }
2525 send_query_to_peer(p);
2526 } else {
2527
2528 close(p->p_fd);
2529 p->p_fd = -1;
2530
2531 if (G.poll_exp < BIGPOLL)
2532 adjust_poll(MINPOLL);
2533 timeout = poll_interval(NOREPLY_INTERVAL);
2534 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
2535 p->p_dotted, p->reachable_bits, timeout);
2536
2537
2538 if (p->reachable_bits == 0)
2539 resolve_peer_hostname(p);
2540
2541 set_next(p, timeout);
2542 }
2543 }
2544
2545 if (p->next_action_time < nextaction)
2546 nextaction = p->next_action_time;
2547
2548 if (p->p_fd >= 0) {
2549
2550 pfd[i].fd = p->p_fd;
2551 pfd[i].events = POLLIN;
2552 idx2peer[i] = p;
2553 i++;
2554 }
2555 }
2556
2557 timeout = nextaction - G.cur_time;
2558 if (timeout < 0)
2559 timeout = 0;
2560 timeout++;
2561
2562
2563 VERB3 {
2564 if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
2565
2566
2567
2568
2569
2570 nfds = poll(pfd, i, 1000);
2571 if (nfds != 0)
2572 goto did_poll;
2573 if (--timeout <= 0)
2574 goto did_poll;
2575 }
2576 bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
2577 }
2578 nfds = poll(pfd, i, timeout * 1000);
2579 did_poll:
2580 gettime1900d();
2581 if (nfds <= 0) {
2582 double ct;
2583 int dns_error;
2584
2585 if (bb_got_signal)
2586 break;
2587
2588 if (G.cur_time - G.last_script_run > 11*60) {
2589
2590 run_script("periodic", G.last_update_offset);
2591 gettime1900d();
2592 }
2593
2594
2595
2596
2597
2598
2599 dns_error = 0;
2600 ct = G.cur_time;
2601 for (item = G.ntp_peers; item != NULL; item = item->link) {
2602 peer_t *p = (peer_t *) item->data;
2603 if (p->next_action_time <= ct && !p->p_lsa) {
2604
2605 dns_error |= (!resolve_peer_hostname(p));
2606 }
2607 }
2608 if (!dns_error)
2609 goto check_unsync;
2610
2611 gettime1900d();
2612 for (item = G.ntp_peers; item != NULL; item = item->link) {
2613 peer_t *p = (peer_t *) item->data;
2614 if (p->next_action_time <= ct && !p->p_lsa) {
2615 set_next(p, HOSTNAME_INTERVAL * p->dns_errors);
2616 }
2617 }
2618 goto check_unsync;
2619 }
2620
2621
2622 j = 0;
2623#if ENABLE_FEATURE_NTPD_SERVER
2624 if (G.listen_fd != -1) {
2625 if (pfd[0].revents ) {
2626 nfds--;
2627 recv_and_process_client_pkt();
2628 gettime1900d();
2629 }
2630 j = 1;
2631 }
2632#endif
2633 for (; nfds != 0 && j < i; j++) {
2634 if (pfd[j].revents ) {
2635
2636
2637
2638
2639
2640 if (option_mask32 & OPT_qq) {
2641 option_mask32 &= ~OPT_qq;
2642 alarm(50);
2643 }
2644 nfds--;
2645 recv_and_process_peer_pkt(idx2peer[j]);
2646 gettime1900d();
2647 }
2648 }
2649
2650 check_unsync:
2651 if (G.ntp_peers && G.stratum != MAXSTRAT) {
2652 for (item = G.ntp_peers; item != NULL; item = item->link) {
2653 peer_t *p = (peer_t *) item->data;
2654 if (p->reachable_bits)
2655 goto have_reachable_peer;
2656 }
2657
2658 clamp_pollexp_and_set_MAXSTRAT();
2659 run_script("unsync", 0.0);
2660 have_reachable_peer: ;
2661 }
2662 }
2663
2664 remove_pidfile_std_path_and_ext("ntpd");
2665 kill_myself_with_sig(bb_got_signal);
2666}
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677#if 0
2678static double
2679direct_freq(double fp_offset)
2680{
2681#ifdef KERNEL_PLL
2682
2683
2684
2685
2686 if (pll_control && kern_enable) {
2687 memset(&ntv, 0, sizeof(ntv));
2688 ntp_adjtime(&ntv);
2689#ifdef STA_NANO
2690 clock_offset = ntv.offset / 1e9;
2691#else
2692 clock_offset = ntv.offset / 1e6;
2693#endif
2694 drift_comp = FREQTOD(ntv.freq);
2695 }
2696#endif
2697 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2698 wander_resid = 0;
2699 return drift_comp;
2700}
2701
2702static void
2703set_freq(double freq)
2704{
2705 char tbuf[80];
2706
2707 drift_comp = freq;
2708
2709#ifdef KERNEL_PLL
2710
2711
2712
2713 if (pll_control && kern_enable) {
2714 memset(&ntv, 0, sizeof(ntv));
2715 ntv.modes = MOD_FREQUENCY;
2716 ntv.freq = DTOFREQ(drift_comp);
2717 ntp_adjtime(&ntv);
2718 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2719 report_event(EVNT_FSET, NULL, tbuf);
2720 } else {
2721 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2722 report_event(EVNT_FSET, NULL, tbuf);
2723 }
2724#else
2725 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2726 report_event(EVNT_FSET, NULL, tbuf);
2727#endif
2728}
2729
2730...
2731...
2732...
2733
2734#ifdef KERNEL_PLL
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750 if (pll_control && kern_enable) {
2751
2752#define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765 memset(&ntv, 0, sizeof(ntv));
2766 if (ext_enable) {
2767 ntv.modes = MOD_STATUS;
2768 } else {
2769#ifdef STA_NANO
2770 ntv.modes = MOD_BITS | MOD_NANO;
2771#else
2772 ntv.modes = MOD_BITS;
2773#endif
2774 if (clock_offset < 0)
2775 dtemp = -.5;
2776 else
2777 dtemp = .5;
2778#ifdef STA_NANO
2779 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2780 ntv.constant = sys_poll;
2781#else
2782 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2783 ntv.constant = sys_poll - 4;
2784#endif
2785 ntv.esterror = (u_int32)(clock_jitter * 1e6);
2786 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2787 ntv.status = STA_PLL;
2788
2789
2790
2791
2792 if (pps_enable) {
2793 if (!(pll_status & STA_PPSTIME))
2794 report_event(EVNT_KERN,
2795 NULL, "PPS enabled");
2796 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2797 } else {
2798 if (pll_status & STA_PPSTIME)
2799 report_event(EVNT_KERN,
2800 NULL, "PPS disabled");
2801 ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
2802 }
2803 if (sys_leap == LEAP_ADDSECOND)
2804 ntv.status |= STA_INS;
2805 else if (sys_leap == LEAP_DELSECOND)
2806 ntv.status |= STA_DEL;
2807 }
2808
2809
2810
2811
2812
2813
2814 if (ntp_adjtime(&ntv) == TIME_ERROR) {
2815 if (!(ntv.status & STA_PPSSIGNAL))
2816 report_event(EVNT_KERN, NULL,
2817 "PPS no signal");
2818 }
2819 pll_status = ntv.status;
2820#ifdef STA_NANO
2821 clock_offset = ntv.offset / 1e9;
2822#else
2823 clock_offset = ntv.offset / 1e6;
2824#endif
2825 clock_frequency = FREQTOD(ntv.freq);
2826
2827
2828
2829
2830 if (ntv.status & STA_PPSTIME) {
2831#ifdef STA_NANO
2832 clock_jitter = ntv.jitter / 1e9;
2833#else
2834 clock_jitter = ntv.jitter / 1e6;
2835#endif
2836 }
2837
2838#if defined(STA_NANO) && NTP_API == 4
2839
2840
2841
2842 if (loop_tai != sys_tai) {
2843 loop_tai = sys_tai;
2844 ntv.modes = MOD_TAI;
2845 ntv.constant = sys_tai;
2846 ntp_adjtime(&ntv);
2847 }
2848#endif
2849 }
2850#endif
2851#endif
2852