ntp.c 25 KB

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