1 /*
2 * NTP state machine interfaces and logic.
3 *
4 * This code was mainly moved from kernel/timer.c and kernel/time.c
5 * Please see those files for relevant copyright info and historical
6 * changelogs.
7 */
8 #include <linux/capability.h>
9 #include <linux/clocksource.h>
10 #include <linux/workqueue.h>
11 #include <linux/hrtimer.h>
12 #include <linux/jiffies.h>
13 #include <linux/math64.h>
14 #include <linux/timex.h>
15 #include <linux/time.h>
16 #include <linux/mm.h>
17 #include <linux/module.h>
18 #include <linux/rtc.h>
19
20 #include "ntp_internal.h"
21
22 /*
23 * NTP timekeeping variables:
24 *
25 * Note: All of the NTP state is protected by the timekeeping locks.
26 */
27
28
29 /* USER_HZ period (usecs): */
30 unsigned long tick_usec = TICK_USEC;
31
32 /* SHIFTED_HZ period (nsecs): */
33 unsigned long tick_nsec;
34
35 static u64 tick_length;
36 static u64 tick_length_base;
37
38 #define SECS_PER_DAY 86400
39 #define MAX_TICKADJ 500LL /* usecs */
40 #define MAX_TICKADJ_SCALED \
41 (((MAX_TICKADJ * NSEC_PER_USEC) << NTP_SCALE_SHIFT) / NTP_INTERVAL_FREQ)
42 #define MAX_TAI_OFFSET 100000
43
44 /*
45 * phase-lock loop variables
46 */
47
48 /*
49 * clock synchronization status
50 *
51 * (TIME_ERROR prevents overwriting the CMOS clock)
52 */
53 static int time_state = TIME_OK;
54
55 /* clock status bits: */
56 static int time_status = STA_UNSYNC;
57
58 /* time adjustment (nsecs): */
59 static s64 time_offset;
60
61 /* pll time constant: */
62 static long time_constant = 2;
63
64 /* maximum error (usecs): */
65 static long time_maxerror = NTP_PHASE_LIMIT;
66
67 /* estimated error (usecs): */
68 static long time_esterror = NTP_PHASE_LIMIT;
69
70 /* frequency offset (scaled nsecs/secs): */
71 static s64 time_freq;
72
73 /* time at last adjustment (secs): */
74 static long time_reftime;
75
76 static long time_adjust;
77
78 /* constant (boot-param configurable) NTP tick adjustment (upscaled) */
79 static s64 ntp_tick_adj;
80
81 /* second value of the next pending leapsecond, or TIME64_MAX if no leap */
82 static time64_t ntp_next_leap_sec = TIME64_MAX;
83
84 #ifdef CONFIG_NTP_PPS
85
86 /*
87 * The following variables are used when a pulse-per-second (PPS) signal
88 * is available. They establish the engineering parameters of the clock
89 * discipline loop when controlled by the PPS signal.
90 */
91 #define PPS_VALID 10 /* PPS signal watchdog max (s) */
92 #define PPS_POPCORN 4 /* popcorn spike threshold (shift) */
93 #define PPS_INTMIN 2 /* min freq interval (s) (shift) */
94 #define PPS_INTMAX 8 /* max freq interval (s) (shift) */
95 #define PPS_INTCOUNT 4 /* number of consecutive good intervals to
96 increase pps_shift or consecutive bad
97 intervals to decrease it */
98 #define PPS_MAXWANDER 100000 /* max PPS freq wander (ns/s) */
99
100 static int pps_valid; /* signal watchdog counter */
101 static long pps_tf[3]; /* phase median filter */
102 static long pps_jitter; /* current jitter (ns) */
103 static struct timespec64 pps_fbase; /* beginning of the last freq interval */
104 static int pps_shift; /* current interval duration (s) (shift) */
105 static int pps_intcnt; /* interval counter */
106 static s64 pps_freq; /* frequency offset (scaled ns/s) */
107 static long pps_stabil; /* current stability (scaled ns/s) */
108
109 /*
110 * PPS signal quality monitors
111 */
112 static long pps_calcnt; /* calibration intervals */
113 static long pps_jitcnt; /* jitter limit exceeded */
114 static long pps_stbcnt; /* stability limit exceeded */
115 static long pps_errcnt; /* calibration errors */
116
117
118 /* PPS kernel consumer compensates the whole phase error immediately.
119 * Otherwise, reduce the offset by a fixed factor times the time constant.
120 */
ntp_offset_chunk(s64 offset)121 static inline s64 ntp_offset_chunk(s64 offset)
122 {
123 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
124 return offset;
125 else
126 return shift_right(offset, SHIFT_PLL + time_constant);
127 }
128
pps_reset_freq_interval(void)129 static inline void pps_reset_freq_interval(void)
130 {
131 /* the PPS calibration interval may end
132 surprisingly early */
133 pps_shift = PPS_INTMIN;
134 pps_intcnt = 0;
135 }
136
137 /**
138 * pps_clear - Clears the PPS state variables
139 */
pps_clear(void)140 static inline void pps_clear(void)
141 {
142 pps_reset_freq_interval();
143 pps_tf[0] = 0;
144 pps_tf[1] = 0;
145 pps_tf[2] = 0;
146 pps_fbase.tv_sec = pps_fbase.tv_nsec = 0;
147 pps_freq = 0;
148 }
149
150 /* Decrease pps_valid to indicate that another second has passed since
151 * the last PPS signal. When it reaches 0, indicate that PPS signal is
152 * missing.
153 */
pps_dec_valid(void)154 static inline void pps_dec_valid(void)
155 {
156 if (pps_valid > 0)
157 pps_valid--;
158 else {
159 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
160 STA_PPSWANDER | STA_PPSERROR);
161 pps_clear();
162 }
163 }
164
pps_set_freq(s64 freq)165 static inline void pps_set_freq(s64 freq)
166 {
167 pps_freq = freq;
168 }
169
is_error_status(int status)170 static inline int is_error_status(int status)
171 {
172 return (status & (STA_UNSYNC|STA_CLOCKERR))
173 /* PPS signal lost when either PPS time or
174 * PPS frequency synchronization requested
175 */
176 || ((status & (STA_PPSFREQ|STA_PPSTIME))
177 && !(status & STA_PPSSIGNAL))
178 /* PPS jitter exceeded when
179 * PPS time synchronization requested */
180 || ((status & (STA_PPSTIME|STA_PPSJITTER))
181 == (STA_PPSTIME|STA_PPSJITTER))
182 /* PPS wander exceeded or calibration error when
183 * PPS frequency synchronization requested
184 */
185 || ((status & STA_PPSFREQ)
186 && (status & (STA_PPSWANDER|STA_PPSERROR)));
187 }
188
pps_fill_timex(struct timex * txc)189 static inline void pps_fill_timex(struct timex *txc)
190 {
191 txc->ppsfreq = shift_right((pps_freq >> PPM_SCALE_INV_SHIFT) *
192 PPM_SCALE_INV, NTP_SCALE_SHIFT);
193 txc->jitter = pps_jitter;
194 if (!(time_status & STA_NANO))
195 txc->jitter /= NSEC_PER_USEC;
196 txc->shift = pps_shift;
197 txc->stabil = pps_stabil;
198 txc->jitcnt = pps_jitcnt;
199 txc->calcnt = pps_calcnt;
200 txc->errcnt = pps_errcnt;
201 txc->stbcnt = pps_stbcnt;
202 }
203
204 #else /* !CONFIG_NTP_PPS */
205
ntp_offset_chunk(s64 offset)206 static inline s64 ntp_offset_chunk(s64 offset)
207 {
208 return shift_right(offset, SHIFT_PLL + time_constant);
209 }
210
pps_reset_freq_interval(void)211 static inline void pps_reset_freq_interval(void) {}
pps_clear(void)212 static inline void pps_clear(void) {}
pps_dec_valid(void)213 static inline void pps_dec_valid(void) {}
pps_set_freq(s64 freq)214 static inline void pps_set_freq(s64 freq) {}
215
is_error_status(int status)216 static inline int is_error_status(int status)
217 {
218 return status & (STA_UNSYNC|STA_CLOCKERR);
219 }
220
pps_fill_timex(struct timex * txc)221 static inline void pps_fill_timex(struct timex *txc)
222 {
223 /* PPS is not implemented, so these are zero */
224 txc->ppsfreq = 0;
225 txc->jitter = 0;
226 txc->shift = 0;
227 txc->stabil = 0;
228 txc->jitcnt = 0;
229 txc->calcnt = 0;
230 txc->errcnt = 0;
231 txc->stbcnt = 0;
232 }
233
234 #endif /* CONFIG_NTP_PPS */
235
236
237 /**
238 * ntp_synced - Returns 1 if the NTP status is not UNSYNC
239 *
240 */
ntp_synced(void)241 static inline int ntp_synced(void)
242 {
243 return !(time_status & STA_UNSYNC);
244 }
245
246
247 /*
248 * NTP methods:
249 */
250
251 /*
252 * Update (tick_length, tick_length_base, tick_nsec), based
253 * on (tick_usec, ntp_tick_adj, time_freq):
254 */
ntp_update_frequency(void)255 static void ntp_update_frequency(void)
256 {
257 u64 second_length;
258 u64 new_base;
259
260 second_length = (u64)(tick_usec * NSEC_PER_USEC * USER_HZ)
261 << NTP_SCALE_SHIFT;
262
263 second_length += ntp_tick_adj;
264 second_length += time_freq;
265
266 tick_nsec = div_u64(second_length, HZ) >> NTP_SCALE_SHIFT;
267 new_base = div_u64(second_length, NTP_INTERVAL_FREQ);
268
269 /*
270 * Don't wait for the next second_overflow, apply
271 * the change to the tick length immediately:
272 */
273 tick_length += new_base - tick_length_base;
274 tick_length_base = new_base;
275 }
276
ntp_update_offset_fll(s64 offset64,long secs)277 static inline s64 ntp_update_offset_fll(s64 offset64, long secs)
278 {
279 time_status &= ~STA_MODE;
280
281 if (secs < MINSEC)
282 return 0;
283
284 if (!(time_status & STA_FLL) && (secs <= MAXSEC))
285 return 0;
286
287 time_status |= STA_MODE;
288
289 return div64_long(offset64 << (NTP_SCALE_SHIFT - SHIFT_FLL), secs);
290 }
291
ntp_update_offset(long offset)292 static void ntp_update_offset(long offset)
293 {
294 s64 freq_adj;
295 s64 offset64;
296 long secs;
297
298 if (!(time_status & STA_PLL))
299 return;
300
301 if (!(time_status & STA_NANO))
302 offset *= NSEC_PER_USEC;
303
304 /*
305 * Scale the phase adjustment and
306 * clamp to the operating range.
307 */
308 offset = min(offset, MAXPHASE);
309 offset = max(offset, -MAXPHASE);
310
311 /*
312 * Select how the frequency is to be controlled
313 * and in which mode (PLL or FLL).
314 */
315 secs = get_seconds() - time_reftime;
316 if (unlikely(time_status & STA_FREQHOLD))
317 secs = 0;
318
319 time_reftime = get_seconds();
320
321 offset64 = offset;
322 freq_adj = ntp_update_offset_fll(offset64, secs);
323
324 /*
325 * Clamp update interval to reduce PLL gain with low
326 * sampling rate (e.g. intermittent network connection)
327 * to avoid instability.
328 */
329 if (unlikely(secs > 1 << (SHIFT_PLL + 1 + time_constant)))
330 secs = 1 << (SHIFT_PLL + 1 + time_constant);
331
332 freq_adj += (offset64 * secs) <<
333 (NTP_SCALE_SHIFT - 2 * (SHIFT_PLL + 2 + time_constant));
334
335 freq_adj = min(freq_adj + time_freq, MAXFREQ_SCALED);
336
337 time_freq = max(freq_adj, -MAXFREQ_SCALED);
338
339 time_offset = div_s64(offset64 << NTP_SCALE_SHIFT, NTP_INTERVAL_FREQ);
340 }
341
342 /**
343 * ntp_clear - Clears the NTP state variables
344 */
ntp_clear(void)345 void ntp_clear(void)
346 {
347 time_adjust = 0; /* stop active adjtime() */
348 time_status |= STA_UNSYNC;
349 time_maxerror = NTP_PHASE_LIMIT;
350 time_esterror = NTP_PHASE_LIMIT;
351
352 ntp_update_frequency();
353
354 tick_length = tick_length_base;
355 time_offset = 0;
356
357 ntp_next_leap_sec = TIME64_MAX;
358 /* Clear PPS state variables */
359 pps_clear();
360 }
361
362
ntp_tick_length(void)363 u64 ntp_tick_length(void)
364 {
365 return tick_length;
366 }
367
368 /**
369 * ntp_get_next_leap - Returns the next leapsecond in CLOCK_REALTIME ktime_t
370 *
371 * Provides the time of the next leapsecond against CLOCK_REALTIME in
372 * a ktime_t format. Returns KTIME_MAX if no leapsecond is pending.
373 */
ntp_get_next_leap(void)374 ktime_t ntp_get_next_leap(void)
375 {
376 ktime_t ret;
377
378 if ((time_state == TIME_INS) && (time_status & STA_INS))
379 return ktime_set(ntp_next_leap_sec, 0);
380 ret.tv64 = KTIME_MAX;
381 return ret;
382 }
383
384 /*
385 * this routine handles the overflow of the microsecond field
386 *
387 * The tricky bits of code to handle the accurate clock support
388 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
389 * They were originally developed for SUN and DEC kernels.
390 * All the kudos should go to Dave for this stuff.
391 *
392 * Also handles leap second processing, and returns leap offset
393 */
second_overflow(unsigned long secs)394 int second_overflow(unsigned long secs)
395 {
396 s64 delta;
397 int leap = 0;
398
399 /*
400 * Leap second processing. If in leap-insert state at the end of the
401 * day, the system clock is set back one second; if in leap-delete
402 * state, the system clock is set ahead one second.
403 */
404 switch (time_state) {
405 case TIME_OK:
406 if (time_status & STA_INS) {
407 time_state = TIME_INS;
408 ntp_next_leap_sec = secs + SECS_PER_DAY -
409 (secs % SECS_PER_DAY);
410 } else if (time_status & STA_DEL) {
411 time_state = TIME_DEL;
412 ntp_next_leap_sec = secs + SECS_PER_DAY -
413 ((secs+1) % SECS_PER_DAY);
414 }
415 break;
416 case TIME_INS:
417 if (!(time_status & STA_INS)) {
418 ntp_next_leap_sec = TIME64_MAX;
419 time_state = TIME_OK;
420 } else if (secs % SECS_PER_DAY == 0) {
421 leap = -1;
422 time_state = TIME_OOP;
423 printk(KERN_NOTICE
424 "Clock: inserting leap second 23:59:60 UTC\n");
425 }
426 break;
427 case TIME_DEL:
428 if (!(time_status & STA_DEL)) {
429 ntp_next_leap_sec = TIME64_MAX;
430 time_state = TIME_OK;
431 } else if ((secs + 1) % SECS_PER_DAY == 0) {
432 leap = 1;
433 ntp_next_leap_sec = TIME64_MAX;
434 time_state = TIME_WAIT;
435 printk(KERN_NOTICE
436 "Clock: deleting leap second 23:59:59 UTC\n");
437 }
438 break;
439 case TIME_OOP:
440 ntp_next_leap_sec = TIME64_MAX;
441 time_state = TIME_WAIT;
442 break;
443 case TIME_WAIT:
444 if (!(time_status & (STA_INS | STA_DEL)))
445 time_state = TIME_OK;
446 break;
447 }
448
449
450 /* Bump the maxerror field */
451 time_maxerror += MAXFREQ / NSEC_PER_USEC;
452 if (time_maxerror > NTP_PHASE_LIMIT) {
453 time_maxerror = NTP_PHASE_LIMIT;
454 time_status |= STA_UNSYNC;
455 }
456
457 /* Compute the phase adjustment for the next second */
458 tick_length = tick_length_base;
459
460 delta = ntp_offset_chunk(time_offset);
461 time_offset -= delta;
462 tick_length += delta;
463
464 /* Check PPS signal */
465 pps_dec_valid();
466
467 if (!time_adjust)
468 goto out;
469
470 if (time_adjust > MAX_TICKADJ) {
471 time_adjust -= MAX_TICKADJ;
472 tick_length += MAX_TICKADJ_SCALED;
473 goto out;
474 }
475
476 if (time_adjust < -MAX_TICKADJ) {
477 time_adjust += MAX_TICKADJ;
478 tick_length -= MAX_TICKADJ_SCALED;
479 goto out;
480 }
481
482 tick_length += (s64)(time_adjust * NSEC_PER_USEC / NTP_INTERVAL_FREQ)
483 << NTP_SCALE_SHIFT;
484 time_adjust = 0;
485
486 out:
487 return leap;
488 }
489
490 #ifdef CONFIG_GENERIC_CMOS_UPDATE
update_persistent_clock(struct timespec now)491 int __weak update_persistent_clock(struct timespec now)
492 {
493 return -ENODEV;
494 }
495
update_persistent_clock64(struct timespec64 now64)496 int __weak update_persistent_clock64(struct timespec64 now64)
497 {
498 struct timespec now;
499
500 now = timespec64_to_timespec(now64);
501 return update_persistent_clock(now);
502 }
503 #endif
504
505 #if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
506 static void sync_cmos_clock(struct work_struct *work);
507
508 static DECLARE_DELAYED_WORK(sync_cmos_work, sync_cmos_clock);
509
sync_cmos_clock(struct work_struct * work)510 static void sync_cmos_clock(struct work_struct *work)
511 {
512 struct timespec64 now;
513 struct timespec64 next;
514 int fail = 1;
515
516 /*
517 * If we have an externally synchronized Linux clock, then update
518 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
519 * called as close as possible to 500 ms before the new second starts.
520 * This code is run on a timer. If the clock is set, that timer
521 * may not expire at the correct time. Thus, we adjust...
522 * We want the clock to be within a couple of ticks from the target.
523 */
524 if (!ntp_synced()) {
525 /*
526 * Not synced, exit, do not restart a timer (if one is
527 * running, let it run out).
528 */
529 return;
530 }
531
532 getnstimeofday64(&now);
533 if (abs(now.tv_nsec - (NSEC_PER_SEC / 2)) <= tick_nsec * 5) {
534 struct timespec64 adjust = now;
535
536 fail = -ENODEV;
537 if (persistent_clock_is_local)
538 adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
539 #ifdef CONFIG_GENERIC_CMOS_UPDATE
540 fail = update_persistent_clock64(adjust);
541 #endif
542
543 #ifdef CONFIG_RTC_SYSTOHC
544 if (fail == -ENODEV)
545 fail = rtc_set_ntp_time(adjust);
546 #endif
547 }
548
549 next.tv_nsec = (NSEC_PER_SEC / 2) - now.tv_nsec - (TICK_NSEC / 2);
550 if (next.tv_nsec <= 0)
551 next.tv_nsec += NSEC_PER_SEC;
552
553 if (!fail || fail == -ENODEV)
554 next.tv_sec = 659;
555 else
556 next.tv_sec = 0;
557
558 if (next.tv_nsec >= NSEC_PER_SEC) {
559 next.tv_sec++;
560 next.tv_nsec -= NSEC_PER_SEC;
561 }
562 queue_delayed_work(system_power_efficient_wq,
563 &sync_cmos_work, timespec64_to_jiffies(&next));
564 }
565
ntp_notify_cmos_timer(void)566 void ntp_notify_cmos_timer(void)
567 {
568 queue_delayed_work(system_power_efficient_wq, &sync_cmos_work, 0);
569 }
570
571 #else
ntp_notify_cmos_timer(void)572 void ntp_notify_cmos_timer(void) { }
573 #endif
574
575
576 /*
577 * Propagate a new txc->status value into the NTP state:
578 */
process_adj_status(struct timex * txc,struct timespec64 * ts)579 static inline void process_adj_status(struct timex *txc, struct timespec64 *ts)
580 {
581 if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
582 time_state = TIME_OK;
583 time_status = STA_UNSYNC;
584 ntp_next_leap_sec = TIME64_MAX;
585 /* restart PPS frequency calibration */
586 pps_reset_freq_interval();
587 }
588
589 /*
590 * If we turn on PLL adjustments then reset the
591 * reference time to current time.
592 */
593 if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
594 time_reftime = get_seconds();
595
596 /* only set allowed bits */
597 time_status &= STA_RONLY;
598 time_status |= txc->status & ~STA_RONLY;
599 }
600
601
process_adjtimex_modes(struct timex * txc,struct timespec64 * ts,s32 * time_tai)602 static inline void process_adjtimex_modes(struct timex *txc,
603 struct timespec64 *ts,
604 s32 *time_tai)
605 {
606 if (txc->modes & ADJ_STATUS)
607 process_adj_status(txc, ts);
608
609 if (txc->modes & ADJ_NANO)
610 time_status |= STA_NANO;
611
612 if (txc->modes & ADJ_MICRO)
613 time_status &= ~STA_NANO;
614
615 if (txc->modes & ADJ_FREQUENCY) {
616 time_freq = txc->freq * PPM_SCALE;
617 time_freq = min(time_freq, MAXFREQ_SCALED);
618 time_freq = max(time_freq, -MAXFREQ_SCALED);
619 /* update pps_freq */
620 pps_set_freq(time_freq);
621 }
622
623 if (txc->modes & ADJ_MAXERROR)
624 time_maxerror = txc->maxerror;
625
626 if (txc->modes & ADJ_ESTERROR)
627 time_esterror = txc->esterror;
628
629 if (txc->modes & ADJ_TIMECONST) {
630 time_constant = txc->constant;
631 if (!(time_status & STA_NANO))
632 time_constant += 4;
633 time_constant = min(time_constant, (long)MAXTC);
634 time_constant = max(time_constant, 0l);
635 }
636
637 if (txc->modes & ADJ_TAI &&
638 txc->constant >= 0 && txc->constant <= MAX_TAI_OFFSET)
639 *time_tai = txc->constant;
640
641 if (txc->modes & ADJ_OFFSET)
642 ntp_update_offset(txc->offset);
643
644 if (txc->modes & ADJ_TICK)
645 tick_usec = txc->tick;
646
647 if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
648 ntp_update_frequency();
649 }
650
651
652
653 /**
654 * ntp_validate_timex - Ensures the timex is ok for use in do_adjtimex
655 */
ntp_validate_timex(struct timex * txc)656 int ntp_validate_timex(struct timex *txc)
657 {
658 if (txc->modes & ADJ_ADJTIME) {
659 /* singleshot must not be used with any other mode bits */
660 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
661 return -EINVAL;
662 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
663 !capable(CAP_SYS_TIME))
664 return -EPERM;
665 } else {
666 /* In order to modify anything, you gotta be super-user! */
667 if (txc->modes && !capable(CAP_SYS_TIME))
668 return -EPERM;
669 /*
670 * if the quartz is off by more than 10% then
671 * something is VERY wrong!
672 */
673 if (txc->modes & ADJ_TICK &&
674 (txc->tick < 900000/USER_HZ ||
675 txc->tick > 1100000/USER_HZ))
676 return -EINVAL;
677 }
678
679 if (txc->modes & ADJ_SETOFFSET) {
680 /* In order to inject time, you gotta be super-user! */
681 if (!capable(CAP_SYS_TIME))
682 return -EPERM;
683
684 if (txc->modes & ADJ_NANO) {
685 struct timespec ts;
686
687 ts.tv_sec = txc->time.tv_sec;
688 ts.tv_nsec = txc->time.tv_usec;
689 if (!timespec_inject_offset_valid(&ts))
690 return -EINVAL;
691
692 } else {
693 if (!timeval_inject_offset_valid(&txc->time))
694 return -EINVAL;
695 }
696 }
697
698 /*
699 * Check for potential multiplication overflows that can
700 * only happen on 64-bit systems:
701 */
702 if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
703 if (LLONG_MIN / PPM_SCALE > txc->freq)
704 return -EINVAL;
705 if (LLONG_MAX / PPM_SCALE < txc->freq)
706 return -EINVAL;
707 }
708
709 return 0;
710 }
711
712
713 /*
714 * adjtimex mainly allows reading (and writing, if superuser) of
715 * kernel time-keeping variables. used by xntpd.
716 */
__do_adjtimex(struct timex * txc,struct timespec64 * ts,s32 * time_tai)717 int __do_adjtimex(struct timex *txc, struct timespec64 *ts, s32 *time_tai)
718 {
719 int result;
720
721 if (txc->modes & ADJ_ADJTIME) {
722 long save_adjust = time_adjust;
723
724 if (!(txc->modes & ADJ_OFFSET_READONLY)) {
725 /* adjtime() is independent from ntp_adjtime() */
726 time_adjust = txc->offset;
727 ntp_update_frequency();
728 }
729 txc->offset = save_adjust;
730 } else {
731
732 /* If there are input parameters, then process them: */
733 if (txc->modes)
734 process_adjtimex_modes(txc, ts, time_tai);
735
736 txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
737 NTP_SCALE_SHIFT);
738 if (!(time_status & STA_NANO))
739 txc->offset /= NSEC_PER_USEC;
740 }
741
742 result = time_state; /* mostly `TIME_OK' */
743 /* check for errors */
744 if (is_error_status(time_status))
745 result = TIME_ERROR;
746
747 txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
748 PPM_SCALE_INV, NTP_SCALE_SHIFT);
749 txc->maxerror = time_maxerror;
750 txc->esterror = time_esterror;
751 txc->status = time_status;
752 txc->constant = time_constant;
753 txc->precision = 1;
754 txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
755 txc->tick = tick_usec;
756 txc->tai = *time_tai;
757
758 /* fill PPS status fields */
759 pps_fill_timex(txc);
760
761 txc->time.tv_sec = (time_t)ts->tv_sec;
762 txc->time.tv_usec = ts->tv_nsec;
763 if (!(time_status & STA_NANO))
764 txc->time.tv_usec /= NSEC_PER_USEC;
765
766 /* Handle leapsec adjustments */
767 if (unlikely(ts->tv_sec >= ntp_next_leap_sec)) {
768 if ((time_state == TIME_INS) && (time_status & STA_INS)) {
769 result = TIME_OOP;
770 txc->tai++;
771 txc->time.tv_sec--;
772 }
773 if ((time_state == TIME_DEL) && (time_status & STA_DEL)) {
774 result = TIME_WAIT;
775 txc->tai--;
776 txc->time.tv_sec++;
777 }
778 if ((time_state == TIME_OOP) &&
779 (ts->tv_sec == ntp_next_leap_sec)) {
780 result = TIME_WAIT;
781 }
782 }
783
784 return result;
785 }
786
787 #ifdef CONFIG_NTP_PPS
788
789 /* actually struct pps_normtime is good old struct timespec, but it is
790 * semantically different (and it is the reason why it was invented):
791 * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
792 * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
793 struct pps_normtime {
794 s64 sec; /* seconds */
795 long nsec; /* nanoseconds */
796 };
797
798 /* normalize the timestamp so that nsec is in the
799 ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
pps_normalize_ts(struct timespec64 ts)800 static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts)
801 {
802 struct pps_normtime norm = {
803 .sec = ts.tv_sec,
804 .nsec = ts.tv_nsec
805 };
806
807 if (norm.nsec > (NSEC_PER_SEC >> 1)) {
808 norm.nsec -= NSEC_PER_SEC;
809 norm.sec++;
810 }
811
812 return norm;
813 }
814
815 /* get current phase correction and jitter */
pps_phase_filter_get(long * jitter)816 static inline long pps_phase_filter_get(long *jitter)
817 {
818 *jitter = pps_tf[0] - pps_tf[1];
819 if (*jitter < 0)
820 *jitter = -*jitter;
821
822 /* TODO: test various filters */
823 return pps_tf[0];
824 }
825
826 /* add the sample to the phase filter */
pps_phase_filter_add(long err)827 static inline void pps_phase_filter_add(long err)
828 {
829 pps_tf[2] = pps_tf[1];
830 pps_tf[1] = pps_tf[0];
831 pps_tf[0] = err;
832 }
833
834 /* decrease frequency calibration interval length.
835 * It is halved after four consecutive unstable intervals.
836 */
pps_dec_freq_interval(void)837 static inline void pps_dec_freq_interval(void)
838 {
839 if (--pps_intcnt <= -PPS_INTCOUNT) {
840 pps_intcnt = -PPS_INTCOUNT;
841 if (pps_shift > PPS_INTMIN) {
842 pps_shift--;
843 pps_intcnt = 0;
844 }
845 }
846 }
847
848 /* increase frequency calibration interval length.
849 * It is doubled after four consecutive stable intervals.
850 */
pps_inc_freq_interval(void)851 static inline void pps_inc_freq_interval(void)
852 {
853 if (++pps_intcnt >= PPS_INTCOUNT) {
854 pps_intcnt = PPS_INTCOUNT;
855 if (pps_shift < PPS_INTMAX) {
856 pps_shift++;
857 pps_intcnt = 0;
858 }
859 }
860 }
861
862 /* update clock frequency based on MONOTONIC_RAW clock PPS signal
863 * timestamps
864 *
865 * At the end of the calibration interval the difference between the
866 * first and last MONOTONIC_RAW clock timestamps divided by the length
867 * of the interval becomes the frequency update. If the interval was
868 * too long, the data are discarded.
869 * Returns the difference between old and new frequency values.
870 */
hardpps_update_freq(struct pps_normtime freq_norm)871 static long hardpps_update_freq(struct pps_normtime freq_norm)
872 {
873 long delta, delta_mod;
874 s64 ftemp;
875
876 /* check if the frequency interval was too long */
877 if (freq_norm.sec > (2 << pps_shift)) {
878 time_status |= STA_PPSERROR;
879 pps_errcnt++;
880 pps_dec_freq_interval();
881 printk_deferred(KERN_ERR
882 "hardpps: PPSERROR: interval too long - %lld s\n",
883 freq_norm.sec);
884 return 0;
885 }
886
887 /* here the raw frequency offset and wander (stability) is
888 * calculated. If the wander is less than the wander threshold
889 * the interval is increased; otherwise it is decreased.
890 */
891 ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
892 freq_norm.sec);
893 delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
894 pps_freq = ftemp;
895 if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
896 printk_deferred(KERN_WARNING
897 "hardpps: PPSWANDER: change=%ld\n", delta);
898 time_status |= STA_PPSWANDER;
899 pps_stbcnt++;
900 pps_dec_freq_interval();
901 } else { /* good sample */
902 pps_inc_freq_interval();
903 }
904
905 /* the stability metric is calculated as the average of recent
906 * frequency changes, but is used only for performance
907 * monitoring
908 */
909 delta_mod = delta;
910 if (delta_mod < 0)
911 delta_mod = -delta_mod;
912 pps_stabil += (div_s64(((s64)delta_mod) <<
913 (NTP_SCALE_SHIFT - SHIFT_USEC),
914 NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
915
916 /* if enabled, the system clock frequency is updated */
917 if ((time_status & STA_PPSFREQ) != 0 &&
918 (time_status & STA_FREQHOLD) == 0) {
919 time_freq = pps_freq;
920 ntp_update_frequency();
921 }
922
923 return delta;
924 }
925
926 /* correct REALTIME clock phase error against PPS signal */
hardpps_update_phase(long error)927 static void hardpps_update_phase(long error)
928 {
929 long correction = -error;
930 long jitter;
931
932 /* add the sample to the median filter */
933 pps_phase_filter_add(correction);
934 correction = pps_phase_filter_get(&jitter);
935
936 /* Nominal jitter is due to PPS signal noise. If it exceeds the
937 * threshold, the sample is discarded; otherwise, if so enabled,
938 * the time offset is updated.
939 */
940 if (jitter > (pps_jitter << PPS_POPCORN)) {
941 printk_deferred(KERN_WARNING
942 "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
943 jitter, (pps_jitter << PPS_POPCORN));
944 time_status |= STA_PPSJITTER;
945 pps_jitcnt++;
946 } else if (time_status & STA_PPSTIME) {
947 /* correct the time using the phase offset */
948 time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
949 NTP_INTERVAL_FREQ);
950 /* cancel running adjtime() */
951 time_adjust = 0;
952 }
953 /* update jitter */
954 pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
955 }
956
957 /*
958 * __hardpps() - discipline CPU clock oscillator to external PPS signal
959 *
960 * This routine is called at each PPS signal arrival in order to
961 * discipline the CPU clock oscillator to the PPS signal. It takes two
962 * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
963 * is used to correct clock phase error and the latter is used to
964 * correct the frequency.
965 *
966 * This code is based on David Mills's reference nanokernel
967 * implementation. It was mostly rewritten but keeps the same idea.
968 */
__hardpps(const struct timespec64 * phase_ts,const struct timespec64 * raw_ts)969 void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
970 {
971 struct pps_normtime pts_norm, freq_norm;
972
973 pts_norm = pps_normalize_ts(*phase_ts);
974
975 /* clear the error bits, they will be set again if needed */
976 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
977
978 /* indicate signal presence */
979 time_status |= STA_PPSSIGNAL;
980 pps_valid = PPS_VALID;
981
982 /* when called for the first time,
983 * just start the frequency interval */
984 if (unlikely(pps_fbase.tv_sec == 0)) {
985 pps_fbase = *raw_ts;
986 return;
987 }
988
989 /* ok, now we have a base for frequency calculation */
990 freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, pps_fbase));
991
992 /* check that the signal is in the range
993 * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
994 if ((freq_norm.sec == 0) ||
995 (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
996 (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
997 time_status |= STA_PPSJITTER;
998 /* restart the frequency calibration interval */
999 pps_fbase = *raw_ts;
1000 printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n");
1001 return;
1002 }
1003
1004 /* signal is ok */
1005
1006 /* check if the current frequency interval is finished */
1007 if (freq_norm.sec >= (1 << pps_shift)) {
1008 pps_calcnt++;
1009 /* restart the frequency calibration interval */
1010 pps_fbase = *raw_ts;
1011 hardpps_update_freq(freq_norm);
1012 }
1013
1014 hardpps_update_phase(pts_norm.nsec);
1015
1016 }
1017 #endif /* CONFIG_NTP_PPS */
1018
ntp_tick_adj_setup(char * str)1019 static int __init ntp_tick_adj_setup(char *str)
1020 {
1021 int rc = kstrtol(str, 0, (long *)&ntp_tick_adj);
1022
1023 if (rc)
1024 return rc;
1025 ntp_tick_adj <<= NTP_SCALE_SHIFT;
1026
1027 return 1;
1028 }
1029
1030 __setup("ntp_tick_adj=", ntp_tick_adj_setup);
1031
ntp_init(void)1032 void __init ntp_init(void)
1033 {
1034 ntp_clear();
1035 }
1036