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