timekeeping.c 34 KB

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