ntp.c 25 KB

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