ntp.c 24 KB

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