ntp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. /* 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. raw_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. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  296. }
  297. u64 ntp_tick_length(void)
  298. {
  299. unsigned long flags;
  300. s64 ret;
  301. raw_spin_lock_irqsave(&ntp_lock, flags);
  302. ret = tick_length;
  303. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  304. return ret;
  305. }
  306. /*
  307. * this routine handles the overflow of the microsecond field
  308. *
  309. * The tricky bits of code to handle the accurate clock support
  310. * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
  311. * They were originally developed for SUN and DEC kernels.
  312. * All the kudos should go to Dave for this stuff.
  313. *
  314. * Also handles leap second processing, and returns leap offset
  315. */
  316. int second_overflow(unsigned long secs)
  317. {
  318. s64 delta;
  319. int leap = 0;
  320. unsigned long flags;
  321. raw_spin_lock_irqsave(&ntp_lock, flags);
  322. /*
  323. * Leap second processing. If in leap-insert state at the end of the
  324. * day, the system clock is set back one second; if in leap-delete
  325. * state, the system clock is set ahead one second.
  326. */
  327. switch (time_state) {
  328. case TIME_OK:
  329. if (time_status & STA_INS)
  330. time_state = TIME_INS;
  331. else if (time_status & STA_DEL)
  332. time_state = TIME_DEL;
  333. break;
  334. case TIME_INS:
  335. if (!(time_status & STA_INS))
  336. time_state = TIME_OK;
  337. else if (secs % 86400 == 0) {
  338. leap = -1;
  339. time_state = TIME_OOP;
  340. time_tai++;
  341. printk(KERN_NOTICE
  342. "Clock: inserting leap second 23:59:60 UTC\n");
  343. }
  344. break;
  345. case TIME_DEL:
  346. if (!(time_status & STA_DEL))
  347. time_state = TIME_OK;
  348. else if ((secs + 1) % 86400 == 0) {
  349. leap = 1;
  350. time_tai--;
  351. time_state = TIME_WAIT;
  352. printk(KERN_NOTICE
  353. "Clock: deleting leap second 23:59:59 UTC\n");
  354. }
  355. break;
  356. case TIME_OOP:
  357. time_state = TIME_WAIT;
  358. break;
  359. case TIME_WAIT:
  360. if (!(time_status & (STA_INS | STA_DEL)))
  361. time_state = TIME_OK;
  362. break;
  363. }
  364. /* Bump the maxerror field */
  365. time_maxerror += MAXFREQ / NSEC_PER_USEC;
  366. if (time_maxerror > NTP_PHASE_LIMIT) {
  367. time_maxerror = NTP_PHASE_LIMIT;
  368. time_status |= STA_UNSYNC;
  369. }
  370. /* Compute the phase adjustment for the next second */
  371. tick_length = tick_length_base;
  372. delta = ntp_offset_chunk(time_offset);
  373. time_offset -= delta;
  374. tick_length += delta;
  375. /* Check PPS signal */
  376. pps_dec_valid();
  377. if (!time_adjust)
  378. goto out;
  379. if (time_adjust > MAX_TICKADJ) {
  380. time_adjust -= MAX_TICKADJ;
  381. tick_length += MAX_TICKADJ_SCALED;
  382. goto out;
  383. }
  384. if (time_adjust < -MAX_TICKADJ) {
  385. time_adjust += MAX_TICKADJ;
  386. tick_length -= MAX_TICKADJ_SCALED;
  387. goto out;
  388. }
  389. tick_length += (s64)(time_adjust * NSEC_PER_USEC / NTP_INTERVAL_FREQ)
  390. << NTP_SCALE_SHIFT;
  391. time_adjust = 0;
  392. out:
  393. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  394. return leap;
  395. }
  396. #if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
  397. static void sync_cmos_clock(struct work_struct *work);
  398. static DECLARE_DELAYED_WORK(sync_cmos_work, sync_cmos_clock);
  399. static void sync_cmos_clock(struct work_struct *work)
  400. {
  401. struct timespec now, next;
  402. int fail = 1;
  403. /*
  404. * If we have an externally synchronized Linux clock, then update
  405. * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
  406. * called as close as possible to 500 ms before the new second starts.
  407. * This code is run on a timer. If the clock is set, that timer
  408. * may not expire at the correct time. Thus, we adjust...
  409. */
  410. if (!ntp_synced()) {
  411. /*
  412. * Not synced, exit, do not restart a timer (if one is
  413. * running, let it run out).
  414. */
  415. return;
  416. }
  417. getnstimeofday(&now);
  418. if (abs(now.tv_nsec - (NSEC_PER_SEC / 2)) <= tick_nsec / 2) {
  419. struct timespec adjust = now;
  420. fail = -ENODEV;
  421. if (persistent_clock_is_local)
  422. adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
  423. #ifdef CONFIG_GENERIC_CMOS_UPDATE
  424. fail = update_persistent_clock(adjust);
  425. #endif
  426. #ifdef CONFIG_RTC_SYSTOHC
  427. if (fail == -ENODEV)
  428. fail = rtc_set_ntp_time(adjust);
  429. #endif
  430. }
  431. next.tv_nsec = (NSEC_PER_SEC / 2) - now.tv_nsec - (TICK_NSEC / 2);
  432. if (next.tv_nsec <= 0)
  433. next.tv_nsec += NSEC_PER_SEC;
  434. if (!fail || fail == -ENODEV)
  435. next.tv_sec = 659;
  436. else
  437. next.tv_sec = 0;
  438. if (next.tv_nsec >= NSEC_PER_SEC) {
  439. next.tv_sec++;
  440. next.tv_nsec -= NSEC_PER_SEC;
  441. }
  442. schedule_delayed_work(&sync_cmos_work, timespec_to_jiffies(&next));
  443. }
  444. static void notify_cmos_timer(void)
  445. {
  446. schedule_delayed_work(&sync_cmos_work, 0);
  447. }
  448. #else
  449. static inline void notify_cmos_timer(void) { }
  450. #endif
  451. /*
  452. * Propagate a new txc->status value into the NTP state:
  453. */
  454. static inline void process_adj_status(struct timex *txc, struct timespec *ts)
  455. {
  456. if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
  457. time_state = TIME_OK;
  458. time_status = STA_UNSYNC;
  459. /* restart PPS frequency calibration */
  460. pps_reset_freq_interval();
  461. }
  462. /*
  463. * If we turn on PLL adjustments then reset the
  464. * reference time to current time.
  465. */
  466. if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
  467. time_reftime = get_seconds();
  468. /* only set allowed bits */
  469. time_status &= STA_RONLY;
  470. time_status |= txc->status & ~STA_RONLY;
  471. }
  472. /*
  473. * Called with ntp_lock held, so we can access and modify
  474. * all the global NTP state:
  475. */
  476. static inline void process_adjtimex_modes(struct timex *txc, struct timespec *ts)
  477. {
  478. if (txc->modes & ADJ_STATUS)
  479. process_adj_status(txc, ts);
  480. if (txc->modes & ADJ_NANO)
  481. time_status |= STA_NANO;
  482. if (txc->modes & ADJ_MICRO)
  483. time_status &= ~STA_NANO;
  484. if (txc->modes & ADJ_FREQUENCY) {
  485. time_freq = txc->freq * PPM_SCALE;
  486. time_freq = min(time_freq, MAXFREQ_SCALED);
  487. time_freq = max(time_freq, -MAXFREQ_SCALED);
  488. /* update pps_freq */
  489. pps_set_freq(time_freq);
  490. }
  491. if (txc->modes & ADJ_MAXERROR)
  492. time_maxerror = txc->maxerror;
  493. if (txc->modes & ADJ_ESTERROR)
  494. time_esterror = txc->esterror;
  495. if (txc->modes & ADJ_TIMECONST) {
  496. time_constant = txc->constant;
  497. if (!(time_status & STA_NANO))
  498. time_constant += 4;
  499. time_constant = min(time_constant, (long)MAXTC);
  500. time_constant = max(time_constant, 0l);
  501. }
  502. if (txc->modes & ADJ_TAI && txc->constant > 0)
  503. time_tai = txc->constant;
  504. if (txc->modes & ADJ_OFFSET)
  505. ntp_update_offset(txc->offset);
  506. if (txc->modes & ADJ_TICK)
  507. tick_usec = txc->tick;
  508. if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
  509. ntp_update_frequency();
  510. }
  511. /*
  512. * adjtimex mainly allows reading (and writing, if superuser) of
  513. * kernel time-keeping variables. used by xntpd.
  514. */
  515. int do_adjtimex(struct timex *txc)
  516. {
  517. struct timespec ts;
  518. int result;
  519. /* Validate the data before disabling interrupts */
  520. if (txc->modes & ADJ_ADJTIME) {
  521. /* singleshot must not be used with any other mode bits */
  522. if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
  523. return -EINVAL;
  524. if (!(txc->modes & ADJ_OFFSET_READONLY) &&
  525. !capable(CAP_SYS_TIME))
  526. return -EPERM;
  527. } else {
  528. /* In order to modify anything, you gotta be super-user! */
  529. if (txc->modes && !capable(CAP_SYS_TIME))
  530. return -EPERM;
  531. /*
  532. * if the quartz is off by more than 10% then
  533. * something is VERY wrong!
  534. */
  535. if (txc->modes & ADJ_TICK &&
  536. (txc->tick < 900000/USER_HZ ||
  537. txc->tick > 1100000/USER_HZ))
  538. return -EINVAL;
  539. }
  540. if (txc->modes & ADJ_SETOFFSET) {
  541. struct timespec delta;
  542. delta.tv_sec = txc->time.tv_sec;
  543. delta.tv_nsec = txc->time.tv_usec;
  544. if (!capable(CAP_SYS_TIME))
  545. return -EPERM;
  546. if (!(txc->modes & ADJ_NANO))
  547. delta.tv_nsec *= 1000;
  548. result = timekeeping_inject_offset(&delta);
  549. if (result)
  550. return result;
  551. }
  552. getnstimeofday(&ts);
  553. raw_spin_lock_irq(&ntp_lock);
  554. if (txc->modes & ADJ_ADJTIME) {
  555. long save_adjust = time_adjust;
  556. if (!(txc->modes & ADJ_OFFSET_READONLY)) {
  557. /* adjtime() is independent from ntp_adjtime() */
  558. time_adjust = txc->offset;
  559. ntp_update_frequency();
  560. }
  561. txc->offset = save_adjust;
  562. } else {
  563. /* If there are input parameters, then process them: */
  564. if (txc->modes)
  565. process_adjtimex_modes(txc, &ts);
  566. txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
  567. NTP_SCALE_SHIFT);
  568. if (!(time_status & STA_NANO))
  569. txc->offset /= NSEC_PER_USEC;
  570. }
  571. result = time_state; /* mostly `TIME_OK' */
  572. /* check for errors */
  573. if (is_error_status(time_status))
  574. result = TIME_ERROR;
  575. txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
  576. PPM_SCALE_INV, NTP_SCALE_SHIFT);
  577. txc->maxerror = time_maxerror;
  578. txc->esterror = time_esterror;
  579. txc->status = time_status;
  580. txc->constant = time_constant;
  581. txc->precision = 1;
  582. txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
  583. txc->tick = tick_usec;
  584. txc->tai = time_tai;
  585. /* fill PPS status fields */
  586. pps_fill_timex(txc);
  587. raw_spin_unlock_irq(&ntp_lock);
  588. txc->time.tv_sec = ts.tv_sec;
  589. txc->time.tv_usec = ts.tv_nsec;
  590. if (!(time_status & STA_NANO))
  591. txc->time.tv_usec /= NSEC_PER_USEC;
  592. notify_cmos_timer();
  593. return result;
  594. }
  595. #ifdef CONFIG_NTP_PPS
  596. /* actually struct pps_normtime is good old struct timespec, but it is
  597. * semantically different (and it is the reason why it was invented):
  598. * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ]
  599. * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) */
  600. struct pps_normtime {
  601. __kernel_time_t sec; /* seconds */
  602. long nsec; /* nanoseconds */
  603. };
  604. /* normalize the timestamp so that nsec is in the
  605. ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval */
  606. static inline struct pps_normtime pps_normalize_ts(struct timespec ts)
  607. {
  608. struct pps_normtime norm = {
  609. .sec = ts.tv_sec,
  610. .nsec = ts.tv_nsec
  611. };
  612. if (norm.nsec > (NSEC_PER_SEC >> 1)) {
  613. norm.nsec -= NSEC_PER_SEC;
  614. norm.sec++;
  615. }
  616. return norm;
  617. }
  618. /* get current phase correction and jitter */
  619. static inline long pps_phase_filter_get(long *jitter)
  620. {
  621. *jitter = pps_tf[0] - pps_tf[1];
  622. if (*jitter < 0)
  623. *jitter = -*jitter;
  624. /* TODO: test various filters */
  625. return pps_tf[0];
  626. }
  627. /* add the sample to the phase filter */
  628. static inline void pps_phase_filter_add(long err)
  629. {
  630. pps_tf[2] = pps_tf[1];
  631. pps_tf[1] = pps_tf[0];
  632. pps_tf[0] = err;
  633. }
  634. /* decrease frequency calibration interval length.
  635. * It is halved after four consecutive unstable intervals.
  636. */
  637. static inline void pps_dec_freq_interval(void)
  638. {
  639. if (--pps_intcnt <= -PPS_INTCOUNT) {
  640. pps_intcnt = -PPS_INTCOUNT;
  641. if (pps_shift > PPS_INTMIN) {
  642. pps_shift--;
  643. pps_intcnt = 0;
  644. }
  645. }
  646. }
  647. /* increase frequency calibration interval length.
  648. * It is doubled after four consecutive stable intervals.
  649. */
  650. static inline void pps_inc_freq_interval(void)
  651. {
  652. if (++pps_intcnt >= PPS_INTCOUNT) {
  653. pps_intcnt = PPS_INTCOUNT;
  654. if (pps_shift < PPS_INTMAX) {
  655. pps_shift++;
  656. pps_intcnt = 0;
  657. }
  658. }
  659. }
  660. /* update clock frequency based on MONOTONIC_RAW clock PPS signal
  661. * timestamps
  662. *
  663. * At the end of the calibration interval the difference between the
  664. * first and last MONOTONIC_RAW clock timestamps divided by the length
  665. * of the interval becomes the frequency update. If the interval was
  666. * too long, the data are discarded.
  667. * Returns the difference between old and new frequency values.
  668. */
  669. static long hardpps_update_freq(struct pps_normtime freq_norm)
  670. {
  671. long delta, delta_mod;
  672. s64 ftemp;
  673. /* check if the frequency interval was too long */
  674. if (freq_norm.sec > (2 << pps_shift)) {
  675. time_status |= STA_PPSERROR;
  676. pps_errcnt++;
  677. pps_dec_freq_interval();
  678. pr_err("hardpps: PPSERROR: interval too long - %ld s\n",
  679. freq_norm.sec);
  680. return 0;
  681. }
  682. /* here the raw frequency offset and wander (stability) is
  683. * calculated. If the wander is less than the wander threshold
  684. * the interval is increased; otherwise it is decreased.
  685. */
  686. ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT,
  687. freq_norm.sec);
  688. delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT);
  689. pps_freq = ftemp;
  690. if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) {
  691. pr_warning("hardpps: PPSWANDER: change=%ld\n", delta);
  692. time_status |= STA_PPSWANDER;
  693. pps_stbcnt++;
  694. pps_dec_freq_interval();
  695. } else { /* good sample */
  696. pps_inc_freq_interval();
  697. }
  698. /* the stability metric is calculated as the average of recent
  699. * frequency changes, but is used only for performance
  700. * monitoring
  701. */
  702. delta_mod = delta;
  703. if (delta_mod < 0)
  704. delta_mod = -delta_mod;
  705. pps_stabil += (div_s64(((s64)delta_mod) <<
  706. (NTP_SCALE_SHIFT - SHIFT_USEC),
  707. NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN;
  708. /* if enabled, the system clock frequency is updated */
  709. if ((time_status & STA_PPSFREQ) != 0 &&
  710. (time_status & STA_FREQHOLD) == 0) {
  711. time_freq = pps_freq;
  712. ntp_update_frequency();
  713. }
  714. return delta;
  715. }
  716. /* correct REALTIME clock phase error against PPS signal */
  717. static void hardpps_update_phase(long error)
  718. {
  719. long correction = -error;
  720. long jitter;
  721. /* add the sample to the median filter */
  722. pps_phase_filter_add(correction);
  723. correction = pps_phase_filter_get(&jitter);
  724. /* Nominal jitter is due to PPS signal noise. If it exceeds the
  725. * threshold, the sample is discarded; otherwise, if so enabled,
  726. * the time offset is updated.
  727. */
  728. if (jitter > (pps_jitter << PPS_POPCORN)) {
  729. pr_warning("hardpps: PPSJITTER: jitter=%ld, limit=%ld\n",
  730. jitter, (pps_jitter << PPS_POPCORN));
  731. time_status |= STA_PPSJITTER;
  732. pps_jitcnt++;
  733. } else if (time_status & STA_PPSTIME) {
  734. /* correct the time using the phase offset */
  735. time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT,
  736. NTP_INTERVAL_FREQ);
  737. /* cancel running adjtime() */
  738. time_adjust = 0;
  739. }
  740. /* update jitter */
  741. pps_jitter += (jitter - pps_jitter) >> PPS_INTMIN;
  742. }
  743. /*
  744. * hardpps() - discipline CPU clock oscillator to external PPS signal
  745. *
  746. * This routine is called at each PPS signal arrival in order to
  747. * discipline the CPU clock oscillator to the PPS signal. It takes two
  748. * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former
  749. * is used to correct clock phase error and the latter is used to
  750. * correct the frequency.
  751. *
  752. * This code is based on David Mills's reference nanokernel
  753. * implementation. It was mostly rewritten but keeps the same idea.
  754. */
  755. void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
  756. {
  757. struct pps_normtime pts_norm, freq_norm;
  758. unsigned long flags;
  759. pts_norm = pps_normalize_ts(*phase_ts);
  760. raw_spin_lock_irqsave(&ntp_lock, flags);
  761. /* clear the error bits, they will be set again if needed */
  762. time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
  763. /* indicate signal presence */
  764. time_status |= STA_PPSSIGNAL;
  765. pps_valid = PPS_VALID;
  766. /* when called for the first time,
  767. * just start the frequency interval */
  768. if (unlikely(pps_fbase.tv_sec == 0)) {
  769. pps_fbase = *raw_ts;
  770. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  771. return;
  772. }
  773. /* ok, now we have a base for frequency calculation */
  774. freq_norm = pps_normalize_ts(timespec_sub(*raw_ts, pps_fbase));
  775. /* check that the signal is in the range
  776. * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it */
  777. if ((freq_norm.sec == 0) ||
  778. (freq_norm.nsec > MAXFREQ * freq_norm.sec) ||
  779. (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) {
  780. time_status |= STA_PPSJITTER;
  781. /* restart the frequency calibration interval */
  782. pps_fbase = *raw_ts;
  783. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  784. pr_err("hardpps: PPSJITTER: bad pulse\n");
  785. return;
  786. }
  787. /* signal is ok */
  788. /* check if the current frequency interval is finished */
  789. if (freq_norm.sec >= (1 << pps_shift)) {
  790. pps_calcnt++;
  791. /* restart the frequency calibration interval */
  792. pps_fbase = *raw_ts;
  793. hardpps_update_freq(freq_norm);
  794. }
  795. hardpps_update_phase(pts_norm.nsec);
  796. raw_spin_unlock_irqrestore(&ntp_lock, flags);
  797. }
  798. EXPORT_SYMBOL(hardpps);
  799. #endif /* CONFIG_NTP_PPS */
  800. static int __init ntp_tick_adj_setup(char *str)
  801. {
  802. ntp_tick_adj = simple_strtol(str, NULL, 0);
  803. ntp_tick_adj <<= NTP_SCALE_SHIFT;
  804. return 1;
  805. }
  806. __setup("ntp_tick_adj=", ntp_tick_adj_setup);
  807. void __init ntp_init(void)
  808. {
  809. ntp_clear();
  810. }