ntp.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. /*
  18. * NTP timekeeping variables:
  19. */
  20. /* USER_HZ period (usecs): */
  21. unsigned long tick_usec = TICK_USEC;
  22. /* ACTHZ period (nsecs): */
  23. unsigned long tick_nsec;
  24. u64 tick_length;
  25. static u64 tick_length_base;
  26. static struct hrtimer leap_timer;
  27. #define MAX_TICKADJ 500LL /* usecs */
  28. #define MAX_TICKADJ_SCALED \
  29. (((MAX_TICKADJ * NSEC_PER_USEC) << NTP_SCALE_SHIFT) / NTP_INTERVAL_FREQ)
  30. /*
  31. * phase-lock loop variables
  32. */
  33. /*
  34. * clock synchronization status
  35. *
  36. * (TIME_ERROR prevents overwriting the CMOS clock)
  37. */
  38. static int time_state = TIME_OK;
  39. /* clock status bits: */
  40. int time_status = STA_UNSYNC;
  41. /* TAI offset (secs): */
  42. static long time_tai;
  43. /* time adjustment (nsecs): */
  44. static s64 time_offset;
  45. /* pll time constant: */
  46. static long time_constant = 2;
  47. /* maximum error (usecs): */
  48. static long time_maxerror = NTP_PHASE_LIMIT;
  49. /* estimated error (usecs): */
  50. static long time_esterror = NTP_PHASE_LIMIT;
  51. /* frequency offset (scaled nsecs/secs): */
  52. static s64 time_freq;
  53. /* time at last adjustment (secs): */
  54. static long time_reftime;
  55. static long time_adjust;
  56. /* constant (boot-param configurable) NTP tick adjustment (upscaled) */
  57. static s64 ntp_tick_adj;
  58. /*
  59. * NTP methods:
  60. */
  61. /*
  62. * Update (tick_length, tick_length_base, tick_nsec), based
  63. * on (tick_usec, ntp_tick_adj, time_freq):
  64. */
  65. static void ntp_update_frequency(void)
  66. {
  67. u64 second_length;
  68. u64 new_base;
  69. second_length = (u64)(tick_usec * NSEC_PER_USEC * USER_HZ)
  70. << NTP_SCALE_SHIFT;
  71. second_length += ntp_tick_adj;
  72. second_length += time_freq;
  73. tick_nsec = div_u64(second_length, HZ) >> NTP_SCALE_SHIFT;
  74. new_base = div_u64(second_length, NTP_INTERVAL_FREQ);
  75. /*
  76. * Don't wait for the next second_overflow, apply
  77. * the change to the tick length immediately:
  78. */
  79. tick_length += new_base - tick_length_base;
  80. tick_length_base = new_base;
  81. }
  82. static inline s64 ntp_update_offset_fll(s64 offset64, long secs)
  83. {
  84. time_status &= ~STA_MODE;
  85. if (secs < MINSEC)
  86. return 0;
  87. if (!(time_status & STA_FLL) && (secs <= MAXSEC))
  88. return 0;
  89. time_status |= STA_MODE;
  90. return div_s64(offset64 << (NTP_SCALE_SHIFT - SHIFT_FLL), secs);
  91. }
  92. static void ntp_update_offset(long offset)
  93. {
  94. s64 freq_adj;
  95. s64 offset64;
  96. long secs;
  97. if (!(time_status & STA_PLL))
  98. return;
  99. if (!(time_status & STA_NANO))
  100. offset *= NSEC_PER_USEC;
  101. /*
  102. * Scale the phase adjustment and
  103. * clamp to the operating range.
  104. */
  105. offset = min(offset, MAXPHASE);
  106. offset = max(offset, -MAXPHASE);
  107. /*
  108. * Select how the frequency is to be controlled
  109. * and in which mode (PLL or FLL).
  110. */
  111. secs = get_seconds() - time_reftime;
  112. if (unlikely(time_status & STA_FREQHOLD))
  113. secs = 0;
  114. time_reftime = get_seconds();
  115. offset64 = offset;
  116. freq_adj = ntp_update_offset_fll(offset64, secs);
  117. /*
  118. * Clamp update interval to reduce PLL gain with low
  119. * sampling rate (e.g. intermittent network connection)
  120. * to avoid instability.
  121. */
  122. if (unlikely(secs > 1 << (SHIFT_PLL + 1 + time_constant)))
  123. secs = 1 << (SHIFT_PLL + 1 + time_constant);
  124. freq_adj += (offset64 * secs) <<
  125. (NTP_SCALE_SHIFT - 2 * (SHIFT_PLL + 2 + time_constant));
  126. freq_adj = min(freq_adj + time_freq, MAXFREQ_SCALED);
  127. time_freq = max(freq_adj, -MAXFREQ_SCALED);
  128. time_offset = div_s64(offset64 << NTP_SCALE_SHIFT, NTP_INTERVAL_FREQ);
  129. }
  130. /**
  131. * ntp_clear - Clears the NTP state variables
  132. *
  133. * Must be called while holding a write on the xtime_lock
  134. */
  135. void ntp_clear(void)
  136. {
  137. time_adjust = 0; /* stop active adjtime() */
  138. time_status |= STA_UNSYNC;
  139. time_maxerror = NTP_PHASE_LIMIT;
  140. time_esterror = NTP_PHASE_LIMIT;
  141. ntp_update_frequency();
  142. tick_length = tick_length_base;
  143. time_offset = 0;
  144. }
  145. /*
  146. * Leap second processing. If in leap-insert state at the end of the
  147. * day, the system clock is set back one second; if in leap-delete
  148. * state, the system clock is set ahead one second.
  149. */
  150. static enum hrtimer_restart ntp_leap_second(struct hrtimer *timer)
  151. {
  152. enum hrtimer_restart res = HRTIMER_NORESTART;
  153. write_seqlock(&xtime_lock);
  154. switch (time_state) {
  155. case TIME_OK:
  156. break;
  157. case TIME_INS:
  158. timekeeping_leap_insert(-1);
  159. time_state = TIME_OOP;
  160. printk(KERN_NOTICE
  161. "Clock: inserting leap second 23:59:60 UTC\n");
  162. hrtimer_add_expires_ns(&leap_timer, NSEC_PER_SEC);
  163. res = HRTIMER_RESTART;
  164. break;
  165. case TIME_DEL:
  166. timekeeping_leap_insert(1);
  167. time_tai--;
  168. time_state = TIME_WAIT;
  169. printk(KERN_NOTICE
  170. "Clock: deleting leap second 23:59:59 UTC\n");
  171. break;
  172. case TIME_OOP:
  173. time_tai++;
  174. time_state = TIME_WAIT;
  175. /* fall through */
  176. case TIME_WAIT:
  177. if (!(time_status & (STA_INS | STA_DEL)))
  178. time_state = TIME_OK;
  179. break;
  180. }
  181. write_sequnlock(&xtime_lock);
  182. return res;
  183. }
  184. /*
  185. * this routine handles the overflow of the microsecond field
  186. *
  187. * The tricky bits of code to handle the accurate clock support
  188. * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
  189. * They were originally developed for SUN and DEC kernels.
  190. * All the kudos should go to Dave for this stuff.
  191. */
  192. void second_overflow(void)
  193. {
  194. s64 delta;
  195. /* Bump the maxerror field */
  196. time_maxerror += MAXFREQ / NSEC_PER_USEC;
  197. if (time_maxerror > NTP_PHASE_LIMIT) {
  198. time_maxerror = NTP_PHASE_LIMIT;
  199. time_status |= STA_UNSYNC;
  200. }
  201. /*
  202. * Compute the phase adjustment for the next second. The offset is
  203. * reduced by a fixed factor times the time constant.
  204. */
  205. tick_length = tick_length_base;
  206. delta = shift_right(time_offset, SHIFT_PLL + time_constant);
  207. time_offset -= delta;
  208. tick_length += delta;
  209. if (!time_adjust)
  210. return;
  211. if (time_adjust > MAX_TICKADJ) {
  212. time_adjust -= MAX_TICKADJ;
  213. tick_length += MAX_TICKADJ_SCALED;
  214. return;
  215. }
  216. if (time_adjust < -MAX_TICKADJ) {
  217. time_adjust += MAX_TICKADJ;
  218. tick_length -= MAX_TICKADJ_SCALED;
  219. return;
  220. }
  221. tick_length += (s64)(time_adjust * NSEC_PER_USEC / NTP_INTERVAL_FREQ)
  222. << NTP_SCALE_SHIFT;
  223. time_adjust = 0;
  224. }
  225. #ifdef CONFIG_GENERIC_CMOS_UPDATE
  226. /* Disable the cmos update - used by virtualization and embedded */
  227. int no_sync_cmos_clock __read_mostly;
  228. static void sync_cmos_clock(struct work_struct *work);
  229. static DECLARE_DELAYED_WORK(sync_cmos_work, sync_cmos_clock);
  230. static void sync_cmos_clock(struct work_struct *work)
  231. {
  232. struct timespec now, next;
  233. int fail = 1;
  234. /*
  235. * If we have an externally synchronized Linux clock, then update
  236. * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
  237. * called as close as possible to 500 ms before the new second starts.
  238. * This code is run on a timer. If the clock is set, that timer
  239. * may not expire at the correct time. Thus, we adjust...
  240. */
  241. if (!ntp_synced()) {
  242. /*
  243. * Not synced, exit, do not restart a timer (if one is
  244. * running, let it run out).
  245. */
  246. return;
  247. }
  248. getnstimeofday(&now);
  249. if (abs(now.tv_nsec - (NSEC_PER_SEC / 2)) <= tick_nsec / 2)
  250. fail = update_persistent_clock(now);
  251. next.tv_nsec = (NSEC_PER_SEC / 2) - now.tv_nsec - (TICK_NSEC / 2);
  252. if (next.tv_nsec <= 0)
  253. next.tv_nsec += NSEC_PER_SEC;
  254. if (!fail)
  255. next.tv_sec = 659;
  256. else
  257. next.tv_sec = 0;
  258. if (next.tv_nsec >= NSEC_PER_SEC) {
  259. next.tv_sec++;
  260. next.tv_nsec -= NSEC_PER_SEC;
  261. }
  262. schedule_delayed_work(&sync_cmos_work, timespec_to_jiffies(&next));
  263. }
  264. static void notify_cmos_timer(void)
  265. {
  266. if (!no_sync_cmos_clock)
  267. schedule_delayed_work(&sync_cmos_work, 0);
  268. }
  269. #else
  270. static inline void notify_cmos_timer(void) { }
  271. #endif
  272. /*
  273. * Start the leap seconds timer:
  274. */
  275. static inline void ntp_start_leap_timer(struct timespec *ts)
  276. {
  277. long now = ts->tv_sec;
  278. if (time_status & STA_INS) {
  279. time_state = TIME_INS;
  280. now += 86400 - now % 86400;
  281. hrtimer_start(&leap_timer, ktime_set(now, 0), HRTIMER_MODE_ABS);
  282. return;
  283. }
  284. if (time_status & STA_DEL) {
  285. time_state = TIME_DEL;
  286. now += 86400 - (now + 1) % 86400;
  287. hrtimer_start(&leap_timer, ktime_set(now, 0), HRTIMER_MODE_ABS);
  288. }
  289. }
  290. /*
  291. * Propagate a new txc->status value into the NTP state:
  292. */
  293. static inline void process_adj_status(struct timex *txc, struct timespec *ts)
  294. {
  295. if ((time_status & STA_PLL) && !(txc->status & STA_PLL)) {
  296. time_state = TIME_OK;
  297. time_status = STA_UNSYNC;
  298. }
  299. /*
  300. * If we turn on PLL adjustments then reset the
  301. * reference time to current time.
  302. */
  303. if (!(time_status & STA_PLL) && (txc->status & STA_PLL))
  304. time_reftime = get_seconds();
  305. /* only set allowed bits */
  306. time_status &= STA_RONLY;
  307. time_status |= txc->status & ~STA_RONLY;
  308. switch (time_state) {
  309. case TIME_OK:
  310. ntp_start_leap_timer(ts);
  311. break;
  312. case TIME_INS:
  313. case TIME_DEL:
  314. time_state = TIME_OK;
  315. ntp_start_leap_timer(ts);
  316. case TIME_WAIT:
  317. if (!(time_status & (STA_INS | STA_DEL)))
  318. time_state = TIME_OK;
  319. break;
  320. case TIME_OOP:
  321. hrtimer_restart(&leap_timer);
  322. break;
  323. }
  324. }
  325. /*
  326. * Called with the xtime lock held, so we can access and modify
  327. * all the global NTP state:
  328. */
  329. static inline void process_adjtimex_modes(struct timex *txc, struct timespec *ts)
  330. {
  331. if (txc->modes & ADJ_STATUS)
  332. process_adj_status(txc, ts);
  333. if (txc->modes & ADJ_NANO)
  334. time_status |= STA_NANO;
  335. if (txc->modes & ADJ_MICRO)
  336. time_status &= ~STA_NANO;
  337. if (txc->modes & ADJ_FREQUENCY) {
  338. time_freq = txc->freq * PPM_SCALE;
  339. time_freq = min(time_freq, MAXFREQ_SCALED);
  340. time_freq = max(time_freq, -MAXFREQ_SCALED);
  341. }
  342. if (txc->modes & ADJ_MAXERROR)
  343. time_maxerror = txc->maxerror;
  344. if (txc->modes & ADJ_ESTERROR)
  345. time_esterror = txc->esterror;
  346. if (txc->modes & ADJ_TIMECONST) {
  347. time_constant = txc->constant;
  348. if (!(time_status & STA_NANO))
  349. time_constant += 4;
  350. time_constant = min(time_constant, (long)MAXTC);
  351. time_constant = max(time_constant, 0l);
  352. }
  353. if (txc->modes & ADJ_TAI && txc->constant > 0)
  354. time_tai = txc->constant;
  355. if (txc->modes & ADJ_OFFSET)
  356. ntp_update_offset(txc->offset);
  357. if (txc->modes & ADJ_TICK)
  358. tick_usec = txc->tick;
  359. if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
  360. ntp_update_frequency();
  361. }
  362. /*
  363. * adjtimex mainly allows reading (and writing, if superuser) of
  364. * kernel time-keeping variables. used by xntpd.
  365. */
  366. int do_adjtimex(struct timex *txc)
  367. {
  368. struct timespec ts;
  369. int result;
  370. /* Validate the data before disabling interrupts */
  371. if (txc->modes & ADJ_ADJTIME) {
  372. /* singleshot must not be used with any other mode bits */
  373. if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
  374. return -EINVAL;
  375. if (!(txc->modes & ADJ_OFFSET_READONLY) &&
  376. !capable(CAP_SYS_TIME))
  377. return -EPERM;
  378. } else {
  379. /* In order to modify anything, you gotta be super-user! */
  380. if (txc->modes && !capable(CAP_SYS_TIME))
  381. return -EPERM;
  382. /*
  383. * if the quartz is off by more than 10% then
  384. * something is VERY wrong!
  385. */
  386. if (txc->modes & ADJ_TICK &&
  387. (txc->tick < 900000/USER_HZ ||
  388. txc->tick > 1100000/USER_HZ))
  389. return -EINVAL;
  390. if (txc->modes & ADJ_STATUS && time_state != TIME_OK)
  391. hrtimer_cancel(&leap_timer);
  392. }
  393. getnstimeofday(&ts);
  394. write_seqlock_irq(&xtime_lock);
  395. if (txc->modes & ADJ_ADJTIME) {
  396. long save_adjust = time_adjust;
  397. if (!(txc->modes & ADJ_OFFSET_READONLY)) {
  398. /* adjtime() is independent from ntp_adjtime() */
  399. time_adjust = txc->offset;
  400. ntp_update_frequency();
  401. }
  402. txc->offset = save_adjust;
  403. } else {
  404. /* If there are input parameters, then process them: */
  405. if (txc->modes)
  406. process_adjtimex_modes(txc, &ts);
  407. txc->offset = shift_right(time_offset * NTP_INTERVAL_FREQ,
  408. NTP_SCALE_SHIFT);
  409. if (!(time_status & STA_NANO))
  410. txc->offset /= NSEC_PER_USEC;
  411. }
  412. result = time_state; /* mostly `TIME_OK' */
  413. if (time_status & (STA_UNSYNC|STA_CLOCKERR))
  414. result = TIME_ERROR;
  415. txc->freq = shift_right((time_freq >> PPM_SCALE_INV_SHIFT) *
  416. PPM_SCALE_INV, NTP_SCALE_SHIFT);
  417. txc->maxerror = time_maxerror;
  418. txc->esterror = time_esterror;
  419. txc->status = time_status;
  420. txc->constant = time_constant;
  421. txc->precision = 1;
  422. txc->tolerance = MAXFREQ_SCALED / PPM_SCALE;
  423. txc->tick = tick_usec;
  424. txc->tai = time_tai;
  425. /* PPS is not implemented, so these are zero */
  426. txc->ppsfreq = 0;
  427. txc->jitter = 0;
  428. txc->shift = 0;
  429. txc->stabil = 0;
  430. txc->jitcnt = 0;
  431. txc->calcnt = 0;
  432. txc->errcnt = 0;
  433. txc->stbcnt = 0;
  434. write_sequnlock_irq(&xtime_lock);
  435. txc->time.tv_sec = ts.tv_sec;
  436. txc->time.tv_usec = ts.tv_nsec;
  437. if (!(time_status & STA_NANO))
  438. txc->time.tv_usec /= NSEC_PER_USEC;
  439. notify_cmos_timer();
  440. return result;
  441. }
  442. static int __init ntp_tick_adj_setup(char *str)
  443. {
  444. ntp_tick_adj = simple_strtol(str, NULL, 0);
  445. ntp_tick_adj <<= NTP_SCALE_SHIFT;
  446. return 1;
  447. }
  448. __setup("ntp_tick_adj=", ntp_tick_adj_setup);
  449. void __init ntp_init(void)
  450. {
  451. ntp_clear();
  452. hrtimer_init(&leap_timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
  453. leap_timer.function = ntp_leap_second;
  454. }