ntp.c 25 KB

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