ntp.c 26 KB

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