ntp.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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/audit.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 __kernel_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 = pps_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 __kernel_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 ([email protected]) 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. #if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
  413. static void sync_hw_clock(struct work_struct *work);
  414. static DECLARE_WORK(sync_work, sync_hw_clock);
  415. static struct hrtimer sync_hrtimer;
  416. #define SYNC_PERIOD_NS (11ULL * 60 * NSEC_PER_SEC)
  417. static enum hrtimer_restart sync_timer_callback(struct hrtimer *timer)
  418. {
  419. queue_work(system_freezable_power_efficient_wq, &sync_work);
  420. return HRTIMER_NORESTART;
  421. }
  422. static void sched_sync_hw_clock(unsigned long offset_nsec, bool retry)
  423. {
  424. ktime_t exp = ktime_set(ktime_get_real_seconds(), 0);
  425. if (retry)
  426. exp = ktime_add_ns(exp, 2ULL * NSEC_PER_SEC - offset_nsec);
  427. else
  428. exp = ktime_add_ns(exp, SYNC_PERIOD_NS - offset_nsec);
  429. hrtimer_start(&sync_hrtimer, exp, HRTIMER_MODE_ABS);
  430. }
  431. /*
  432. * Check whether @now is correct versus the required time to update the RTC
  433. * and calculate the value which needs to be written to the RTC so that the
  434. * next seconds increment of the RTC after the write is aligned with the next
  435. * seconds increment of clock REALTIME.
  436. *
  437. * tsched t1 write(t2.tv_sec - 1sec)) t2 RTC increments seconds
  438. *
  439. * t2.tv_nsec == 0
  440. * tsched = t2 - set_offset_nsec
  441. * newval = t2 - NSEC_PER_SEC
  442. *
  443. * ==> neval = tsched + set_offset_nsec - NSEC_PER_SEC
  444. *
  445. * As the execution of this code is not guaranteed to happen exactly at
  446. * tsched this allows it to happen within a fuzzy region:
  447. *
  448. * abs(now - tsched) < FUZZ
  449. *
  450. * If @now is not inside the allowed window the function returns false.
  451. */
  452. static inline bool rtc_tv_nsec_ok(unsigned long set_offset_nsec,
  453. struct timespec64 *to_set,
  454. const struct timespec64 *now)
  455. {
  456. /* Allowed error in tv_nsec, arbitrarily set to 5 jiffies in ns. */
  457. const unsigned long TIME_SET_NSEC_FUZZ = TICK_NSEC * 5;
  458. struct timespec64 delay = {.tv_sec = -1,
  459. .tv_nsec = set_offset_nsec};
  460. *to_set = timespec64_add(*now, delay);
  461. if (to_set->tv_nsec < TIME_SET_NSEC_FUZZ) {
  462. to_set->tv_nsec = 0;
  463. return true;
  464. }
  465. if (to_set->tv_nsec > NSEC_PER_SEC - TIME_SET_NSEC_FUZZ) {
  466. to_set->tv_sec++;
  467. to_set->tv_nsec = 0;
  468. return true;
  469. }
  470. return false;
  471. }
  472. #ifdef CONFIG_GENERIC_CMOS_UPDATE
  473. int __weak update_persistent_clock64(struct timespec64 now64)
  474. {
  475. return -ENODEV;
  476. }
  477. #else
  478. static inline int update_persistent_clock64(struct timespec64 now64)
  479. {
  480. return -ENODEV;
  481. }
  482. #endif
  483. #ifdef CONFIG_RTC_SYSTOHC
  484. /* Save NTP synchronized time to the RTC */
  485. static int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
  486. {
  487. struct rtc_device *rtc;
  488. struct rtc_time tm;
  489. int err = -ENODEV;
  490. rtc = rtc_class_open(CONFIG_RTC_SYSTOHC_DEVICE);
  491. if (!rtc)
  492. return -ENODEV;
  493. if (!rtc->ops || !rtc->ops->set_time)
  494. goto out_close;
  495. /* First call might not have the correct offset */
  496. if (*offset_nsec == rtc->set_offset_nsec) {
  497. rtc_time64_to_tm(to_set->tv_sec, &tm);
  498. err = rtc_set_time(rtc, &tm);
  499. } else {
  500. /* Store the update offset and let the caller try again */
  501. *offset_nsec = rtc->set_offset_nsec;
  502. err = -EAGAIN;
  503. }
  504. out_close:
  505. rtc_class_close(rtc);
  506. return err;
  507. }
  508. #else
  509. static inline int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
  510. {
  511. return -ENODEV;
  512. }
  513. #endif
  514. /*
  515. * If we have an externally synchronized Linux clock, then update RTC clock
  516. * accordingly every ~11 minutes. Generally RTCs can only store second
  517. * precision, but many RTCs will adjust the phase of their second tick to
  518. * match the moment of update. This infrastructure arranges to call to the RTC
  519. * set at the correct moment to phase synchronize the RTC second tick over
  520. * with the kernel clock.
  521. */
  522. static void sync_hw_clock(struct work_struct *work)
  523. {
  524. /*
  525. * The default synchronization offset is 500ms for the deprecated
  526. * update_persistent_clock64() under the assumption that it uses
  527. * the infamous CMOS clock (MC146818).
  528. */
  529. static unsigned long offset_nsec = NSEC_PER_SEC / 2;
  530. struct timespec64 now, to_set;
  531. int res = -EAGAIN;
  532. /*
  533. * Don't update if STA_UNSYNC is set and if ntp_notify_cmos_timer()
  534. * managed to schedule the work between the timer firing and the
  535. * work being able to rearm the timer. Wait for the timer to expire.
  536. */
  537. if (!ntp_synced() || hrtimer_is_queued(&sync_hrtimer))
  538. return;
  539. ktime_get_real_ts64(&now);
  540. /* If @now is not in the allowed window, try again */
  541. if (!rtc_tv_nsec_ok(offset_nsec, &to_set, &now))
  542. goto rearm;
  543. /* Take timezone adjusted RTCs into account */
  544. if (persistent_clock_is_local)
  545. to_set.tv_sec -= (sys_tz.tz_minuteswest * 60);
  546. /* Try the legacy RTC first. */
  547. res = update_persistent_clock64(to_set);
  548. if (res != -ENODEV)
  549. goto rearm;
  550. /* Try the RTC class */
  551. res = update_rtc(&to_set, &offset_nsec);
  552. if (res == -ENODEV)
  553. return;
  554. rearm:
  555. sched_sync_hw_clock(offset_nsec, res != 0);
  556. }
  557. void ntp_notify_cmos_timer(void)
  558. {
  559. /*
  560. * When the work is currently executed but has not yet the timer
  561. * rearmed this queues the work immediately again. No big issue,
  562. * just a pointless work scheduled.
  563. */
  564. if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
  565. queue_work(system_freezable_power_efficient_wq, &sync_work);
  566. }
  567. static void __init ntp_init_cmos_sync(void)
  568. {
  569. hrtimer_init(&sync_hrtimer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
  570. sync_hrtimer.function = sync_timer_callback;
  571. }
  572. #else /* CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */
  573. static inline void __init ntp_init_cmos_sync(void) { }
  574. #endif /* !CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */
  575. /*
  576. * Propagate a new txc->status value into the NTP state:
  577. */
  578. static inline void process_adj_status(const struct __kernel_timex *txc)
  579. {
  580. if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
  581. time_state = TIME_OK;
  582. time_status = STA_UNSYNC;
  583. ntp_next_leap_sec = TIME64_MAX;
  584. /* restart PPS frequency calibration */
  585. pps_reset_freq_interval();
  586. }
  587. /*
  588. * If we turn on PLL adjustments then reset the
  589. * reference time to current time.
  590. */
  591. if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
  592. time_reftime = __ktime_get_real_seconds();
  593. /* only set allowed bits */
  594. time_status &= STA_RONLY;
  595. time_status |= txc->status & ~STA_RONLY;
  596. }
  597. static inline void process_adjtimex_modes(const struct __kernel_timex *txc,
  598. s32 *time_tai)
  599. {
  600. if (txc->modes & ADJ_STATUS)
  601. process_adj_status(txc);
  602. if (txc->modes & ADJ_NANO)
  603. time_status |= STA_NANO;
  604. if (txc->modes & ADJ_MICRO)
  605. time_status &= ~STA_NANO;
  606. if (txc->modes & ADJ_FREQUENCY) {
  607. time_freq = txc->freq * PPM_SCALE;
  608. time_freq = min(time_freq, MAXFREQ_SCALED);
  609. time_freq = max(time_freq, -MAXFREQ_SCALED);
  610. /* update pps_freq */
  611. pps_set_freq(time_freq);
  612. }
  613. if (txc->modes & ADJ_MAXERROR)
  614. time_maxerror = txc->maxerror;
  615. if (txc->modes & ADJ_ESTERROR)
  616. time_esterror = txc->esterror;
  617. if (txc->modes & ADJ_TIMECONST) {
  618. time_constant = txc->constant;
  619. if (!(time_status & STA_NANO))
  620. time_constant += 4;
  621. time_constant = min(time_constant, (long)MAXTC);
  622. time_constant = max(time_constant, 0l);
  623. }
  624. if (txc->modes & ADJ_TAI &&
  625. txc->constant >= 0 && txc->constant <= MAX_TAI_OFFSET)
  626. *time_tai = txc->constant;
  627. if (txc->modes & ADJ_OFFSET)
  628. ntp_update_offset(txc->offset);
  629. if (txc->modes & ADJ_TICK)
  630. tick_usec = txc->tick;
  631. if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
  632. ntp_update_frequency();
  633. }
  634. /*
  635. * adjtimex mainly allows reading (and writing, if superuser) of
  636. * kernel time-keeping variables. used by xntpd.
  637. */
  638. int __do_adjtimex(struct __kernel_timex *txc, const struct timespec64 *ts,
  639. s32 *time_tai, struct audit_ntp_data *ad)
  640. {
  641. int result;
  642. if (txc->modes & ADJ_ADJTIME) {
  643. long save_adjust = time_adjust;
  644. if (!(txc->modes & ADJ_OFFSET_READONLY)) {
  645. /* adjtime() is independent from ntp_adjtime() */
  646. time_adjust = txc->offset;
  647. ntp_update_frequency();
  648. audit_ntp_set_old(ad, AUDIT_NTP_ADJUST, save_adjust);
  649. audit_ntp_set_new(ad, AUDIT_NTP_ADJUST, time_adjust);
  650. }
  651. txc->offset = save_adjust;
  652. } else {
  653. /* If there are input parameters, then process them: */
  654. if (txc->modes) {
  655. audit_ntp_set_old(ad, AUDIT_NTP_OFFSET, time_offset);
  656. audit_ntp_set_old(ad, AUDIT_NTP_FREQ, time_freq);
  657. audit_ntp_set_old(ad, AUDIT_NTP_STATUS, time_status);
  658. audit_ntp_set_old(ad, AUDIT_NTP_TAI, *time_tai);
  659. audit_ntp_set_old(ad, AUDIT_NTP_TICK, tick_usec);
  660. process_adjtimex_modes(txc, time_tai);
  661. audit_ntp_set_new(ad, AUDIT_NTP_OFFSET, time_offset);
  662. audit_ntp_set_new(ad, AUDIT_NTP_FREQ, time_freq);
  663. audit_ntp_set_new(ad, AUDIT_NTP_STATUS, time_status);
  664. audit_ntp_set_new(ad, AUDIT_NTP_TAI, *time_tai);
  665. audit_ntp_set_new(ad, AUDIT_NTP_TICK, tick_usec);
  666. }
  667. txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
  668. NTP_SCALE_SHIFT);
  669. if (!(time_status & STA_NANO))
  670. txc->offset = (u32)txc->offset / NSEC_PER_USEC;
  671. }
  672. result = time_state; /* mostly `TIME_OK' */
  673. /* check for errors */
  674. if (is_error_status(time_status))
  675. result = TIME_ERROR;
  676. txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
  677. PPM_SCALE_INV, NTP_SCALE_SHIFT);
  678. txc->maxerror = time_maxerror;
  679. txc->esterror = time_esterror;
  680. txc->status = time_status;
  681. txc->constant = time_constant;
  682. txc->precision = 1;
  683. txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
  684. txc->tick = tick_usec;
  685. txc->tai = *time_tai;
  686. /* fill PPS status fields */
  687. pps_fill_timex(txc);
  688. txc->time.tv_sec = ts->tv_sec;
  689. txc->time.tv_usec = ts->tv_nsec;
  690. if (!(time_status & STA_NANO))
  691. txc->time.tv_usec = ts->tv_nsec / NSEC_PER_USEC;
  692. /* Handle leapsec adjustments */
  693. if (unlikely(ts->tv_sec >= ntp_next_leap_sec)) {
  694. if ((time_state == TIME_INS) && (time_status & STA_INS)) {
  695. result = TIME_OOP;
  696. txc->tai++;
  697. txc->time.tv_sec--;
  698. }
  699. if ((time_state == TIME_DEL) && (time_status & STA_DEL)) {
  700. result = TIME_WAIT;
  701. txc->tai--;
  702. txc->time.tv_sec++;
  703. }
  704. if ((time_state == TIME_OOP) &&
  705. (ts->tv_sec == ntp_next_leap_sec)) {
  706. result = TIME_WAIT;
  707. }
  708. }
  709. return result;
  710. }
  711. #ifdef CONFIG_NTP_PPS
  712. /* actually struct pps_normtime is good old struct timespec, but it is
  713. * semantically different (and it is the reason why it was invented):
  714. * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
  715. * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
  716. struct pps_normtime {
  717. s64 sec; /* seconds */
  718. long nsec; /* nanoseconds */
  719. };
  720. /* normalize the timestamp so that nsec is in the
  721. ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
  722. static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts)
  723. {
  724. struct pps_normtime norm = {
  725. .sec = ts.tv_sec,
  726. .nsec = ts.tv_nsec
  727. };
  728. if (norm.nsec > (NSEC_PER_SEC >> 1)) {
  729. norm.nsec -= NSEC_PER_SEC;
  730. norm.sec++;
  731. }
  732. return norm;
  733. }
  734. /* get current phase correction and jitter */
  735. static inline long pps_phase_filter_get(long *jitter)
  736. {
  737. *jitter = pps_tf[0] - pps_tf[1];
  738. if (*jitter < 0)
  739. *jitter = -*jitter;
  740. /* TODO: test various filters */
  741. return pps_tf[0];
  742. }
  743. /* add the sample to the phase filter */
  744. static inline void pps_phase_filter_add(long err)
  745. {
  746. pps_tf[2] = pps_tf[1];
  747. pps_tf[1] = pps_tf[0];
  748. pps_tf[0] = err;
  749. }
  750. /* decrease frequency calibration interval length.
  751. * It is halved after four consecutive unstable intervals.
  752. */
  753. static inline void pps_dec_freq_interval(void)
  754. {
  755. if (--pps_intcnt <= -PPS_INTCOUNT) {
  756. pps_intcnt = -PPS_INTCOUNT;
  757. if (pps_shift > PPS_INTMIN) {
  758. pps_shift--;
  759. pps_intcnt = 0;
  760. }
  761. }
  762. }
  763. /* increase frequency calibration interval length.
  764. * It is doubled after four consecutive stable intervals.
  765. */
  766. static inline void pps_inc_freq_interval(void)
  767. {
  768. if (++pps_intcnt >= PPS_INTCOUNT) {
  769. pps_intcnt = PPS_INTCOUNT;
  770. if (pps_shift < PPS_INTMAX) {
  771. pps_shift++;
  772. pps_intcnt = 0;
  773. }
  774. }
  775. }
  776. /* update clock frequency based on MONOTONIC_RAW clock PPS signal
  777. * timestamps
  778. *
  779. * At the end of the calibration interval the difference between the
  780. * first and last MONOTONIC_RAW clock timestamps divided by the length
  781. * of the interval becomes the frequency update. If the interval was
  782. * too long, the data are discarded.
  783. * Returns the difference between old and new frequency values.
  784. */
  785. static long hardpps_update_freq(struct pps_normtime freq_norm)
  786. {
  787. long delta, delta_mod;
  788. s64 ftemp;
  789. /* check if the frequency interval was too long */
  790. if (freq_norm.sec > (2 << pps_shift)) {
  791. time_status |= STA_PPSERROR;
  792. pps_errcnt++;
  793. pps_dec_freq_interval();
  794. printk_deferred(KERN_ERR
  795. "hardpps: PPSERROR: interval too long - %lld s\n",
  796. freq_norm.sec);
  797. return 0;
  798. }
  799. /* here the raw frequency offset and wander (stability) is
  800. * calculated. If the wander is less than the wander threshold
  801. * the interval is increased; otherwise it is decreased.
  802. */
  803. ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
  804. freq_norm.sec);
  805. delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
  806. pps_freq = ftemp;
  807. if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
  808. printk_deferred(KERN_WARNING
  809. "hardpps: PPSWANDER: change=%ld\n", delta);
  810. time_status |= STA_PPSWANDER;
  811. pps_stbcnt++;
  812. pps_dec_freq_interval();
  813. } else { /* good sample */
  814. pps_inc_freq_interval();
  815. }
  816. /* the stability metric is calculated as the average of recent
  817. * frequency changes, but is used only for performance
  818. * monitoring
  819. */
  820. delta_mod = delta;
  821. if (delta_mod < 0)
  822. delta_mod = -delta_mod;
  823. pps_stabil += (div_s64(((s64)delta_mod) <<
  824. (NTP_SCALE_SHIFT - SHIFT_USEC),
  825. NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
  826. /* if enabled, the system clock frequency is updated */
  827. if ((time_status & STA_PPSFREQ) != 0 &&
  828. (time_status & STA_FREQHOLD) == 0) {
  829. time_freq = pps_freq;
  830. ntp_update_frequency();
  831. }
  832. return delta;
  833. }
  834. /* correct REALTIME clock phase error against PPS signal */
  835. static void hardpps_update_phase(long error)
  836. {
  837. long correction = -error;
  838. long jitter;
  839. /* add the sample to the median filter */
  840. pps_phase_filter_add(correction);
  841. correction = pps_phase_filter_get(&jitter);
  842. /* Nominal jitter is due to PPS signal noise. If it exceeds the
  843. * threshold, the sample is discarded; otherwise, if so enabled,
  844. * the time offset is updated.
  845. */
  846. if (jitter > (pps_jitter << PPS_POPCORN)) {
  847. printk_deferred(KERN_WARNING
  848. "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
  849. jitter, (pps_jitter << PPS_POPCORN));
  850. time_status |= STA_PPSJITTER;
  851. pps_jitcnt++;
  852. } else if (time_status & STA_PPSTIME) {
  853. /* correct the time using the phase offset */
  854. time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
  855. NTP_INTERVAL_FREQ);
  856. /* cancel running adjtime() */
  857. time_adjust = 0;
  858. }
  859. /* update jitter */
  860. pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
  861. }
  862. /*
  863. * __hardpps() - discipline CPU clock oscillator to external PPS signal
  864. *
  865. * This routine is called at each PPS signal arrival in order to
  866. * discipline the CPU clock oscillator to the PPS signal. It takes two
  867. * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
  868. * is used to correct clock phase error and the latter is used to
  869. * correct the frequency.
  870. *
  871. * This code is based on David Mills's reference nanokernel
  872. * implementation. It was mostly rewritten but keeps the same idea.
  873. */
  874. void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
  875. {
  876. struct pps_normtime pts_norm, freq_norm;
  877. pts_norm = pps_normalize_ts(*phase_ts);
  878. /* clear the error bits, they will be set again if needed */
  879. time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
  880. /* indicate signal presence */
  881. time_status |= STA_PPSSIGNAL;
  882. pps_valid = PPS_VALID;
  883. /* when called for the first time,
  884. * just start the frequency interval */
  885. if (unlikely(pps_fbase.tv_sec == 0)) {
  886. pps_fbase = *raw_ts;
  887. return;
  888. }
  889. /* ok, now we have a base for frequency calculation */
  890. freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, pps_fbase));
  891. /* check that the signal is in the range
  892. * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
  893. if ((freq_norm.sec == 0) ||
  894. (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
  895. (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
  896. time_status |= STA_PPSJITTER;
  897. /* restart the frequency calibration interval */
  898. pps_fbase = *raw_ts;
  899. printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n");
  900. return;
  901. }
  902. /* signal is ok */
  903. /* check if the current frequency interval is finished */
  904. if (freq_norm.sec >= (1 << pps_shift)) {
  905. pps_calcnt++;
  906. /* restart the frequency calibration interval */
  907. pps_fbase = *raw_ts;
  908. hardpps_update_freq(freq_norm);
  909. }
  910. hardpps_update_phase(pts_norm.nsec);
  911. }
  912. #endif /* CONFIG_NTP_PPS */
  913. static int __init ntp_tick_adj_setup(char *str)
  914. {
  915. int rc = kstrtos64(str, 0, &ntp_tick_adj);
  916. if (rc)
  917. return rc;
  918. ntp_tick_adj <<= NTP_SCALE_SHIFT;
  919. return 1;
  920. }
  921. __setup("ntp_tick_adj=", ntp_tick_adj_setup);
  922. void __init ntp_init(void)
  923. {
  924. ntp_clear();
  925. ntp_init_cmos_sync();
  926. }