ntp.c 24 KB

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