These changes are the raw update to linux-4.4.6-rt14. Kernel sources
[kvmfornfv.git] / kernel / kernel / time / ntp.c
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/kthread.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
21 #include "ntp_internal.h"
22
23 /*
24  * NTP timekeeping variables:
25  *
26  * Note: All of the NTP state is protected by the timekeeping locks.
27  */
28
29
30 /* USER_HZ period (usecs): */
31 unsigned long                   tick_usec = TICK_USEC;
32
33 /* SHIFTED_HZ period (nsecs): */
34 unsigned long                   tick_nsec;
35
36 static u64                      tick_length;
37 static u64                      tick_length_base;
38
39 #define SECS_PER_DAY            86400
40 #define MAX_TICKADJ             500LL           /* usecs */
41 #define MAX_TICKADJ_SCALED \
42         (((MAX_TICKADJ * NSEC_PER_USEC) << NTP_SCALE_SHIFT) / NTP_INTERVAL_FREQ)
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  */
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
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  */
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  */
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
165 static inline void pps_set_freq(s64 freq)
166 {
167         pps_freq = freq;
168 }
169
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
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
206 static inline s64 ntp_offset_chunk(s64 offset)
207 {
208         return shift_right(offset, SHIFT_PLL + time_constant);
209 }
210
211 static inline void pps_reset_freq_interval(void) {}
212 static inline void pps_clear(void) {}
213 static inline void pps_dec_valid(void) {}
214 static inline void pps_set_freq(s64 freq) {}
215
216 static inline int is_error_status(int status)
217 {
218         return status & (STA_UNSYNC|STA_CLOCKERR);
219 }
220
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  */
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  */
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
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
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  */
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
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  */
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  */
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
491 int __weak update_persistent_clock(struct timespec now)
492 {
493         return -ENODEV;
494 }
495
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
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
566 #ifdef CONFIG_PREEMPT_RT_FULL
567 /*
568  * RT can not call schedule_delayed_work from real interrupt context.
569  * Need to make a thread to do the real work.
570  */
571 static struct task_struct *cmos_delay_thread;
572 static bool do_cmos_delay;
573
574 static int run_cmos_delay(void *ignore)
575 {
576         while (!kthread_should_stop()) {
577                 set_current_state(TASK_INTERRUPTIBLE);
578                 if (do_cmos_delay) {
579                         do_cmos_delay = false;
580                         queue_delayed_work(system_power_efficient_wq,
581                                            &sync_cmos_work, 0);
582                 }
583                 schedule();
584         }
585         __set_current_state(TASK_RUNNING);
586         return 0;
587 }
588
589 void ntp_notify_cmos_timer(void)
590 {
591         do_cmos_delay = true;
592         /* Make visible before waking up process */
593         smp_wmb();
594         wake_up_process(cmos_delay_thread);
595 }
596
597 static __init int create_cmos_delay_thread(void)
598 {
599         cmos_delay_thread = kthread_run(run_cmos_delay, NULL, "kcmosdelayd");
600         BUG_ON(!cmos_delay_thread);
601         return 0;
602 }
603 early_initcall(create_cmos_delay_thread);
604
605 #else
606
607 void ntp_notify_cmos_timer(void)
608 {
609         queue_delayed_work(system_power_efficient_wq, &sync_cmos_work, 0);
610 }
611 #endif /* CONFIG_PREEMPT_RT_FULL */
612
613 #else
614 void ntp_notify_cmos_timer(void) { }
615 #endif
616
617
618 /*
619  * Propagate a new txc->status value into the NTP state:
620  */
621 static inline void process_adj_status(struct timex *txc, struct timespec64 *ts)
622 {
623         if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
624                 time_state = TIME_OK;
625                 time_status = STA_UNSYNC;
626                 ntp_next_leap_sec = TIME64_MAX;
627                 /* restart PPS frequency calibration */
628                 pps_reset_freq_interval();
629         }
630
631         /*
632          * If we turn on PLL adjustments then reset the
633          * reference time to current time.
634          */
635         if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
636                 time_reftime = get_seconds();
637
638         /* only set allowed bits */
639         time_status &= STA_RONLY;
640         time_status |= txc->status & ~STA_RONLY;
641 }
642
643
644 static inline void process_adjtimex_modes(struct timex *txc,
645                                                 struct timespec64 *ts,
646                                                 s32 *time_tai)
647 {
648         if (txc->modes & ADJ_STATUS)
649                 process_adj_status(txc, ts);
650
651         if (txc->modes & ADJ_NANO)
652                 time_status |= STA_NANO;
653
654         if (txc->modes & ADJ_MICRO)
655                 time_status &= ~STA_NANO;
656
657         if (txc->modes & ADJ_FREQUENCY) {
658                 time_freq = txc->freq * PPM_SCALE;
659                 time_freq = min(time_freq, MAXFREQ_SCALED);
660                 time_freq = max(time_freq, -MAXFREQ_SCALED);
661                 /* update pps_freq */
662                 pps_set_freq(time_freq);
663         }
664
665         if (txc->modes & ADJ_MAXERROR)
666                 time_maxerror = txc->maxerror;
667
668         if (txc->modes & ADJ_ESTERROR)
669                 time_esterror = txc->esterror;
670
671         if (txc->modes & ADJ_TIMECONST) {
672                 time_constant = txc->constant;
673                 if (!(time_status & STA_NANO))
674                         time_constant += 4;
675                 time_constant = min(time_constant, (long)MAXTC);
676                 time_constant = max(time_constant, 0l);
677         }
678
679         if (txc->modes & ADJ_TAI && txc->constant > 0)
680                 *time_tai = txc->constant;
681
682         if (txc->modes & ADJ_OFFSET)
683                 ntp_update_offset(txc->offset);
684
685         if (txc->modes & ADJ_TICK)
686                 tick_usec = txc->tick;
687
688         if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
689                 ntp_update_frequency();
690 }
691
692
693
694 /**
695  * ntp_validate_timex - Ensures the timex is ok for use in do_adjtimex
696  */
697 int ntp_validate_timex(struct timex *txc)
698 {
699         if (txc->modes & ADJ_ADJTIME) {
700                 /* singleshot must not be used with any other mode bits */
701                 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
702                         return -EINVAL;
703                 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
704                     !capable(CAP_SYS_TIME))
705                         return -EPERM;
706         } else {
707                 /* In order to modify anything, you gotta be super-user! */
708                  if (txc->modes && !capable(CAP_SYS_TIME))
709                         return -EPERM;
710                 /*
711                  * if the quartz is off by more than 10% then
712                  * something is VERY wrong!
713                  */
714                 if (txc->modes & ADJ_TICK &&
715                     (txc->tick <  900000/USER_HZ ||
716                      txc->tick > 1100000/USER_HZ))
717                         return -EINVAL;
718         }
719
720         if ((txc->modes & ADJ_SETOFFSET) && (!capable(CAP_SYS_TIME)))
721                 return -EPERM;
722
723         /*
724          * Check for potential multiplication overflows that can
725          * only happen on 64-bit systems:
726          */
727         if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
728                 if (LLONG_MIN / PPM_SCALE > txc->freq)
729                         return -EINVAL;
730                 if (LLONG_MAX / PPM_SCALE < txc->freq)
731                         return -EINVAL;
732         }
733
734         return 0;
735 }
736
737
738 /*
739  * adjtimex mainly allows reading (and writing, if superuser) of
740  * kernel time-keeping variables. used by xntpd.
741  */
742 int __do_adjtimex(struct timex *txc, struct timespec64 *ts, s32 *time_tai)
743 {
744         int result;
745
746         if (txc->modes & ADJ_ADJTIME) {
747                 long save_adjust = time_adjust;
748
749                 if (!(txc->modes & ADJ_OFFSET_READONLY)) {
750                         /* adjtime() is independent from ntp_adjtime() */
751                         time_adjust = txc->offset;
752                         ntp_update_frequency();
753                 }
754                 txc->offset = save_adjust;
755         } else {
756
757                 /* If there are input parameters, then process them: */
758                 if (txc->modes)
759                         process_adjtimex_modes(txc, ts, time_tai);
760
761                 txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
762                                   NTP_SCALE_SHIFT);
763                 if (!(time_status & STA_NANO))
764                         txc->offset /= NSEC_PER_USEC;
765         }
766
767         result = time_state;    /* mostly `TIME_OK' */
768         /* check for errors */
769         if (is_error_status(time_status))
770                 result = TIME_ERROR;
771
772         txc->freq          = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
773                                          PPM_SCALE_INV, NTP_SCALE_SHIFT);
774         txc->maxerror      = time_maxerror;
775         txc->esterror      = time_esterror;
776         txc->status        = time_status;
777         txc->constant      = time_constant;
778         txc->precision     = 1;
779         txc->tolerance     = MAXFREQ_SCALED / PPM_SCALE;
780         txc->tick          = tick_usec;
781         txc->tai           = *time_tai;
782
783         /* fill PPS status fields */
784         pps_fill_timex(txc);
785
786         txc->time.tv_sec = (time_t)ts->tv_sec;
787         txc->time.tv_usec = ts->tv_nsec;
788         if (!(time_status & STA_NANO))
789                 txc->time.tv_usec /= NSEC_PER_USEC;
790
791         /* Handle leapsec adjustments */
792         if (unlikely(ts->tv_sec >= ntp_next_leap_sec)) {
793                 if ((time_state == TIME_INS) && (time_status & STA_INS)) {
794                         result = TIME_OOP;
795                         txc->tai++;
796                         txc->time.tv_sec--;
797                 }
798                 if ((time_state == TIME_DEL) && (time_status & STA_DEL)) {
799                         result = TIME_WAIT;
800                         txc->tai--;
801                         txc->time.tv_sec++;
802                 }
803                 if ((time_state == TIME_OOP) &&
804                                         (ts->tv_sec == ntp_next_leap_sec)) {
805                         result = TIME_WAIT;
806                 }
807         }
808
809         return result;
810 }
811
812 #ifdef  CONFIG_NTP_PPS
813
814 /* actually struct pps_normtime is good old struct timespec, but it is
815  * semantically different (and it is the reason why it was invented):
816  * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
817  * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
818 struct pps_normtime {
819         s64             sec;    /* seconds */
820         long            nsec;   /* nanoseconds */
821 };
822
823 /* normalize the timestamp so that nsec is in the
824    ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
825 static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts)
826 {
827         struct pps_normtime norm = {
828                 .sec = ts.tv_sec,
829                 .nsec = ts.tv_nsec
830         };
831
832         if (norm.nsec > (NSEC_PER_SEC >> 1)) {
833                 norm.nsec -= NSEC_PER_SEC;
834                 norm.sec++;
835         }
836
837         return norm;
838 }
839
840 /* get current phase correction and jitter */
841 static inline long pps_phase_filter_get(long *jitter)
842 {
843         *jitter = pps_tf[0] - pps_tf[1];
844         if (*jitter < 0)
845                 *jitter = -*jitter;
846
847         /* TODO: test various filters */
848         return pps_tf[0];
849 }
850
851 /* add the sample to the phase filter */
852 static inline void pps_phase_filter_add(long err)
853 {
854         pps_tf[2] = pps_tf[1];
855         pps_tf[1] = pps_tf[0];
856         pps_tf[0] = err;
857 }
858
859 /* decrease frequency calibration interval length.
860  * It is halved after four consecutive unstable intervals.
861  */
862 static inline void pps_dec_freq_interval(void)
863 {
864         if (--pps_intcnt <= -PPS_INTCOUNT) {
865                 pps_intcnt = -PPS_INTCOUNT;
866                 if (pps_shift > PPS_INTMIN) {
867                         pps_shift--;
868                         pps_intcnt = 0;
869                 }
870         }
871 }
872
873 /* increase frequency calibration interval length.
874  * It is doubled after four consecutive stable intervals.
875  */
876 static inline void pps_inc_freq_interval(void)
877 {
878         if (++pps_intcnt >= PPS_INTCOUNT) {
879                 pps_intcnt = PPS_INTCOUNT;
880                 if (pps_shift < PPS_INTMAX) {
881                         pps_shift++;
882                         pps_intcnt = 0;
883                 }
884         }
885 }
886
887 /* update clock frequency based on MONOTONIC_RAW clock PPS signal
888  * timestamps
889  *
890  * At the end of the calibration interval the difference between the
891  * first and last MONOTONIC_RAW clock timestamps divided by the length
892  * of the interval becomes the frequency update. If the interval was
893  * too long, the data are discarded.
894  * Returns the difference between old and new frequency values.
895  */
896 static long hardpps_update_freq(struct pps_normtime freq_norm)
897 {
898         long delta, delta_mod;
899         s64 ftemp;
900
901         /* check if the frequency interval was too long */
902         if (freq_norm.sec > (2 << pps_shift)) {
903                 time_status |= STA_PPSERROR;
904                 pps_errcnt++;
905                 pps_dec_freq_interval();
906                 printk_deferred(KERN_ERR
907                         "hardpps: PPSERROR: interval too long - %lld s\n",
908                         freq_norm.sec);
909                 return 0;
910         }
911
912         /* here the raw frequency offset and wander (stability) is
913          * calculated. If the wander is less than the wander threshold
914          * the interval is increased; otherwise it is decreased.
915          */
916         ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
917                         freq_norm.sec);
918         delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
919         pps_freq = ftemp;
920         if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
921                 printk_deferred(KERN_WARNING
922                                 "hardpps: PPSWANDER: change=%ld\n", delta);
923                 time_status |= STA_PPSWANDER;
924                 pps_stbcnt++;
925                 pps_dec_freq_interval();
926         } else {        /* good sample */
927                 pps_inc_freq_interval();
928         }
929
930         /* the stability metric is calculated as the average of recent
931          * frequency changes, but is used only for performance
932          * monitoring
933          */
934         delta_mod = delta;
935         if (delta_mod < 0)
936                 delta_mod = -delta_mod;
937         pps_stabil += (div_s64(((s64)delta_mod) <<
938                                 (NTP_SCALE_SHIFT - SHIFT_USEC),
939                                 NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
940
941         /* if enabled, the system clock frequency is updated */
942         if ((time_status & STA_PPSFREQ) != 0 &&
943             (time_status & STA_FREQHOLD) == 0) {
944                 time_freq = pps_freq;
945                 ntp_update_frequency();
946         }
947
948         return delta;
949 }
950
951 /* correct REALTIME clock phase error against PPS signal */
952 static void hardpps_update_phase(long error)
953 {
954         long correction = -error;
955         long jitter;
956
957         /* add the sample to the median filter */
958         pps_phase_filter_add(correction);
959         correction = pps_phase_filter_get(&jitter);
960
961         /* Nominal jitter is due to PPS signal noise. If it exceeds the
962          * threshold, the sample is discarded; otherwise, if so enabled,
963          * the time offset is updated.
964          */
965         if (jitter > (pps_jitter << PPS_POPCORN)) {
966                 printk_deferred(KERN_WARNING
967                                 "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
968                                 jitter, (pps_jitter << PPS_POPCORN));
969                 time_status |= STA_PPSJITTER;
970                 pps_jitcnt++;
971         } else if (time_status & STA_PPSTIME) {
972                 /* correct the time using the phase offset */
973                 time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
974                                 NTP_INTERVAL_FREQ);
975                 /* cancel running adjtime() */
976                 time_adjust = 0;
977         }
978         /* update jitter */
979         pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
980 }
981
982 /*
983  * __hardpps() - discipline CPU clock oscillator to external PPS signal
984  *
985  * This routine is called at each PPS signal arrival in order to
986  * discipline the CPU clock oscillator to the PPS signal. It takes two
987  * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
988  * is used to correct clock phase error and the latter is used to
989  * correct the frequency.
990  *
991  * This code is based on David Mills's reference nanokernel
992  * implementation. It was mostly rewritten but keeps the same idea.
993  */
994 void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
995 {
996         struct pps_normtime pts_norm, freq_norm;
997
998         pts_norm = pps_normalize_ts(*phase_ts);
999
1000         /* clear the error bits, they will be set again if needed */
1001         time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1002
1003         /* indicate signal presence */
1004         time_status |= STA_PPSSIGNAL;
1005         pps_valid = PPS_VALID;
1006
1007         /* when called for the first time,
1008          * just start the frequency interval */
1009         if (unlikely(pps_fbase.tv_sec == 0)) {
1010                 pps_fbase = *raw_ts;
1011                 return;
1012         }
1013
1014         /* ok, now we have a base for frequency calculation */
1015         freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, pps_fbase));
1016
1017         /* check that the signal is in the range
1018          * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
1019         if ((freq_norm.sec == 0) ||
1020                         (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
1021                         (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
1022                 time_status |= STA_PPSJITTER;
1023                 /* restart the frequency calibration interval */
1024                 pps_fbase = *raw_ts;
1025                 printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n");
1026                 return;
1027         }
1028
1029         /* signal is ok */
1030
1031         /* check if the current frequency interval is finished */
1032         if (freq_norm.sec >= (1 << pps_shift)) {
1033                 pps_calcnt++;
1034                 /* restart the frequency calibration interval */
1035                 pps_fbase = *raw_ts;
1036                 hardpps_update_freq(freq_norm);
1037         }
1038
1039         hardpps_update_phase(pts_norm.nsec);
1040
1041 }
1042 #endif  /* CONFIG_NTP_PPS */
1043
1044 static int __init ntp_tick_adj_setup(char *str)
1045 {
1046         int rc = kstrtol(str, 0, (long *)&ntp_tick_adj);
1047
1048         if (rc)
1049                 return rc;
1050         ntp_tick_adj <<= NTP_SCALE_SHIFT;
1051
1052         return 1;
1053 }
1054
1055 __setup("ntp_tick_adj=", ntp_tick_adj_setup);
1056
1057 void __init ntp_init(void)
1058 {
1059         ntp_clear();
1060 }