timekeeping.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /*
  2. * linux/kernel/time/timekeeping.c
  3. *
  4. * Kernel timekeeping code and accessor functions
  5. *
  6. * This code was moved from linux/kernel/timer.c.
  7. * Please see that file for copyright and history logs.
  8. *
  9. */
  10. #include <linux/module.h>
  11. #include <linux/interrupt.h>
  12. #include <linux/percpu.h>
  13. #include <linux/init.h>
  14. #include <linux/mm.h>
  15. #include <linux/sched.h>
  16. #include <linux/syscore_ops.h>
  17. #include <linux/clocksource.h>
  18. #include <linux/jiffies.h>
  19. #include <linux/time.h>
  20. #include <linux/tick.h>
  21. #include <linux/stop_machine.h>
  22. /* Structure holding internal timekeeping values. */
  23. struct timekeeper {
  24. /* Current clocksource used for timekeeping. */
  25. struct clocksource *clock;
  26. /* NTP adjusted clock multiplier */
  27. u32 mult;
  28. /* The shift value of the current clocksource. */
  29. int shift;
  30. /* Number of clock cycles in one NTP interval. */
  31. cycle_t cycle_interval;
  32. /* Number of clock shifted nano seconds in one NTP interval. */
  33. u64 xtime_interval;
  34. /* shifted nano seconds left over when rounding cycle_interval */
  35. s64 xtime_remainder;
  36. /* Raw nano seconds accumulated per NTP interval. */
  37. u32 raw_interval;
  38. /* Clock shifted nano seconds remainder not stored in xtime.tv_nsec. */
  39. u64 xtime_nsec;
  40. /* Difference between accumulated time and NTP time in ntp
  41. * shifted nano seconds. */
  42. s64 ntp_error;
  43. /* Shift conversion between clock shifted nano seconds and
  44. * ntp shifted nano seconds. */
  45. int ntp_error_shift;
  46. /* The current time */
  47. struct timespec xtime;
  48. /*
  49. * wall_to_monotonic is what we need to add to xtime (or xtime corrected
  50. * for sub jiffie times) to get to monotonic time. Monotonic is pegged
  51. * at zero at system boot time, so wall_to_monotonic will be negative,
  52. * however, we will ALWAYS keep the tv_nsec part positive so we can use
  53. * the usual normalization.
  54. *
  55. * wall_to_monotonic is moved after resume from suspend for the
  56. * monotonic time not to jump. We need to add total_sleep_time to
  57. * wall_to_monotonic to get the real boot based time offset.
  58. *
  59. * - wall_to_monotonic is no longer the boot time, getboottime must be
  60. * used instead.
  61. */
  62. struct timespec wall_to_monotonic;
  63. /* time spent in suspend */
  64. struct timespec total_sleep_time;
  65. /* The raw monotonic time for the CLOCK_MONOTONIC_RAW posix clock. */
  66. struct timespec raw_time;
  67. /* Seqlock for all timekeeper values */
  68. seqlock_t lock;
  69. };
  70. static struct timekeeper timekeeper;
  71. /*
  72. * This read-write spinlock protects us from races in SMP while
  73. * playing with xtime.
  74. */
  75. __cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
  76. /* flag for if timekeeping is suspended */
  77. int __read_mostly timekeeping_suspended;
  78. /**
  79. * timekeeper_setup_internals - Set up internals to use clocksource clock.
  80. *
  81. * @clock: Pointer to clocksource.
  82. *
  83. * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
  84. * pair and interval request.
  85. *
  86. * Unless you're the timekeeping code, you should not be using this!
  87. */
  88. static void timekeeper_setup_internals(struct clocksource *clock)
  89. {
  90. cycle_t interval;
  91. u64 tmp, ntpinterval;
  92. timekeeper.clock = clock;
  93. clock->cycle_last = clock->read(clock);
  94. /* Do the ns -> cycle conversion first, using original mult */
  95. tmp = NTP_INTERVAL_LENGTH;
  96. tmp <<= clock->shift;
  97. ntpinterval = tmp;
  98. tmp += clock->mult/2;
  99. do_div(tmp, clock->mult);
  100. if (tmp == 0)
  101. tmp = 1;
  102. interval = (cycle_t) tmp;
  103. timekeeper.cycle_interval = interval;
  104. /* Go back from cycles -> shifted ns */
  105. timekeeper.xtime_interval = (u64) interval * clock->mult;
  106. timekeeper.xtime_remainder = ntpinterval - timekeeper.xtime_interval;
  107. timekeeper.raw_interval =
  108. ((u64) interval * clock->mult) >> clock->shift;
  109. timekeeper.xtime_nsec = 0;
  110. timekeeper.shift = clock->shift;
  111. timekeeper.ntp_error = 0;
  112. timekeeper.ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
  113. /*
  114. * The timekeeper keeps its own mult values for the currently
  115. * active clocksource. These value will be adjusted via NTP
  116. * to counteract clock drifting.
  117. */
  118. timekeeper.mult = clock->mult;
  119. }
  120. /* Timekeeper helper functions. */
  121. static inline s64 timekeeping_get_ns(void)
  122. {
  123. cycle_t cycle_now, cycle_delta;
  124. struct clocksource *clock;
  125. /* read clocksource: */
  126. clock = timekeeper.clock;
  127. cycle_now = clock->read(clock);
  128. /* calculate the delta since the last update_wall_time: */
  129. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  130. /* return delta convert to nanoseconds using ntp adjusted mult. */
  131. return clocksource_cyc2ns(cycle_delta, timekeeper.mult,
  132. timekeeper.shift);
  133. }
  134. static inline s64 timekeeping_get_ns_raw(void)
  135. {
  136. cycle_t cycle_now, cycle_delta;
  137. struct clocksource *clock;
  138. /* read clocksource: */
  139. clock = timekeeper.clock;
  140. cycle_now = clock->read(clock);
  141. /* calculate the delta since the last update_wall_time: */
  142. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  143. /* return delta convert to nanoseconds. */
  144. return clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
  145. }
  146. /* must hold write on timekeeper.lock */
  147. static void timekeeping_update(bool clearntp)
  148. {
  149. if (clearntp) {
  150. timekeeper.ntp_error = 0;
  151. ntp_clear();
  152. }
  153. update_vsyscall(&timekeeper.xtime, &timekeeper.wall_to_monotonic,
  154. timekeeper.clock, timekeeper.mult);
  155. }
  156. void timekeeping_leap_insert(int leapsecond)
  157. {
  158. unsigned long flags;
  159. write_seqlock_irqsave(&timekeeper.lock, flags);
  160. timekeeper.xtime.tv_sec += leapsecond;
  161. timekeeper.wall_to_monotonic.tv_sec -= leapsecond;
  162. timekeeping_update(false);
  163. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  164. }
  165. /**
  166. * timekeeping_forward_now - update clock to the current time
  167. *
  168. * Forward the current clock to update its state since the last call to
  169. * update_wall_time(). This is useful before significant clock changes,
  170. * as it avoids having to deal with this time offset explicitly.
  171. */
  172. static void timekeeping_forward_now(void)
  173. {
  174. cycle_t cycle_now, cycle_delta;
  175. struct clocksource *clock;
  176. s64 nsec;
  177. clock = timekeeper.clock;
  178. cycle_now = clock->read(clock);
  179. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  180. clock->cycle_last = cycle_now;
  181. nsec = clocksource_cyc2ns(cycle_delta, timekeeper.mult,
  182. timekeeper.shift);
  183. /* If arch requires, add in gettimeoffset() */
  184. nsec += arch_gettimeoffset();
  185. timespec_add_ns(&timekeeper.xtime, nsec);
  186. nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
  187. timespec_add_ns(&timekeeper.raw_time, nsec);
  188. }
  189. /**
  190. * getnstimeofday - Returns the time of day in a timespec
  191. * @ts: pointer to the timespec to be set
  192. *
  193. * Returns the time of day in a timespec.
  194. */
  195. void getnstimeofday(struct timespec *ts)
  196. {
  197. unsigned long seq;
  198. s64 nsecs;
  199. WARN_ON(timekeeping_suspended);
  200. do {
  201. seq = read_seqbegin(&timekeeper.lock);
  202. *ts = timekeeper.xtime;
  203. nsecs = timekeeping_get_ns();
  204. /* If arch requires, add in gettimeoffset() */
  205. nsecs += arch_gettimeoffset();
  206. } while (read_seqretry(&timekeeper.lock, seq));
  207. timespec_add_ns(ts, nsecs);
  208. }
  209. EXPORT_SYMBOL(getnstimeofday);
  210. ktime_t ktime_get(void)
  211. {
  212. unsigned int seq;
  213. s64 secs, nsecs;
  214. WARN_ON(timekeeping_suspended);
  215. do {
  216. seq = read_seqbegin(&timekeeper.lock);
  217. secs = timekeeper.xtime.tv_sec +
  218. timekeeper.wall_to_monotonic.tv_sec;
  219. nsecs = timekeeper.xtime.tv_nsec +
  220. timekeeper.wall_to_monotonic.tv_nsec;
  221. nsecs += timekeeping_get_ns();
  222. /* If arch requires, add in gettimeoffset() */
  223. nsecs += arch_gettimeoffset();
  224. } while (read_seqretry(&timekeeper.lock, seq));
  225. /*
  226. * Use ktime_set/ktime_add_ns to create a proper ktime on
  227. * 32-bit architectures without CONFIG_KTIME_SCALAR.
  228. */
  229. return ktime_add_ns(ktime_set(secs, 0), nsecs);
  230. }
  231. EXPORT_SYMBOL_GPL(ktime_get);
  232. /**
  233. * ktime_get_ts - get the monotonic clock in timespec format
  234. * @ts: pointer to timespec variable
  235. *
  236. * The function calculates the monotonic clock from the realtime
  237. * clock and the wall_to_monotonic offset and stores the result
  238. * in normalized timespec format in the variable pointed to by @ts.
  239. */
  240. void ktime_get_ts(struct timespec *ts)
  241. {
  242. struct timespec tomono;
  243. unsigned int seq;
  244. s64 nsecs;
  245. WARN_ON(timekeeping_suspended);
  246. do {
  247. seq = read_seqbegin(&timekeeper.lock);
  248. *ts = timekeeper.xtime;
  249. tomono = timekeeper.wall_to_monotonic;
  250. nsecs = timekeeping_get_ns();
  251. /* If arch requires, add in gettimeoffset() */
  252. nsecs += arch_gettimeoffset();
  253. } while (read_seqretry(&timekeeper.lock, seq));
  254. set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
  255. ts->tv_nsec + tomono.tv_nsec + nsecs);
  256. }
  257. EXPORT_SYMBOL_GPL(ktime_get_ts);
  258. #ifdef CONFIG_NTP_PPS
  259. /**
  260. * getnstime_raw_and_real - get day and raw monotonic time in timespec format
  261. * @ts_raw: pointer to the timespec to be set to raw monotonic time
  262. * @ts_real: pointer to the timespec to be set to the time of day
  263. *
  264. * This function reads both the time of day and raw monotonic time at the
  265. * same time atomically and stores the resulting timestamps in timespec
  266. * format.
  267. */
  268. void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
  269. {
  270. unsigned long seq;
  271. s64 nsecs_raw, nsecs_real;
  272. WARN_ON_ONCE(timekeeping_suspended);
  273. do {
  274. u32 arch_offset;
  275. seq = read_seqbegin(&timekeeper.lock);
  276. *ts_raw = timekeeper.raw_time;
  277. *ts_real = timekeeper.xtime;
  278. nsecs_raw = timekeeping_get_ns_raw();
  279. nsecs_real = timekeeping_get_ns();
  280. /* If arch requires, add in gettimeoffset() */
  281. arch_offset = arch_gettimeoffset();
  282. nsecs_raw += arch_offset;
  283. nsecs_real += arch_offset;
  284. } while (read_seqretry(&timekeeper.lock, seq));
  285. timespec_add_ns(ts_raw, nsecs_raw);
  286. timespec_add_ns(ts_real, nsecs_real);
  287. }
  288. EXPORT_SYMBOL(getnstime_raw_and_real);
  289. #endif /* CONFIG_NTP_PPS */
  290. /**
  291. * do_gettimeofday - Returns the time of day in a timeval
  292. * @tv: pointer to the timeval to be set
  293. *
  294. * NOTE: Users should be converted to using getnstimeofday()
  295. */
  296. void do_gettimeofday(struct timeval *tv)
  297. {
  298. struct timespec now;
  299. getnstimeofday(&now);
  300. tv->tv_sec = now.tv_sec;
  301. tv->tv_usec = now.tv_nsec/1000;
  302. }
  303. EXPORT_SYMBOL(do_gettimeofday);
  304. /**
  305. * do_settimeofday - Sets the time of day
  306. * @tv: pointer to the timespec variable containing the new time
  307. *
  308. * Sets the time of day to the new time and update NTP and notify hrtimers
  309. */
  310. int do_settimeofday(const struct timespec *tv)
  311. {
  312. struct timespec ts_delta;
  313. unsigned long flags;
  314. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  315. return -EINVAL;
  316. write_seqlock_irqsave(&timekeeper.lock, flags);
  317. timekeeping_forward_now();
  318. ts_delta.tv_sec = tv->tv_sec - timekeeper.xtime.tv_sec;
  319. ts_delta.tv_nsec = tv->tv_nsec - timekeeper.xtime.tv_nsec;
  320. timekeeper.wall_to_monotonic =
  321. timespec_sub(timekeeper.wall_to_monotonic, ts_delta);
  322. timekeeper.xtime = *tv;
  323. timekeeping_update(true);
  324. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  325. /* signal hrtimers about time change */
  326. clock_was_set();
  327. return 0;
  328. }
  329. EXPORT_SYMBOL(do_settimeofday);
  330. /**
  331. * timekeeping_inject_offset - Adds or subtracts from the current time.
  332. * @tv: pointer to the timespec variable containing the offset
  333. *
  334. * Adds or subtracts an offset value from the current time.
  335. */
  336. int timekeeping_inject_offset(struct timespec *ts)
  337. {
  338. unsigned long flags;
  339. if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
  340. return -EINVAL;
  341. write_seqlock_irqsave(&timekeeper.lock, flags);
  342. timekeeping_forward_now();
  343. timekeeper.xtime = timespec_add(timekeeper.xtime, *ts);
  344. timekeeper.wall_to_monotonic =
  345. timespec_sub(timekeeper.wall_to_monotonic, *ts);
  346. timekeeping_update(true);
  347. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  348. /* signal hrtimers about time change */
  349. clock_was_set();
  350. return 0;
  351. }
  352. EXPORT_SYMBOL(timekeeping_inject_offset);
  353. /**
  354. * change_clocksource - Swaps clocksources if a new one is available
  355. *
  356. * Accumulates current time interval and initializes new clocksource
  357. */
  358. static int change_clocksource(void *data)
  359. {
  360. struct clocksource *new, *old;
  361. unsigned long flags;
  362. new = (struct clocksource *) data;
  363. write_seqlock_irqsave(&timekeeper.lock, flags);
  364. timekeeping_forward_now();
  365. if (!new->enable || new->enable(new) == 0) {
  366. old = timekeeper.clock;
  367. timekeeper_setup_internals(new);
  368. if (old->disable)
  369. old->disable(old);
  370. }
  371. timekeeping_update(true);
  372. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  373. return 0;
  374. }
  375. /**
  376. * timekeeping_notify - Install a new clock source
  377. * @clock: pointer to the clock source
  378. *
  379. * This function is called from clocksource.c after a new, better clock
  380. * source has been registered. The caller holds the clocksource_mutex.
  381. */
  382. void timekeeping_notify(struct clocksource *clock)
  383. {
  384. if (timekeeper.clock == clock)
  385. return;
  386. stop_machine(change_clocksource, clock, NULL);
  387. tick_clock_notify();
  388. }
  389. /**
  390. * ktime_get_real - get the real (wall-) time in ktime_t format
  391. *
  392. * returns the time in ktime_t format
  393. */
  394. ktime_t ktime_get_real(void)
  395. {
  396. struct timespec now;
  397. getnstimeofday(&now);
  398. return timespec_to_ktime(now);
  399. }
  400. EXPORT_SYMBOL_GPL(ktime_get_real);
  401. /**
  402. * getrawmonotonic - Returns the raw monotonic time in a timespec
  403. * @ts: pointer to the timespec to be set
  404. *
  405. * Returns the raw monotonic time (completely un-modified by ntp)
  406. */
  407. void getrawmonotonic(struct timespec *ts)
  408. {
  409. unsigned long seq;
  410. s64 nsecs;
  411. do {
  412. seq = read_seqbegin(&timekeeper.lock);
  413. nsecs = timekeeping_get_ns_raw();
  414. *ts = timekeeper.raw_time;
  415. } while (read_seqretry(&timekeeper.lock, seq));
  416. timespec_add_ns(ts, nsecs);
  417. }
  418. EXPORT_SYMBOL(getrawmonotonic);
  419. /**
  420. * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
  421. */
  422. int timekeeping_valid_for_hres(void)
  423. {
  424. unsigned long seq;
  425. int ret;
  426. do {
  427. seq = read_seqbegin(&timekeeper.lock);
  428. ret = timekeeper.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  429. } while (read_seqretry(&timekeeper.lock, seq));
  430. return ret;
  431. }
  432. /**
  433. * timekeeping_max_deferment - Returns max time the clocksource can be deferred
  434. */
  435. u64 timekeeping_max_deferment(void)
  436. {
  437. unsigned long seq;
  438. u64 ret;
  439. do {
  440. seq = read_seqbegin(&timekeeper.lock);
  441. ret = timekeeper.clock->max_idle_ns;
  442. } while (read_seqretry(&timekeeper.lock, seq));
  443. return ret;
  444. }
  445. /**
  446. * read_persistent_clock - Return time from the persistent clock.
  447. *
  448. * Weak dummy function for arches that do not yet support it.
  449. * Reads the time from the battery backed persistent clock.
  450. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  451. *
  452. * XXX - Do be sure to remove it once all arches implement it.
  453. */
  454. void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
  455. {
  456. ts->tv_sec = 0;
  457. ts->tv_nsec = 0;
  458. }
  459. /**
  460. * read_boot_clock - Return time of the system start.
  461. *
  462. * Weak dummy function for arches that do not yet support it.
  463. * Function to read the exact time the system has been started.
  464. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  465. *
  466. * XXX - Do be sure to remove it once all arches implement it.
  467. */
  468. void __attribute__((weak)) read_boot_clock(struct timespec *ts)
  469. {
  470. ts->tv_sec = 0;
  471. ts->tv_nsec = 0;
  472. }
  473. /*
  474. * timekeeping_init - Initializes the clocksource and common timekeeping values
  475. */
  476. void __init timekeeping_init(void)
  477. {
  478. struct clocksource *clock;
  479. unsigned long flags;
  480. struct timespec now, boot;
  481. read_persistent_clock(&now);
  482. read_boot_clock(&boot);
  483. seqlock_init(&timekeeper.lock);
  484. ntp_init();
  485. write_seqlock_irqsave(&timekeeper.lock, flags);
  486. clock = clocksource_default_clock();
  487. if (clock->enable)
  488. clock->enable(clock);
  489. timekeeper_setup_internals(clock);
  490. timekeeper.xtime.tv_sec = now.tv_sec;
  491. timekeeper.xtime.tv_nsec = now.tv_nsec;
  492. timekeeper.raw_time.tv_sec = 0;
  493. timekeeper.raw_time.tv_nsec = 0;
  494. if (boot.tv_sec == 0 && boot.tv_nsec == 0) {
  495. boot.tv_sec = timekeeper.xtime.tv_sec;
  496. boot.tv_nsec = timekeeper.xtime.tv_nsec;
  497. }
  498. set_normalized_timespec(&timekeeper.wall_to_monotonic,
  499. -boot.tv_sec, -boot.tv_nsec);
  500. timekeeper.total_sleep_time.tv_sec = 0;
  501. timekeeper.total_sleep_time.tv_nsec = 0;
  502. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  503. }
  504. /* time in seconds when suspend began */
  505. static struct timespec timekeeping_suspend_time;
  506. /**
  507. * __timekeeping_inject_sleeptime - Internal function to add sleep interval
  508. * @delta: pointer to a timespec delta value
  509. *
  510. * Takes a timespec offset measuring a suspend interval and properly
  511. * adds the sleep offset to the timekeeping variables.
  512. */
  513. static void __timekeeping_inject_sleeptime(struct timespec *delta)
  514. {
  515. if (!timespec_valid(delta)) {
  516. printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
  517. "sleep delta value!\n");
  518. return;
  519. }
  520. timekeeper.xtime = timespec_add(timekeeper.xtime, *delta);
  521. timekeeper.wall_to_monotonic =
  522. timespec_sub(timekeeper.wall_to_monotonic, *delta);
  523. timekeeper.total_sleep_time = timespec_add(
  524. timekeeper.total_sleep_time, *delta);
  525. }
  526. /**
  527. * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
  528. * @delta: pointer to a timespec delta value
  529. *
  530. * This hook is for architectures that cannot support read_persistent_clock
  531. * because their RTC/persistent clock is only accessible when irqs are enabled.
  532. *
  533. * This function should only be called by rtc_resume(), and allows
  534. * a suspend offset to be injected into the timekeeping values.
  535. */
  536. void timekeeping_inject_sleeptime(struct timespec *delta)
  537. {
  538. unsigned long flags;
  539. struct timespec ts;
  540. /* Make sure we don't set the clock twice */
  541. read_persistent_clock(&ts);
  542. if (!(ts.tv_sec == 0 && ts.tv_nsec == 0))
  543. return;
  544. write_seqlock_irqsave(&timekeeper.lock, flags);
  545. timekeeping_forward_now();
  546. __timekeeping_inject_sleeptime(delta);
  547. timekeeping_update(true);
  548. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  549. /* signal hrtimers about time change */
  550. clock_was_set();
  551. }
  552. /**
  553. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  554. *
  555. * This is for the generic clocksource timekeeping.
  556. * xtime/wall_to_monotonic/jiffies/etc are
  557. * still managed by arch specific suspend/resume code.
  558. */
  559. static void timekeeping_resume(void)
  560. {
  561. unsigned long flags;
  562. struct timespec ts;
  563. read_persistent_clock(&ts);
  564. clocksource_resume();
  565. write_seqlock_irqsave(&timekeeper.lock, flags);
  566. if (timespec_compare(&ts, &timekeeping_suspend_time) > 0) {
  567. ts = timespec_sub(ts, timekeeping_suspend_time);
  568. __timekeeping_inject_sleeptime(&ts);
  569. }
  570. /* re-base the last cycle value */
  571. timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
  572. timekeeper.ntp_error = 0;
  573. timekeeping_suspended = 0;
  574. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  575. touch_softlockup_watchdog();
  576. clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
  577. /* Resume hrtimers */
  578. hrtimers_resume();
  579. }
  580. static int timekeeping_suspend(void)
  581. {
  582. unsigned long flags;
  583. struct timespec delta, delta_delta;
  584. static struct timespec old_delta;
  585. read_persistent_clock(&timekeeping_suspend_time);
  586. write_seqlock_irqsave(&timekeeper.lock, flags);
  587. timekeeping_forward_now();
  588. timekeeping_suspended = 1;
  589. /*
  590. * To avoid drift caused by repeated suspend/resumes,
  591. * which each can add ~1 second drift error,
  592. * try to compensate so the difference in system time
  593. * and persistent_clock time stays close to constant.
  594. */
  595. delta = timespec_sub(timekeeper.xtime, timekeeping_suspend_time);
  596. delta_delta = timespec_sub(delta, old_delta);
  597. if (abs(delta_delta.tv_sec) >= 2) {
  598. /*
  599. * if delta_delta is too large, assume time correction
  600. * has occured and set old_delta to the current delta.
  601. */
  602. old_delta = delta;
  603. } else {
  604. /* Otherwise try to adjust old_system to compensate */
  605. timekeeping_suspend_time =
  606. timespec_add(timekeeping_suspend_time, delta_delta);
  607. }
  608. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  609. clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
  610. clocksource_suspend();
  611. return 0;
  612. }
  613. /* sysfs resume/suspend bits for timekeeping */
  614. static struct syscore_ops timekeeping_syscore_ops = {
  615. .resume = timekeeping_resume,
  616. .suspend = timekeeping_suspend,
  617. };
  618. static int __init timekeeping_init_ops(void)
  619. {
  620. register_syscore_ops(&timekeeping_syscore_ops);
  621. return 0;
  622. }
  623. device_initcall(timekeeping_init_ops);
  624. /*
  625. * If the error is already larger, we look ahead even further
  626. * to compensate for late or lost adjustments.
  627. */
  628. static __always_inline int timekeeping_bigadjust(s64 error, s64 *interval,
  629. s64 *offset)
  630. {
  631. s64 tick_error, i;
  632. u32 look_ahead, adj;
  633. s32 error2, mult;
  634. /*
  635. * Use the current error value to determine how much to look ahead.
  636. * The larger the error the slower we adjust for it to avoid problems
  637. * with losing too many ticks, otherwise we would overadjust and
  638. * produce an even larger error. The smaller the adjustment the
  639. * faster we try to adjust for it, as lost ticks can do less harm
  640. * here. This is tuned so that an error of about 1 msec is adjusted
  641. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  642. */
  643. error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
  644. error2 = abs(error2);
  645. for (look_ahead = 0; error2 > 0; look_ahead++)
  646. error2 >>= 2;
  647. /*
  648. * Now calculate the error in (1 << look_ahead) ticks, but first
  649. * remove the single look ahead already included in the error.
  650. */
  651. tick_error = ntp_tick_length() >> (timekeeper.ntp_error_shift + 1);
  652. tick_error -= timekeeper.xtime_interval >> 1;
  653. error = ((error - tick_error) >> look_ahead) + tick_error;
  654. /* Finally calculate the adjustment shift value. */
  655. i = *interval;
  656. mult = 1;
  657. if (error < 0) {
  658. error = -error;
  659. *interval = -*interval;
  660. *offset = -*offset;
  661. mult = -1;
  662. }
  663. for (adj = 0; error > i; adj++)
  664. error >>= 1;
  665. *interval <<= adj;
  666. *offset <<= adj;
  667. return mult << adj;
  668. }
  669. /*
  670. * Adjust the multiplier to reduce the error value,
  671. * this is optimized for the most common adjustments of -1,0,1,
  672. * for other values we can do a bit more work.
  673. */
  674. static void timekeeping_adjust(s64 offset)
  675. {
  676. s64 error, interval = timekeeper.cycle_interval;
  677. int adj;
  678. /*
  679. * The point of this is to check if the error is greater then half
  680. * an interval.
  681. *
  682. * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
  683. *
  684. * Note we subtract one in the shift, so that error is really error*2.
  685. * This "saves" dividing(shifting) interval twice, but keeps the
  686. * (error > interval) comparison as still measuring if error is
  687. * larger then half an interval.
  688. *
  689. * Note: It does not "save" on aggravation when reading the code.
  690. */
  691. error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
  692. if (error > interval) {
  693. /*
  694. * We now divide error by 4(via shift), which checks if
  695. * the error is greater then twice the interval.
  696. * If it is greater, we need a bigadjust, if its smaller,
  697. * we can adjust by 1.
  698. */
  699. error >>= 2;
  700. /*
  701. * XXX - In update_wall_time, we round up to the next
  702. * nanosecond, and store the amount rounded up into
  703. * the error. This causes the likely below to be unlikely.
  704. *
  705. * The proper fix is to avoid rounding up by using
  706. * the high precision timekeeper.xtime_nsec instead of
  707. * xtime.tv_nsec everywhere. Fixing this will take some
  708. * time.
  709. */
  710. if (likely(error <= interval))
  711. adj = 1;
  712. else
  713. adj = timekeeping_bigadjust(error, &interval, &offset);
  714. } else if (error < -interval) {
  715. /* See comment above, this is just switched for the negative */
  716. error >>= 2;
  717. if (likely(error >= -interval)) {
  718. adj = -1;
  719. interval = -interval;
  720. offset = -offset;
  721. } else
  722. adj = timekeeping_bigadjust(error, &interval, &offset);
  723. } else /* No adjustment needed */
  724. return;
  725. WARN_ONCE(timekeeper.clock->maxadj &&
  726. (timekeeper.mult + adj > timekeeper.clock->mult +
  727. timekeeper.clock->maxadj),
  728. "Adjusting %s more then 11%% (%ld vs %ld)\n",
  729. timekeeper.clock->name, (long)timekeeper.mult + adj,
  730. (long)timekeeper.clock->mult +
  731. timekeeper.clock->maxadj);
  732. /*
  733. * So the following can be confusing.
  734. *
  735. * To keep things simple, lets assume adj == 1 for now.
  736. *
  737. * When adj != 1, remember that the interval and offset values
  738. * have been appropriately scaled so the math is the same.
  739. *
  740. * The basic idea here is that we're increasing the multiplier
  741. * by one, this causes the xtime_interval to be incremented by
  742. * one cycle_interval. This is because:
  743. * xtime_interval = cycle_interval * mult
  744. * So if mult is being incremented by one:
  745. * xtime_interval = cycle_interval * (mult + 1)
  746. * Its the same as:
  747. * xtime_interval = (cycle_interval * mult) + cycle_interval
  748. * Which can be shortened to:
  749. * xtime_interval += cycle_interval
  750. *
  751. * So offset stores the non-accumulated cycles. Thus the current
  752. * time (in shifted nanoseconds) is:
  753. * now = (offset * adj) + xtime_nsec
  754. * Now, even though we're adjusting the clock frequency, we have
  755. * to keep time consistent. In other words, we can't jump back
  756. * in time, and we also want to avoid jumping forward in time.
  757. *
  758. * So given the same offset value, we need the time to be the same
  759. * both before and after the freq adjustment.
  760. * now = (offset * adj_1) + xtime_nsec_1
  761. * now = (offset * adj_2) + xtime_nsec_2
  762. * So:
  763. * (offset * adj_1) + xtime_nsec_1 =
  764. * (offset * adj_2) + xtime_nsec_2
  765. * And we know:
  766. * adj_2 = adj_1 + 1
  767. * So:
  768. * (offset * adj_1) + xtime_nsec_1 =
  769. * (offset * (adj_1+1)) + xtime_nsec_2
  770. * (offset * adj_1) + xtime_nsec_1 =
  771. * (offset * adj_1) + offset + xtime_nsec_2
  772. * Canceling the sides:
  773. * xtime_nsec_1 = offset + xtime_nsec_2
  774. * Which gives us:
  775. * xtime_nsec_2 = xtime_nsec_1 - offset
  776. * Which simplfies to:
  777. * xtime_nsec -= offset
  778. *
  779. * XXX - TODO: Doc ntp_error calculation.
  780. */
  781. timekeeper.mult += adj;
  782. timekeeper.xtime_interval += interval;
  783. timekeeper.xtime_nsec -= offset;
  784. timekeeper.ntp_error -= (interval - offset) <<
  785. timekeeper.ntp_error_shift;
  786. }
  787. /**
  788. * logarithmic_accumulation - shifted accumulation of cycles
  789. *
  790. * This functions accumulates a shifted interval of cycles into
  791. * into a shifted interval nanoseconds. Allows for O(log) accumulation
  792. * loop.
  793. *
  794. * Returns the unconsumed cycles.
  795. */
  796. static cycle_t logarithmic_accumulation(cycle_t offset, int shift)
  797. {
  798. u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
  799. u64 raw_nsecs;
  800. /* If the offset is smaller then a shifted interval, do nothing */
  801. if (offset < timekeeper.cycle_interval<<shift)
  802. return offset;
  803. /* Accumulate one shifted interval */
  804. offset -= timekeeper.cycle_interval << shift;
  805. timekeeper.clock->cycle_last += timekeeper.cycle_interval << shift;
  806. timekeeper.xtime_nsec += timekeeper.xtime_interval << shift;
  807. while (timekeeper.xtime_nsec >= nsecps) {
  808. timekeeper.xtime_nsec -= nsecps;
  809. timekeeper.xtime.tv_sec++;
  810. second_overflow();
  811. }
  812. /* Accumulate raw time */
  813. raw_nsecs = timekeeper.raw_interval << shift;
  814. raw_nsecs += timekeeper.raw_time.tv_nsec;
  815. if (raw_nsecs >= NSEC_PER_SEC) {
  816. u64 raw_secs = raw_nsecs;
  817. raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
  818. timekeeper.raw_time.tv_sec += raw_secs;
  819. }
  820. timekeeper.raw_time.tv_nsec = raw_nsecs;
  821. /* Accumulate error between NTP and clock interval */
  822. timekeeper.ntp_error += ntp_tick_length() << shift;
  823. timekeeper.ntp_error -=
  824. (timekeeper.xtime_interval + timekeeper.xtime_remainder) <<
  825. (timekeeper.ntp_error_shift + shift);
  826. return offset;
  827. }
  828. /**
  829. * update_wall_time - Uses the current clocksource to increment the wall time
  830. *
  831. */
  832. static void update_wall_time(void)
  833. {
  834. struct clocksource *clock;
  835. cycle_t offset;
  836. int shift = 0, maxshift;
  837. unsigned long flags;
  838. write_seqlock_irqsave(&timekeeper.lock, flags);
  839. /* Make sure we're fully resumed: */
  840. if (unlikely(timekeeping_suspended))
  841. goto out;
  842. clock = timekeeper.clock;
  843. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  844. offset = timekeeper.cycle_interval;
  845. #else
  846. offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
  847. #endif
  848. timekeeper.xtime_nsec = (s64)timekeeper.xtime.tv_nsec <<
  849. timekeeper.shift;
  850. /*
  851. * With NO_HZ we may have to accumulate many cycle_intervals
  852. * (think "ticks") worth of time at once. To do this efficiently,
  853. * we calculate the largest doubling multiple of cycle_intervals
  854. * that is smaller then the offset. We then accumulate that
  855. * chunk in one go, and then try to consume the next smaller
  856. * doubled multiple.
  857. */
  858. shift = ilog2(offset) - ilog2(timekeeper.cycle_interval);
  859. shift = max(0, shift);
  860. /* Bound shift to one less then what overflows tick_length */
  861. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  862. shift = min(shift, maxshift);
  863. while (offset >= timekeeper.cycle_interval) {
  864. offset = logarithmic_accumulation(offset, shift);
  865. if(offset < timekeeper.cycle_interval<<shift)
  866. shift--;
  867. }
  868. /* correct the clock when NTP error is too big */
  869. timekeeping_adjust(offset);
  870. /*
  871. * Since in the loop above, we accumulate any amount of time
  872. * in xtime_nsec over a second into xtime.tv_sec, its possible for
  873. * xtime_nsec to be fairly small after the loop. Further, if we're
  874. * slightly speeding the clocksource up in timekeeping_adjust(),
  875. * its possible the required corrective factor to xtime_nsec could
  876. * cause it to underflow.
  877. *
  878. * Now, we cannot simply roll the accumulated second back, since
  879. * the NTP subsystem has been notified via second_overflow. So
  880. * instead we push xtime_nsec forward by the amount we underflowed,
  881. * and add that amount into the error.
  882. *
  883. * We'll correct this error next time through this function, when
  884. * xtime_nsec is not as small.
  885. */
  886. if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
  887. s64 neg = -(s64)timekeeper.xtime_nsec;
  888. timekeeper.xtime_nsec = 0;
  889. timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
  890. }
  891. /*
  892. * Store full nanoseconds into xtime after rounding it up and
  893. * add the remainder to the error difference.
  894. */
  895. timekeeper.xtime.tv_nsec = ((s64)timekeeper.xtime_nsec >>
  896. timekeeper.shift) + 1;
  897. timekeeper.xtime_nsec -= (s64)timekeeper.xtime.tv_nsec <<
  898. timekeeper.shift;
  899. timekeeper.ntp_error += timekeeper.xtime_nsec <<
  900. timekeeper.ntp_error_shift;
  901. /*
  902. * Finally, make sure that after the rounding
  903. * xtime.tv_nsec isn't larger then NSEC_PER_SEC
  904. */
  905. if (unlikely(timekeeper.xtime.tv_nsec >= NSEC_PER_SEC)) {
  906. timekeeper.xtime.tv_nsec -= NSEC_PER_SEC;
  907. timekeeper.xtime.tv_sec++;
  908. second_overflow();
  909. }
  910. timekeeping_update(false);
  911. out:
  912. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  913. }
  914. /**
  915. * getboottime - Return the real time of system boot.
  916. * @ts: pointer to the timespec to be set
  917. *
  918. * Returns the wall-time of boot in a timespec.
  919. *
  920. * This is based on the wall_to_monotonic offset and the total suspend
  921. * time. Calls to settimeofday will affect the value returned (which
  922. * basically means that however wrong your real time clock is at boot time,
  923. * you get the right time here).
  924. */
  925. void getboottime(struct timespec *ts)
  926. {
  927. struct timespec boottime = {
  928. .tv_sec = timekeeper.wall_to_monotonic.tv_sec +
  929. timekeeper.total_sleep_time.tv_sec,
  930. .tv_nsec = timekeeper.wall_to_monotonic.tv_nsec +
  931. timekeeper.total_sleep_time.tv_nsec
  932. };
  933. set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
  934. }
  935. EXPORT_SYMBOL_GPL(getboottime);
  936. /**
  937. * get_monotonic_boottime - Returns monotonic time since boot
  938. * @ts: pointer to the timespec to be set
  939. *
  940. * Returns the monotonic time since boot in a timespec.
  941. *
  942. * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
  943. * includes the time spent in suspend.
  944. */
  945. void get_monotonic_boottime(struct timespec *ts)
  946. {
  947. struct timespec tomono, sleep;
  948. unsigned int seq;
  949. s64 nsecs;
  950. WARN_ON(timekeeping_suspended);
  951. do {
  952. seq = read_seqbegin(&timekeeper.lock);
  953. *ts = timekeeper.xtime;
  954. tomono = timekeeper.wall_to_monotonic;
  955. sleep = timekeeper.total_sleep_time;
  956. nsecs = timekeeping_get_ns();
  957. } while (read_seqretry(&timekeeper.lock, seq));
  958. set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec + sleep.tv_sec,
  959. ts->tv_nsec + tomono.tv_nsec + sleep.tv_nsec + nsecs);
  960. }
  961. EXPORT_SYMBOL_GPL(get_monotonic_boottime);
  962. /**
  963. * ktime_get_boottime - Returns monotonic time since boot in a ktime
  964. *
  965. * Returns the monotonic time since boot in a ktime
  966. *
  967. * This is similar to CLOCK_MONTONIC/ktime_get, but also
  968. * includes the time spent in suspend.
  969. */
  970. ktime_t ktime_get_boottime(void)
  971. {
  972. struct timespec ts;
  973. get_monotonic_boottime(&ts);
  974. return timespec_to_ktime(ts);
  975. }
  976. EXPORT_SYMBOL_GPL(ktime_get_boottime);
  977. /**
  978. * monotonic_to_bootbased - Convert the monotonic time to boot based.
  979. * @ts: pointer to the timespec to be converted
  980. */
  981. void monotonic_to_bootbased(struct timespec *ts)
  982. {
  983. *ts = timespec_add(*ts, timekeeper.total_sleep_time);
  984. }
  985. EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
  986. unsigned long get_seconds(void)
  987. {
  988. return timekeeper.xtime.tv_sec;
  989. }
  990. EXPORT_SYMBOL(get_seconds);
  991. struct timespec __current_kernel_time(void)
  992. {
  993. return timekeeper.xtime;
  994. }
  995. struct timespec current_kernel_time(void)
  996. {
  997. struct timespec now;
  998. unsigned long seq;
  999. do {
  1000. seq = read_seqbegin(&timekeeper.lock);
  1001. now = timekeeper.xtime;
  1002. } while (read_seqretry(&timekeeper.lock, seq));
  1003. return now;
  1004. }
  1005. EXPORT_SYMBOL(current_kernel_time);
  1006. struct timespec get_monotonic_coarse(void)
  1007. {
  1008. struct timespec now, mono;
  1009. unsigned long seq;
  1010. do {
  1011. seq = read_seqbegin(&timekeeper.lock);
  1012. now = timekeeper.xtime;
  1013. mono = timekeeper.wall_to_monotonic;
  1014. } while (read_seqretry(&timekeeper.lock, seq));
  1015. set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
  1016. now.tv_nsec + mono.tv_nsec);
  1017. return now;
  1018. }
  1019. /*
  1020. * The 64-bit jiffies value is not atomic - you MUST NOT read it
  1021. * without sampling the sequence number in xtime_lock.
  1022. * jiffies is defined in the linker script...
  1023. */
  1024. void do_timer(unsigned long ticks)
  1025. {
  1026. jiffies_64 += ticks;
  1027. update_wall_time();
  1028. calc_global_load(ticks);
  1029. }
  1030. /**
  1031. * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
  1032. * and sleep offsets.
  1033. * @xtim: pointer to timespec to be set with xtime
  1034. * @wtom: pointer to timespec to be set with wall_to_monotonic
  1035. * @sleep: pointer to timespec to be set with time in suspend
  1036. */
  1037. void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
  1038. struct timespec *wtom, struct timespec *sleep)
  1039. {
  1040. unsigned long seq;
  1041. do {
  1042. seq = read_seqbegin(&timekeeper.lock);
  1043. *xtim = timekeeper.xtime;
  1044. *wtom = timekeeper.wall_to_monotonic;
  1045. *sleep = timekeeper.total_sleep_time;
  1046. } while (read_seqretry(&timekeeper.lock, seq));
  1047. }
  1048. /**
  1049. * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
  1050. */
  1051. ktime_t ktime_get_monotonic_offset(void)
  1052. {
  1053. unsigned long seq;
  1054. struct timespec wtom;
  1055. do {
  1056. seq = read_seqbegin(&timekeeper.lock);
  1057. wtom = timekeeper.wall_to_monotonic;
  1058. } while (read_seqretry(&timekeeper.lock, seq));
  1059. return timespec_to_ktime(wtom);
  1060. }
  1061. /**
  1062. * xtime_update() - advances the timekeeping infrastructure
  1063. * @ticks: number of ticks, that have elapsed since the last call.
  1064. *
  1065. * Must be called with interrupts disabled.
  1066. */
  1067. void xtime_update(unsigned long ticks)
  1068. {
  1069. write_seqlock(&xtime_lock);
  1070. do_timer(ticks);
  1071. write_sequnlock(&xtime_lock);
  1072. }