ntp.c 26 KB

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