ntp.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. #ifdef CONFIG_GENERIC_CMOS_UPDATE
  413. int __weak update_persistent_clock(struct timespec now)
  414. {
  415. return -ENODEV;
  416. }
  417. int __weak update_persistent_clock64(struct timespec64 now64)
  418. {
  419. struct timespec now;
  420. now = timespec64_to_timespec(now64);
  421. return update_persistent_clock(now);
  422. }
  423. #endif
  424. #if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
  425. static void sync_cmos_clock(struct work_struct *work);
  426. static DECLARE_DELAYED_WORK(sync_cmos_work, sync_cmos_clock);
  427. static void sync_cmos_clock(struct work_struct *work)
  428. {
  429. struct timespec64 now;
  430. struct timespec64 next;
  431. int fail = 1;
  432. /*
  433. * If we have an externally synchronized Linux clock, then update
  434. * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
  435. * called as close as possible to 500 ms before the new second starts.
  436. * This code is run on a timer. If the clock is set, that timer
  437. * may not expire at the correct time. Thus, we adjust...
  438. * We want the clock to be within a couple of ticks from the target.
  439. */
  440. if (!ntp_synced()) {
  441. /*
  442. * Not synced, exit, do not restart a timer (if one is
  443. * running, let it run out).
  444. */
  445. return;
  446. }
  447. getnstimeofday64(&now);
  448. if (abs(now.tv_nsec - (NSEC_PER_SEC / 2)) <= tick_nsec * 5) {
  449. struct timespec64 adjust = now;
  450. fail = -ENODEV;
  451. if (persistent_clock_is_local)
  452. adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
  453. #ifdef CONFIG_GENERIC_CMOS_UPDATE
  454. fail = update_persistent_clock64(adjust);
  455. #endif
  456. #ifdef CONFIG_RTC_SYSTOHC
  457. if (fail == -ENODEV)
  458. fail = rtc_set_ntp_time(adjust);
  459. #endif
  460. }
  461. next.tv_nsec = (NSEC_PER_SEC / 2) - now.tv_nsec - (TICK_NSEC / 2);
  462. if (next.tv_nsec <= 0)
  463. next.tv_nsec += NSEC_PER_SEC;
  464. if (!fail || fail == -ENODEV)
  465. next.tv_sec = 659;
  466. else
  467. next.tv_sec = 0;
  468. if (next.tv_nsec >= NSEC_PER_SEC) {
  469. next.tv_sec++;
  470. next.tv_nsec -= NSEC_PER_SEC;
  471. }
  472. queue_delayed_work(system_power_efficient_wq,
  473. &sync_cmos_work, timespec64_to_jiffies(&next));
  474. }
  475. void ntp_notify_cmos_timer(void)
  476. {
  477. queue_delayed_work(system_power_efficient_wq, &sync_cmos_work, 0);
  478. }
  479. #else
  480. void ntp_notify_cmos_timer(void) { }
  481. #endif
  482. /*
  483. * Propagate a new txc->status value into the NTP state:
  484. */
  485. static inline void process_adj_status(struct timex *txc, struct timespec64 *ts)
  486. {
  487. if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
  488. time_state = TIME_OK;
  489. time_status = STA_UNSYNC;
  490. ntp_next_leap_sec = TIME64_MAX;
  491. /* restart PPS frequency calibration */
  492. pps_reset_freq_interval();
  493. }
  494. /*
  495. * If we turn on PLL adjustments then reset the
  496. * reference time to current time.
  497. */
  498. if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
  499. time_reftime = __ktime_get_real_seconds();
  500. /* only set allowed bits */
  501. time_status &= STA_RONLY;
  502. time_status |= txc->status & ~STA_RONLY;
  503. }
  504. static inline void process_adjtimex_modes(struct timex *txc,
  505. struct timespec64 *ts,
  506. s32 *time_tai)
  507. {
  508. if (txc->modes & ADJ_STATUS)
  509. process_adj_status(txc, ts);
  510. if (txc->modes & ADJ_NANO)
  511. time_status |= STA_NANO;
  512. if (txc->modes & ADJ_MICRO)
  513. time_status &= ~STA_NANO;
  514. if (txc->modes & ADJ_FREQUENCY) {
  515. time_freq = txc->freq * PPM_SCALE;
  516. time_freq = min(time_freq, MAXFREQ_SCALED);
  517. time_freq = max(time_freq, -MAXFREQ_SCALED);
  518. /* update pps_freq */
  519. pps_set_freq(time_freq);
  520. }
  521. if (txc->modes & ADJ_MAXERROR)
  522. time_maxerror = txc->maxerror;
  523. if (txc->modes & ADJ_ESTERROR)
  524. time_esterror = txc->esterror;
  525. if (txc->modes & ADJ_TIMECONST) {
  526. time_constant = txc->constant;
  527. if (!(time_status & STA_NANO))
  528. time_constant += 4;
  529. time_constant = min(time_constant, (long)MAXTC);
  530. time_constant = max(time_constant, 0l);
  531. }
  532. if (txc->modes & ADJ_TAI &&
  533. txc->constant >= 0 && txc->constant <= MAX_TAI_OFFSET)
  534. *time_tai = txc->constant;
  535. if (txc->modes & ADJ_OFFSET)
  536. ntp_update_offset(txc->offset);
  537. if (txc->modes & ADJ_TICK)
  538. tick_usec = txc->tick;
  539. if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
  540. ntp_update_frequency();
  541. }
  542. /**
  543. * ntp_validate_timex - Ensures the timex is ok for use in do_adjtimex
  544. */
  545. int ntp_validate_timex(struct timex *txc)
  546. {
  547. if (txc->modes & ADJ_ADJTIME) {
  548. /* singleshot must not be used with any other mode bits */
  549. if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
  550. return -EINVAL;
  551. if (!(txc->modes & ADJ_OFFSET_READONLY) &&
  552. !capable(CAP_SYS_TIME))
  553. return -EPERM;
  554. } else {
  555. /* In order to modify anything, you gotta be super-user! */
  556. if (txc->modes && !capable(CAP_SYS_TIME))
  557. return -EPERM;
  558. /*
  559. * if the quartz is off by more than 10% then
  560. * something is VERY wrong!
  561. */
  562. if (txc->modes & ADJ_TICK &&
  563. (txc->tick < 900000/USER_HZ ||
  564. txc->tick > 1100000/USER_HZ))
  565. return -EINVAL;
  566. }
  567. if (txc->modes & ADJ_SETOFFSET) {
  568. /* In order to inject time, you gotta be super-user! */
  569. if (!capable(CAP_SYS_TIME))
  570. return -EPERM;
  571. if (txc->modes & ADJ_NANO) {
  572. struct timespec ts;
  573. ts.tv_sec = txc->time.tv_sec;
  574. ts.tv_nsec = txc->time.tv_usec;
  575. if (!timespec_inject_offset_valid(&ts))
  576. return -EINVAL;
  577. } else {
  578. if (!timeval_inject_offset_valid(&txc->time))
  579. return -EINVAL;
  580. }
  581. }
  582. /*
  583. * Check for potential multiplication overflows that can
  584. * only happen on 64-bit systems:
  585. */
  586. if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
  587. if (LLONG_MIN / PPM_SCALE > txc->freq)
  588. return -EINVAL;
  589. if (LLONG_MAX / PPM_SCALE < txc->freq)
  590. return -EINVAL;
  591. }
  592. return 0;
  593. }
  594. /*
  595. * adjtimex mainly allows reading (and writing, if superuser) of
  596. * kernel time-keeping variables. used by xntpd.
  597. */
  598. int __do_adjtimex(struct timex *txc, struct timespec64 *ts, s32 *time_tai)
  599. {
  600. int result;
  601. if (txc->modes & ADJ_ADJTIME) {
  602. long save_adjust = time_adjust;
  603. if (!(txc->modes & ADJ_OFFSET_READONLY)) {
  604. /* adjtime() is independent from ntp_adjtime() */
  605. time_adjust = txc->offset;
  606. ntp_update_frequency();
  607. }
  608. txc->offset = save_adjust;
  609. } else {
  610. /* If there are input parameters, then process them: */
  611. if (txc->modes)
  612. process_adjtimex_modes(txc, ts, time_tai);
  613. txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
  614. NTP_SCALE_SHIFT);
  615. if (!(time_status & STA_NANO))
  616. txc->offset /= NSEC_PER_USEC;
  617. }
  618. result = time_state; /* mostly `TIME_OK' */
  619. /* check for errors */
  620. if (is_error_status(time_status))
  621. result = TIME_ERROR;
  622. txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
  623. PPM_SCALE_INV, NTP_SCALE_SHIFT);
  624. txc->maxerror = time_maxerror;
  625. txc->esterror = time_esterror;
  626. txc->status = time_status;
  627. txc->constant = time_constant;
  628. txc->precision = 1;
  629. txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
  630. txc->tick = tick_usec;
  631. txc->tai = *time_tai;
  632. /* fill PPS status fields */
  633. pps_fill_timex(txc);
  634. txc->time.tv_sec = (time_t)ts->tv_sec;
  635. txc->time.tv_usec = ts->tv_nsec;
  636. if (!(time_status & STA_NANO))
  637. txc->time.tv_usec /= NSEC_PER_USEC;
  638. /* Handle leapsec adjustments */
  639. if (unlikely(ts->tv_sec >= ntp_next_leap_sec)) {
  640. if ((time_state == TIME_INS) && (time_status & STA_INS)) {
  641. result = TIME_OOP;
  642. txc->tai++;
  643. txc->time.tv_sec--;
  644. }
  645. if ((time_state == TIME_DEL) && (time_status & STA_DEL)) {
  646. result = TIME_WAIT;
  647. txc->tai--;
  648. txc->time.tv_sec++;
  649. }
  650. if ((time_state == TIME_OOP) &&
  651. (ts->tv_sec == ntp_next_leap_sec)) {
  652. result = TIME_WAIT;
  653. }
  654. }
  655. return result;
  656. }
  657. #ifdef CONFIG_NTP_PPS
  658. /* actually struct pps_normtime is good old struct timespec, but it is
  659. * semantically different (and it is the reason why it was invented):
  660. * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
  661. * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
  662. struct pps_normtime {
  663. s64 sec; /* seconds */
  664. long nsec; /* nanoseconds */
  665. };
  666. /* normalize the timestamp so that nsec is in the
  667. ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
  668. static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts)
  669. {
  670. struct pps_normtime norm = {
  671. .sec = ts.tv_sec,
  672. .nsec = ts.tv_nsec
  673. };
  674. if (norm.nsec > (NSEC_PER_SEC >> 1)) {
  675. norm.nsec -= NSEC_PER_SEC;
  676. norm.sec++;
  677. }
  678. return norm;
  679. }
  680. /* get current phase correction and jitter */
  681. static inline long pps_phase_filter_get(long *jitter)
  682. {
  683. *jitter = pps_tf[0] - pps_tf[1];
  684. if (*jitter < 0)
  685. *jitter = -*jitter;
  686. /* TODO: test various filters */
  687. return pps_tf[0];
  688. }
  689. /* add the sample to the phase filter */
  690. static inline void pps_phase_filter_add(long err)
  691. {
  692. pps_tf[2] = pps_tf[1];
  693. pps_tf[1] = pps_tf[0];
  694. pps_tf[0] = err;
  695. }
  696. /* decrease frequency calibration interval length.
  697. * It is halved after four consecutive unstable intervals.
  698. */
  699. static inline void pps_dec_freq_interval(void)
  700. {
  701. if (--pps_intcnt <= -PPS_INTCOUNT) {
  702. pps_intcnt = -PPS_INTCOUNT;
  703. if (pps_shift > PPS_INTMIN) {
  704. pps_shift--;
  705. pps_intcnt = 0;
  706. }
  707. }
  708. }
  709. /* increase frequency calibration interval length.
  710. * It is doubled after four consecutive stable intervals.
  711. */
  712. static inline void pps_inc_freq_interval(void)
  713. {
  714. if (++pps_intcnt >= PPS_INTCOUNT) {
  715. pps_intcnt = PPS_INTCOUNT;
  716. if (pps_shift < PPS_INTMAX) {
  717. pps_shift++;
  718. pps_intcnt = 0;
  719. }
  720. }
  721. }
  722. /* update clock frequency based on MONOTONIC_RAW clock PPS signal
  723. * timestamps
  724. *
  725. * At the end of the calibration interval the difference between the
  726. * first and last MONOTONIC_RAW clock timestamps divided by the length
  727. * of the interval becomes the frequency update. If the interval was
  728. * too long, the data are discarded.
  729. * Returns the difference between old and new frequency values.
  730. */
  731. static long hardpps_update_freq(struct pps_normtime freq_norm)
  732. {
  733. long delta, delta_mod;
  734. s64 ftemp;
  735. /* check if the frequency interval was too long */
  736. if (freq_norm.sec > (2 << pps_shift)) {
  737. time_status |= STA_PPSERROR;
  738. pps_errcnt++;
  739. pps_dec_freq_interval();
  740. printk_deferred(KERN_ERR
  741. "hardpps: PPSERROR: interval too long - %lld s\n",
  742. freq_norm.sec);
  743. return 0;
  744. }
  745. /* here the raw frequency offset and wander (stability) is
  746. * calculated. If the wander is less than the wander threshold
  747. * the interval is increased; otherwise it is decreased.
  748. */
  749. ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
  750. freq_norm.sec);
  751. delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
  752. pps_freq = ftemp;
  753. if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
  754. printk_deferred(KERN_WARNING
  755. "hardpps: PPSWANDER: change=%ld\n", delta);
  756. time_status |= STA_PPSWANDER;
  757. pps_stbcnt++;
  758. pps_dec_freq_interval();
  759. } else { /* good sample */
  760. pps_inc_freq_interval();
  761. }
  762. /* the stability metric is calculated as the average of recent
  763. * frequency changes, but is used only for performance
  764. * monitoring
  765. */
  766. delta_mod = delta;
  767. if (delta_mod < 0)
  768. delta_mod = -delta_mod;
  769. pps_stabil += (div_s64(((s64)delta_mod) <<
  770. (NTP_SCALE_SHIFT - SHIFT_USEC),
  771. NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
  772. /* if enabled, the system clock frequency is updated */
  773. if ((time_status & STA_PPSFREQ) != 0 &&
  774. (time_status & STA_FREQHOLD) == 0) {
  775. time_freq = pps_freq;
  776. ntp_update_frequency();
  777. }
  778. return delta;
  779. }
  780. /* correct REALTIME clock phase error against PPS signal */
  781. static void hardpps_update_phase(long error)
  782. {
  783. long correction = -error;
  784. long jitter;
  785. /* add the sample to the median filter */
  786. pps_phase_filter_add(correction);
  787. correction = pps_phase_filter_get(&jitter);
  788. /* Nominal jitter is due to PPS signal noise. If it exceeds the
  789. * threshold, the sample is discarded; otherwise, if so enabled,
  790. * the time offset is updated.
  791. */
  792. if (jitter > (pps_jitter << PPS_POPCORN)) {
  793. printk_deferred(KERN_WARNING
  794. "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
  795. jitter, (pps_jitter << PPS_POPCORN));
  796. time_status |= STA_PPSJITTER;
  797. pps_jitcnt++;
  798. } else if (time_status & STA_PPSTIME) {
  799. /* correct the time using the phase offset */
  800. time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
  801. NTP_INTERVAL_FREQ);
  802. /* cancel running adjtime() */
  803. time_adjust = 0;
  804. }
  805. /* update jitter */
  806. pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
  807. }
  808. /*
  809. * __hardpps() - discipline CPU clock oscillator to external PPS signal
  810. *
  811. * This routine is called at each PPS signal arrival in order to
  812. * discipline the CPU clock oscillator to the PPS signal. It takes two
  813. * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
  814. * is used to correct clock phase error and the latter is used to
  815. * correct the frequency.
  816. *
  817. * This code is based on David Mills's reference nanokernel
  818. * implementation. It was mostly rewritten but keeps the same idea.
  819. */
  820. void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
  821. {
  822. struct pps_normtime pts_norm, freq_norm;
  823. pts_norm = pps_normalize_ts(*phase_ts);
  824. /* clear the error bits, they will be set again if needed */
  825. time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
  826. /* indicate signal presence */
  827. time_status |= STA_PPSSIGNAL;
  828. pps_valid = PPS_VALID;
  829. /* when called for the first time,
  830. * just start the frequency interval */
  831. if (unlikely(pps_fbase.tv_sec == 0)) {
  832. pps_fbase = *raw_ts;
  833. return;
  834. }
  835. /* ok, now we have a base for frequency calculation */
  836. freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, pps_fbase));
  837. /* check that the signal is in the range
  838. * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
  839. if ((freq_norm.sec == 0) ||
  840. (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
  841. (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
  842. time_status |= STA_PPSJITTER;
  843. /* restart the frequency calibration interval */
  844. pps_fbase = *raw_ts;
  845. printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n");
  846. return;
  847. }
  848. /* signal is ok */
  849. /* check if the current frequency interval is finished */
  850. if (freq_norm.sec >= (1 << pps_shift)) {
  851. pps_calcnt++;
  852. /* restart the frequency calibration interval */
  853. pps_fbase = *raw_ts;
  854. hardpps_update_freq(freq_norm);
  855. }
  856. hardpps_update_phase(pts_norm.nsec);
  857. }
  858. #endif /* CONFIG_NTP_PPS */
  859. static int __init ntp_tick_adj_setup(char *str)
  860. {
  861. int rc = kstrtol(str, 0, (long *)&ntp_tick_adj);
  862. if (rc)
  863. return rc;
  864. ntp_tick_adj <<= NTP_SCALE_SHIFT;
  865. return 1;
  866. }
  867. __setup("ntp_tick_adj=", ntp_tick_adj_setup);
  868. void __init ntp_init(void)
  869. {
  870. ntp_clear();
  871. }