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