timekeeping.c 34 KB

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