ntp.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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 (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. #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(bool offset_set)
  558. {
  559. /*
  560. * If the time jumped (using ADJ_SETOFFSET) cancels sync timer,
  561. * which may have been running if the time was synchronized
  562. * prior to the ADJ_SETOFFSET call.
  563. */
  564. if (offset_set)
  565. hrtimer_cancel(&sync_hrtimer);
  566. /*
  567. * When the work is currently executed but has not yet the timer
  568. * rearmed this queues the work immediately again. No big issue,
  569. * just a pointless work scheduled.
  570. */
  571. if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
  572. queue_work(system_freezable_power_efficient_wq, &sync_work);
  573. }
  574. static void __init ntp_init_cmos_sync(void)
  575. {
  576. hrtimer_init(&sync_hrtimer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
  577. sync_hrtimer.function = sync_timer_callback;
  578. }
  579. #else /* CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */
  580. static inline void __init ntp_init_cmos_sync(void) { }
  581. #endif /* !CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */
  582. /*
  583. * Propagate a new txc->status value into the NTP state:
  584. */
  585. static inline void process_adj_status(const struct __kernel_timex *txc)
  586. {
  587. if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
  588. time_state = TIME_OK;
  589. time_status = STA_UNSYNC;
  590. ntp_next_leap_sec = TIME64_MAX;
  591. /* restart PPS frequency calibration */
  592. pps_reset_freq_interval();
  593. }
  594. /*
  595. * If we turn on PLL adjustments then reset the
  596. * reference time to current time.
  597. */
  598. if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
  599. time_reftime = __ktime_get_real_seconds();
  600. /* only set allowed bits */
  601. time_status &= STA_RONLY;
  602. time_status |= txc->status & ~STA_RONLY;
  603. }
  604. static inline void process_adjtimex_modes(const struct __kernel_timex *txc,
  605. s32 *time_tai)
  606. {
  607. if (txc->modes & ADJ_STATUS)
  608. process_adj_status(txc);
  609. if (txc->modes & ADJ_NANO)
  610. time_status |= STA_NANO;
  611. if (txc->modes & ADJ_MICRO)
  612. time_status &= ~STA_NANO;
  613. if (txc->modes & ADJ_FREQUENCY) {
  614. time_freq = txc->freq * PPM_SCALE;
  615. time_freq = min(time_freq, MAXFREQ_SCALED);
  616. time_freq = max(time_freq, -MAXFREQ_SCALED);
  617. /* update pps_freq */
  618. pps_set_freq(time_freq);
  619. }
  620. if (txc->modes & ADJ_MAXERROR)
  621. time_maxerror = clamp(txc->maxerror, 0, NTP_PHASE_LIMIT);
  622. if (txc->modes & ADJ_ESTERROR)
  623. time_esterror = clamp(txc->esterror, 0, NTP_PHASE_LIMIT);
  624. if (txc->modes & ADJ_TIMECONST) {
  625. time_constant = clamp(txc->constant, 0, MAXTC);
  626. if (!(time_status & STA_NANO))
  627. time_constant += 4;
  628. time_constant = clamp(time_constant, 0, MAXTC);
  629. }
  630. if (txc->modes & ADJ_TAI &&
  631. txc->constant >= 0 && txc->constant <= MAX_TAI_OFFSET)
  632. *time_tai = txc->constant;
  633. if (txc->modes & ADJ_OFFSET)
  634. ntp_update_offset(txc->offset);
  635. if (txc->modes & ADJ_TICK)
  636. tick_usec = txc->tick;
  637. if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
  638. ntp_update_frequency();
  639. }
  640. /*
  641. * adjtimex mainly allows reading (and writing, if superuser) of
  642. * kernel time-keeping variables. used by xntpd.
  643. */
  644. int __do_adjtimex(struct __kernel_timex *txc, const struct timespec64 *ts,
  645. s32 *time_tai, struct audit_ntp_data *ad)
  646. {
  647. int result;
  648. if (txc->modes & ADJ_ADJTIME) {
  649. long save_adjust = time_adjust;
  650. if (!(txc->modes & ADJ_OFFSET_READONLY)) {
  651. /* adjtime() is independent from ntp_adjtime() */
  652. time_adjust = txc->offset;
  653. ntp_update_frequency();
  654. audit_ntp_set_old(ad, AUDIT_NTP_ADJUST, save_adjust);
  655. audit_ntp_set_new(ad, AUDIT_NTP_ADJUST, time_adjust);
  656. }
  657. txc->offset = save_adjust;
  658. } else {
  659. /* If there are input parameters, then process them: */
  660. if (txc->modes) {
  661. audit_ntp_set_old(ad, AUDIT_NTP_OFFSET, time_offset);
  662. audit_ntp_set_old(ad, AUDIT_NTP_FREQ, time_freq);
  663. audit_ntp_set_old(ad, AUDIT_NTP_STATUS, time_status);
  664. audit_ntp_set_old(ad, AUDIT_NTP_TAI, *time_tai);
  665. audit_ntp_set_old(ad, AUDIT_NTP_TICK, tick_usec);
  666. process_adjtimex_modes(txc, time_tai);
  667. audit_ntp_set_new(ad, AUDIT_NTP_OFFSET, time_offset);
  668. audit_ntp_set_new(ad, AUDIT_NTP_FREQ, time_freq);
  669. audit_ntp_set_new(ad, AUDIT_NTP_STATUS, time_status);
  670. audit_ntp_set_new(ad, AUDIT_NTP_TAI, *time_tai);
  671. audit_ntp_set_new(ad, AUDIT_NTP_TICK, tick_usec);
  672. }
  673. txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
  674. NTP_SCALE_SHIFT);
  675. if (!(time_status & STA_NANO))
  676. txc->offset = div_s64(txc->offset, NSEC_PER_USEC);
  677. }
  678. result = time_state; /* mostly `TIME_OK' */
  679. /* check for errors */
  680. if (is_error_status(time_status))
  681. result = TIME_ERROR;
  682. txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
  683. PPM_SCALE_INV, NTP_SCALE_SHIFT);
  684. txc->maxerror = time_maxerror;
  685. txc->esterror = time_esterror;
  686. txc->status = time_status;
  687. txc->constant = time_constant;
  688. txc->precision = 1;
  689. txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
  690. txc->tick = tick_usec;
  691. txc->tai = *time_tai;
  692. /* fill PPS status fields */
  693. pps_fill_timex(txc);
  694. txc->time.tv_sec = ts->tv_sec;
  695. txc->time.tv_usec = ts->tv_nsec;
  696. if (!(time_status & STA_NANO))
  697. txc->time.tv_usec = ts->tv_nsec / NSEC_PER_USEC;
  698. /* Handle leapsec adjustments */
  699. if (unlikely(ts->tv_sec >= ntp_next_leap_sec)) {
  700. if ((time_state == TIME_INS) && (time_status & STA_INS)) {
  701. result = TIME_OOP;
  702. txc->tai++;
  703. txc->time.tv_sec--;
  704. }
  705. if ((time_state == TIME_DEL) && (time_status & STA_DEL)) {
  706. result = TIME_WAIT;
  707. txc->tai--;
  708. txc->time.tv_sec++;
  709. }
  710. if ((time_state == TIME_OOP) &&
  711. (ts->tv_sec == ntp_next_leap_sec)) {
  712. result = TIME_WAIT;
  713. }
  714. }
  715. return result;
  716. }
  717. #ifdef CONFIG_NTP_PPS
  718. /* actually struct pps_normtime is good old struct timespec, but it is
  719. * semantically different (and it is the reason why it was invented):
  720. * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
  721. * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
  722. struct pps_normtime {
  723. s64 sec; /* seconds */
  724. long nsec; /* nanoseconds */
  725. };
  726. /* normalize the timestamp so that nsec is in the
  727. ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
  728. static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts)
  729. {
  730. struct pps_normtime norm = {
  731. .sec = ts.tv_sec,
  732. .nsec = ts.tv_nsec
  733. };
  734. if (norm.nsec > (NSEC_PER_SEC >> 1)) {
  735. norm.nsec -= NSEC_PER_SEC;
  736. norm.sec++;
  737. }
  738. return norm;
  739. }
  740. /* get current phase correction and jitter */
  741. static inline long pps_phase_filter_get(long *jitter)
  742. {
  743. *jitter = pps_tf[0] - pps_tf[1];
  744. if (*jitter < 0)
  745. *jitter = -*jitter;
  746. /* TODO: test various filters */
  747. return pps_tf[0];
  748. }
  749. /* add the sample to the phase filter */
  750. static inline void pps_phase_filter_add(long err)
  751. {
  752. pps_tf[2] = pps_tf[1];
  753. pps_tf[1] = pps_tf[0];
  754. pps_tf[0] = err;
  755. }
  756. /* decrease frequency calibration interval length.
  757. * It is halved after four consecutive unstable intervals.
  758. */
  759. static inline void pps_dec_freq_interval(void)
  760. {
  761. if (--pps_intcnt <= -PPS_INTCOUNT) {
  762. pps_intcnt = -PPS_INTCOUNT;
  763. if (pps_shift > PPS_INTMIN) {
  764. pps_shift--;
  765. pps_intcnt = 0;
  766. }
  767. }
  768. }
  769. /* increase frequency calibration interval length.
  770. * It is doubled after four consecutive stable intervals.
  771. */
  772. static inline void pps_inc_freq_interval(void)
  773. {
  774. if (++pps_intcnt >= PPS_INTCOUNT) {
  775. pps_intcnt = PPS_INTCOUNT;
  776. if (pps_shift < PPS_INTMAX) {
  777. pps_shift++;
  778. pps_intcnt = 0;
  779. }
  780. }
  781. }
  782. /* update clock frequency based on MONOTONIC_RAW clock PPS signal
  783. * timestamps
  784. *
  785. * At the end of the calibration interval the difference between the
  786. * first and last MONOTONIC_RAW clock timestamps divided by the length
  787. * of the interval becomes the frequency update. If the interval was
  788. * too long, the data are discarded.
  789. * Returns the difference between old and new frequency values.
  790. */
  791. static long hardpps_update_freq(struct pps_normtime freq_norm)
  792. {
  793. long delta, delta_mod;
  794. s64 ftemp;
  795. /* check if the frequency interval was too long */
  796. if (freq_norm.sec > (2 << pps_shift)) {
  797. time_status |= STA_PPSERROR;
  798. pps_errcnt++;
  799. pps_dec_freq_interval();
  800. printk_deferred(KERN_ERR
  801. "hardpps: PPSERROR: interval too long - %lld s\n",
  802. freq_norm.sec);
  803. return 0;
  804. }
  805. /* here the raw frequency offset and wander (stability) is
  806. * calculated. If the wander is less than the wander threshold
  807. * the interval is increased; otherwise it is decreased.
  808. */
  809. ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
  810. freq_norm.sec);
  811. delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
  812. pps_freq = ftemp;
  813. if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
  814. printk_deferred(KERN_WARNING
  815. "hardpps: PPSWANDER: change=%ld\n", delta);
  816. time_status |= STA_PPSWANDER;
  817. pps_stbcnt++;
  818. pps_dec_freq_interval();
  819. } else { /* good sample */
  820. pps_inc_freq_interval();
  821. }
  822. /* the stability metric is calculated as the average of recent
  823. * frequency changes, but is used only for performance
  824. * monitoring
  825. */
  826. delta_mod = delta;
  827. if (delta_mod < 0)
  828. delta_mod = -delta_mod;
  829. pps_stabil += (div_s64(((s64)delta_mod) <<
  830. (NTP_SCALE_SHIFT - SHIFT_USEC),
  831. NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
  832. /* if enabled, the system clock frequency is updated */
  833. if ((time_status & STA_PPSFREQ) != 0 &&
  834. (time_status & STA_FREQHOLD) == 0) {
  835. time_freq = pps_freq;
  836. ntp_update_frequency();
  837. }
  838. return delta;
  839. }
  840. /* correct REALTIME clock phase error against PPS signal */
  841. static void hardpps_update_phase(long error)
  842. {
  843. long correction = -error;
  844. long jitter;
  845. /* add the sample to the median filter */
  846. pps_phase_filter_add(correction);
  847. correction = pps_phase_filter_get(&jitter);
  848. /* Nominal jitter is due to PPS signal noise. If it exceeds the
  849. * threshold, the sample is discarded; otherwise, if so enabled,
  850. * the time offset is updated.
  851. */
  852. if (jitter > (pps_jitter << PPS_POPCORN)) {
  853. printk_deferred(KERN_WARNING
  854. "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
  855. jitter, (pps_jitter << PPS_POPCORN));
  856. time_status |= STA_PPSJITTER;
  857. pps_jitcnt++;
  858. } else if (time_status & STA_PPSTIME) {
  859. /* correct the time using the phase offset */
  860. time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
  861. NTP_INTERVAL_FREQ);
  862. /* cancel running adjtime() */
  863. time_adjust = 0;
  864. }
  865. /* update jitter */
  866. pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
  867. }
  868. /*
  869. * __hardpps() - discipline CPU clock oscillator to external PPS signal
  870. *
  871. * This routine is called at each PPS signal arrival in order to
  872. * discipline the CPU clock oscillator to the PPS signal. It takes two
  873. * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
  874. * is used to correct clock phase error and the latter is used to
  875. * correct the frequency.
  876. *
  877. * This code is based on David Mills's reference nanokernel
  878. * implementation. It was mostly rewritten but keeps the same idea.
  879. */
  880. void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
  881. {
  882. struct pps_normtime pts_norm, freq_norm;
  883. pts_norm = pps_normalize_ts(*phase_ts);
  884. /* clear the error bits, they will be set again if needed */
  885. time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
  886. /* indicate signal presence */
  887. time_status |= STA_PPSSIGNAL;
  888. pps_valid = PPS_VALID;
  889. /* when called for the first time,
  890. * just start the frequency interval */
  891. if (unlikely(pps_fbase.tv_sec == 0)) {
  892. pps_fbase = *raw_ts;
  893. return;
  894. }
  895. /* ok, now we have a base for frequency calculation */
  896. freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, pps_fbase));
  897. /* check that the signal is in the range
  898. * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
  899. if ((freq_norm.sec == 0) ||
  900. (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
  901. (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
  902. time_status |= STA_PPSJITTER;
  903. /* restart the frequency calibration interval */
  904. pps_fbase = *raw_ts;
  905. printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n");
  906. return;
  907. }
  908. /* signal is ok */
  909. /* check if the current frequency interval is finished */
  910. if (freq_norm.sec >= (1 << pps_shift)) {
  911. pps_calcnt++;
  912. /* restart the frequency calibration interval */
  913. pps_fbase = *raw_ts;
  914. hardpps_update_freq(freq_norm);
  915. }
  916. hardpps_update_phase(pts_norm.nsec);
  917. }
  918. #endif /* CONFIG_NTP_PPS */
  919. static int __init ntp_tick_adj_setup(char *str)
  920. {
  921. int rc = kstrtos64(str, 0, &ntp_tick_adj);
  922. if (rc)
  923. return rc;
  924. ntp_tick_adj <<= NTP_SCALE_SHIFT;
  925. return 1;
  926. }
  927. __setup("ntp_tick_adj=", ntp_tick_adj_setup);
  928. void __init ntp_init(void)
  929. {
  930. ntp_clear();
  931. ntp_init_cmos_sync();
  932. }