timekeeping.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  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. new = (struct clocksource *) data;
  362. timekeeping_forward_now();
  363. if (!new->enable || new->enable(new) == 0) {
  364. old = timekeeper.clock;
  365. timekeeper_setup_internals(new);
  366. if (old->disable)
  367. old->disable(old);
  368. }
  369. return 0;
  370. }
  371. /**
  372. * timekeeping_notify - Install a new clock source
  373. * @clock: pointer to the clock source
  374. *
  375. * This function is called from clocksource.c after a new, better clock
  376. * source has been registered. The caller holds the clocksource_mutex.
  377. */
  378. void timekeeping_notify(struct clocksource *clock)
  379. {
  380. if (timekeeper.clock == clock)
  381. return;
  382. stop_machine(change_clocksource, clock, NULL);
  383. tick_clock_notify();
  384. }
  385. /**
  386. * ktime_get_real - get the real (wall-) time in ktime_t format
  387. *
  388. * returns the time in ktime_t format
  389. */
  390. ktime_t ktime_get_real(void)
  391. {
  392. struct timespec now;
  393. getnstimeofday(&now);
  394. return timespec_to_ktime(now);
  395. }
  396. EXPORT_SYMBOL_GPL(ktime_get_real);
  397. /**
  398. * getrawmonotonic - Returns the raw monotonic time in a timespec
  399. * @ts: pointer to the timespec to be set
  400. *
  401. * Returns the raw monotonic time (completely un-modified by ntp)
  402. */
  403. void getrawmonotonic(struct timespec *ts)
  404. {
  405. unsigned long seq;
  406. s64 nsecs;
  407. do {
  408. seq = read_seqbegin(&timekeeper.lock);
  409. nsecs = timekeeping_get_ns_raw();
  410. *ts = timekeeper.raw_time;
  411. } while (read_seqretry(&timekeeper.lock, seq));
  412. timespec_add_ns(ts, nsecs);
  413. }
  414. EXPORT_SYMBOL(getrawmonotonic);
  415. /**
  416. * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
  417. */
  418. int timekeeping_valid_for_hres(void)
  419. {
  420. unsigned long seq;
  421. int ret;
  422. do {
  423. seq = read_seqbegin(&timekeeper.lock);
  424. ret = timekeeper.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  425. } while (read_seqretry(&timekeeper.lock, seq));
  426. return ret;
  427. }
  428. /**
  429. * timekeeping_max_deferment - Returns max time the clocksource can be deferred
  430. */
  431. u64 timekeeping_max_deferment(void)
  432. {
  433. unsigned long seq;
  434. u64 ret;
  435. do {
  436. seq = read_seqbegin(&timekeeper.lock);
  437. ret = timekeeper.clock->max_idle_ns;
  438. } while (read_seqretry(&timekeeper.lock, seq));
  439. return ret;
  440. }
  441. /**
  442. * read_persistent_clock - Return time from the persistent clock.
  443. *
  444. * Weak dummy function for arches that do not yet support it.
  445. * Reads the time from the battery backed persistent clock.
  446. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  447. *
  448. * XXX - Do be sure to remove it once all arches implement it.
  449. */
  450. void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
  451. {
  452. ts->tv_sec = 0;
  453. ts->tv_nsec = 0;
  454. }
  455. /**
  456. * read_boot_clock - Return time of the system start.
  457. *
  458. * Weak dummy function for arches that do not yet support it.
  459. * Function to read the exact time the system has been started.
  460. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  461. *
  462. * XXX - Do be sure to remove it once all arches implement it.
  463. */
  464. void __attribute__((weak)) read_boot_clock(struct timespec *ts)
  465. {
  466. ts->tv_sec = 0;
  467. ts->tv_nsec = 0;
  468. }
  469. /*
  470. * timekeeping_init - Initializes the clocksource and common timekeeping values
  471. */
  472. void __init timekeeping_init(void)
  473. {
  474. struct clocksource *clock;
  475. unsigned long flags;
  476. struct timespec now, boot;
  477. read_persistent_clock(&now);
  478. read_boot_clock(&boot);
  479. seqlock_init(&timekeeper.lock);
  480. ntp_init();
  481. write_seqlock_irqsave(&timekeeper.lock, flags);
  482. clock = clocksource_default_clock();
  483. if (clock->enable)
  484. clock->enable(clock);
  485. timekeeper_setup_internals(clock);
  486. timekeeper.xtime.tv_sec = now.tv_sec;
  487. timekeeper.xtime.tv_nsec = now.tv_nsec;
  488. timekeeper.raw_time.tv_sec = 0;
  489. timekeeper.raw_time.tv_nsec = 0;
  490. if (boot.tv_sec == 0 && boot.tv_nsec == 0) {
  491. boot.tv_sec = timekeeper.xtime.tv_sec;
  492. boot.tv_nsec = timekeeper.xtime.tv_nsec;
  493. }
  494. set_normalized_timespec(&timekeeper.wall_to_monotonic,
  495. -boot.tv_sec, -boot.tv_nsec);
  496. timekeeper.total_sleep_time.tv_sec = 0;
  497. timekeeper.total_sleep_time.tv_nsec = 0;
  498. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  499. }
  500. /* time in seconds when suspend began */
  501. static struct timespec timekeeping_suspend_time;
  502. /**
  503. * __timekeeping_inject_sleeptime - Internal function to add sleep interval
  504. * @delta: pointer to a timespec delta value
  505. *
  506. * Takes a timespec offset measuring a suspend interval and properly
  507. * adds the sleep offset to the timekeeping variables.
  508. */
  509. static void __timekeeping_inject_sleeptime(struct timespec *delta)
  510. {
  511. if (!timespec_valid(delta)) {
  512. printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
  513. "sleep delta value!\n");
  514. return;
  515. }
  516. timekeeper.xtime = timespec_add(timekeeper.xtime, *delta);
  517. timekeeper.wall_to_monotonic =
  518. timespec_sub(timekeeper.wall_to_monotonic, *delta);
  519. timekeeper.total_sleep_time = timespec_add(
  520. timekeeper.total_sleep_time, *delta);
  521. }
  522. /**
  523. * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
  524. * @delta: pointer to a timespec delta value
  525. *
  526. * This hook is for architectures that cannot support read_persistent_clock
  527. * because their RTC/persistent clock is only accessible when irqs are enabled.
  528. *
  529. * This function should only be called by rtc_resume(), and allows
  530. * a suspend offset to be injected into the timekeeping values.
  531. */
  532. void timekeeping_inject_sleeptime(struct timespec *delta)
  533. {
  534. unsigned long flags;
  535. struct timespec ts;
  536. /* Make sure we don't set the clock twice */
  537. read_persistent_clock(&ts);
  538. if (!(ts.tv_sec == 0 && ts.tv_nsec == 0))
  539. return;
  540. write_seqlock_irqsave(&timekeeper.lock, flags);
  541. timekeeping_forward_now();
  542. __timekeeping_inject_sleeptime(delta);
  543. timekeeping_update(true);
  544. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  545. /* signal hrtimers about time change */
  546. clock_was_set();
  547. }
  548. /**
  549. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  550. *
  551. * This is for the generic clocksource timekeeping.
  552. * xtime/wall_to_monotonic/jiffies/etc are
  553. * still managed by arch specific suspend/resume code.
  554. */
  555. static void timekeeping_resume(void)
  556. {
  557. unsigned long flags;
  558. struct timespec ts;
  559. read_persistent_clock(&ts);
  560. clocksource_resume();
  561. write_seqlock_irqsave(&timekeeper.lock, flags);
  562. if (timespec_compare(&ts, &timekeeping_suspend_time) > 0) {
  563. ts = timespec_sub(ts, timekeeping_suspend_time);
  564. __timekeeping_inject_sleeptime(&ts);
  565. }
  566. /* re-base the last cycle value */
  567. timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
  568. timekeeper.ntp_error = 0;
  569. timekeeping_suspended = 0;
  570. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  571. touch_softlockup_watchdog();
  572. clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
  573. /* Resume hrtimers */
  574. hrtimers_resume();
  575. }
  576. static int timekeeping_suspend(void)
  577. {
  578. unsigned long flags;
  579. struct timespec delta, delta_delta;
  580. static struct timespec old_delta;
  581. read_persistent_clock(&timekeeping_suspend_time);
  582. write_seqlock_irqsave(&timekeeper.lock, flags);
  583. timekeeping_forward_now();
  584. timekeeping_suspended = 1;
  585. /*
  586. * To avoid drift caused by repeated suspend/resumes,
  587. * which each can add ~1 second drift error,
  588. * try to compensate so the difference in system time
  589. * and persistent_clock time stays close to constant.
  590. */
  591. delta = timespec_sub(timekeeper.xtime, timekeeping_suspend_time);
  592. delta_delta = timespec_sub(delta, old_delta);
  593. if (abs(delta_delta.tv_sec) >= 2) {
  594. /*
  595. * if delta_delta is too large, assume time correction
  596. * has occured and set old_delta to the current delta.
  597. */
  598. old_delta = delta;
  599. } else {
  600. /* Otherwise try to adjust old_system to compensate */
  601. timekeeping_suspend_time =
  602. timespec_add(timekeeping_suspend_time, delta_delta);
  603. }
  604. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  605. clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
  606. clocksource_suspend();
  607. return 0;
  608. }
  609. /* sysfs resume/suspend bits for timekeeping */
  610. static struct syscore_ops timekeeping_syscore_ops = {
  611. .resume = timekeeping_resume,
  612. .suspend = timekeeping_suspend,
  613. };
  614. static int __init timekeeping_init_ops(void)
  615. {
  616. register_syscore_ops(&timekeeping_syscore_ops);
  617. return 0;
  618. }
  619. device_initcall(timekeeping_init_ops);
  620. /*
  621. * If the error is already larger, we look ahead even further
  622. * to compensate for late or lost adjustments.
  623. */
  624. static __always_inline int timekeeping_bigadjust(s64 error, s64 *interval,
  625. s64 *offset)
  626. {
  627. s64 tick_error, i;
  628. u32 look_ahead, adj;
  629. s32 error2, mult;
  630. /*
  631. * Use the current error value to determine how much to look ahead.
  632. * The larger the error the slower we adjust for it to avoid problems
  633. * with losing too many ticks, otherwise we would overadjust and
  634. * produce an even larger error. The smaller the adjustment the
  635. * faster we try to adjust for it, as lost ticks can do less harm
  636. * here. This is tuned so that an error of about 1 msec is adjusted
  637. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  638. */
  639. error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
  640. error2 = abs(error2);
  641. for (look_ahead = 0; error2 > 0; look_ahead++)
  642. error2 >>= 2;
  643. /*
  644. * Now calculate the error in (1 << look_ahead) ticks, but first
  645. * remove the single look ahead already included in the error.
  646. */
  647. tick_error = ntp_tick_length() >> (timekeeper.ntp_error_shift + 1);
  648. tick_error -= timekeeper.xtime_interval >> 1;
  649. error = ((error - tick_error) >> look_ahead) + tick_error;
  650. /* Finally calculate the adjustment shift value. */
  651. i = *interval;
  652. mult = 1;
  653. if (error < 0) {
  654. error = -error;
  655. *interval = -*interval;
  656. *offset = -*offset;
  657. mult = -1;
  658. }
  659. for (adj = 0; error > i; adj++)
  660. error >>= 1;
  661. *interval <<= adj;
  662. *offset <<= adj;
  663. return mult << adj;
  664. }
  665. /*
  666. * Adjust the multiplier to reduce the error value,
  667. * this is optimized for the most common adjustments of -1,0,1,
  668. * for other values we can do a bit more work.
  669. */
  670. static void timekeeping_adjust(s64 offset)
  671. {
  672. s64 error, interval = timekeeper.cycle_interval;
  673. int adj;
  674. /*
  675. * The point of this is to check if the error is greater then half
  676. * an interval.
  677. *
  678. * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
  679. *
  680. * Note we subtract one in the shift, so that error is really error*2.
  681. * This "saves" dividing(shifting) interval twice, but keeps the
  682. * (error > interval) comparison as still measuring if error is
  683. * larger then half an interval.
  684. *
  685. * Note: It does not "save" on aggravation when reading the code.
  686. */
  687. error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
  688. if (error > interval) {
  689. /*
  690. * We now divide error by 4(via shift), which checks if
  691. * the error is greater then twice the interval.
  692. * If it is greater, we need a bigadjust, if its smaller,
  693. * we can adjust by 1.
  694. */
  695. error >>= 2;
  696. /*
  697. * XXX - In update_wall_time, we round up to the next
  698. * nanosecond, and store the amount rounded up into
  699. * the error. This causes the likely below to be unlikely.
  700. *
  701. * The proper fix is to avoid rounding up by using
  702. * the high precision timekeeper.xtime_nsec instead of
  703. * xtime.tv_nsec everywhere. Fixing this will take some
  704. * time.
  705. */
  706. if (likely(error <= interval))
  707. adj = 1;
  708. else
  709. adj = timekeeping_bigadjust(error, &interval, &offset);
  710. } else if (error < -interval) {
  711. /* See comment above, this is just switched for the negative */
  712. error >>= 2;
  713. if (likely(error >= -interval)) {
  714. adj = -1;
  715. interval = -interval;
  716. offset = -offset;
  717. } else
  718. adj = timekeeping_bigadjust(error, &interval, &offset);
  719. } else /* No adjustment needed */
  720. return;
  721. WARN_ONCE(timekeeper.clock->maxadj &&
  722. (timekeeper.mult + adj > timekeeper.clock->mult +
  723. timekeeper.clock->maxadj),
  724. "Adjusting %s more then 11%% (%ld vs %ld)\n",
  725. timekeeper.clock->name, (long)timekeeper.mult + adj,
  726. (long)timekeeper.clock->mult +
  727. timekeeper.clock->maxadj);
  728. /*
  729. * So the following can be confusing.
  730. *
  731. * To keep things simple, lets assume adj == 1 for now.
  732. *
  733. * When adj != 1, remember that the interval and offset values
  734. * have been appropriately scaled so the math is the same.
  735. *
  736. * The basic idea here is that we're increasing the multiplier
  737. * by one, this causes the xtime_interval to be incremented by
  738. * one cycle_interval. This is because:
  739. * xtime_interval = cycle_interval * mult
  740. * So if mult is being incremented by one:
  741. * xtime_interval = cycle_interval * (mult + 1)
  742. * Its the same as:
  743. * xtime_interval = (cycle_interval * mult) + cycle_interval
  744. * Which can be shortened to:
  745. * xtime_interval += cycle_interval
  746. *
  747. * So offset stores the non-accumulated cycles. Thus the current
  748. * time (in shifted nanoseconds) is:
  749. * now = (offset * adj) + xtime_nsec
  750. * Now, even though we're adjusting the clock frequency, we have
  751. * to keep time consistent. In other words, we can't jump back
  752. * in time, and we also want to avoid jumping forward in time.
  753. *
  754. * So given the same offset value, we need the time to be the same
  755. * both before and after the freq adjustment.
  756. * now = (offset * adj_1) + xtime_nsec_1
  757. * now = (offset * adj_2) + xtime_nsec_2
  758. * So:
  759. * (offset * adj_1) + xtime_nsec_1 =
  760. * (offset * adj_2) + xtime_nsec_2
  761. * And we know:
  762. * adj_2 = adj_1 + 1
  763. * So:
  764. * (offset * adj_1) + xtime_nsec_1 =
  765. * (offset * (adj_1+1)) + xtime_nsec_2
  766. * (offset * adj_1) + xtime_nsec_1 =
  767. * (offset * adj_1) + offset + xtime_nsec_2
  768. * Canceling the sides:
  769. * xtime_nsec_1 = offset + xtime_nsec_2
  770. * Which gives us:
  771. * xtime_nsec_2 = xtime_nsec_1 - offset
  772. * Which simplfies to:
  773. * xtime_nsec -= offset
  774. *
  775. * XXX - TODO: Doc ntp_error calculation.
  776. */
  777. timekeeper.mult += adj;
  778. timekeeper.xtime_interval += interval;
  779. timekeeper.xtime_nsec -= offset;
  780. timekeeper.ntp_error -= (interval - offset) <<
  781. timekeeper.ntp_error_shift;
  782. }
  783. /**
  784. * logarithmic_accumulation - shifted accumulation of cycles
  785. *
  786. * This functions accumulates a shifted interval of cycles into
  787. * into a shifted interval nanoseconds. Allows for O(log) accumulation
  788. * loop.
  789. *
  790. * Returns the unconsumed cycles.
  791. */
  792. static cycle_t logarithmic_accumulation(cycle_t offset, int shift)
  793. {
  794. u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
  795. u64 raw_nsecs;
  796. /* If the offset is smaller then a shifted interval, do nothing */
  797. if (offset < timekeeper.cycle_interval<<shift)
  798. return offset;
  799. /* Accumulate one shifted interval */
  800. offset -= timekeeper.cycle_interval << shift;
  801. timekeeper.clock->cycle_last += timekeeper.cycle_interval << shift;
  802. timekeeper.xtime_nsec += timekeeper.xtime_interval << shift;
  803. while (timekeeper.xtime_nsec >= nsecps) {
  804. timekeeper.xtime_nsec -= nsecps;
  805. timekeeper.xtime.tv_sec++;
  806. second_overflow();
  807. }
  808. /* Accumulate raw time */
  809. raw_nsecs = timekeeper.raw_interval << shift;
  810. raw_nsecs += timekeeper.raw_time.tv_nsec;
  811. if (raw_nsecs >= NSEC_PER_SEC) {
  812. u64 raw_secs = raw_nsecs;
  813. raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
  814. timekeeper.raw_time.tv_sec += raw_secs;
  815. }
  816. timekeeper.raw_time.tv_nsec = raw_nsecs;
  817. /* Accumulate error between NTP and clock interval */
  818. timekeeper.ntp_error += ntp_tick_length() << shift;
  819. timekeeper.ntp_error -=
  820. (timekeeper.xtime_interval + timekeeper.xtime_remainder) <<
  821. (timekeeper.ntp_error_shift + shift);
  822. return offset;
  823. }
  824. /**
  825. * update_wall_time - Uses the current clocksource to increment the wall time
  826. *
  827. */
  828. static void update_wall_time(void)
  829. {
  830. struct clocksource *clock;
  831. cycle_t offset;
  832. int shift = 0, maxshift;
  833. unsigned long flags;
  834. write_seqlock_irqsave(&timekeeper.lock, flags);
  835. /* Make sure we're fully resumed: */
  836. if (unlikely(timekeeping_suspended))
  837. goto out;
  838. clock = timekeeper.clock;
  839. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  840. offset = timekeeper.cycle_interval;
  841. #else
  842. offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
  843. #endif
  844. timekeeper.xtime_nsec = (s64)timekeeper.xtime.tv_nsec <<
  845. timekeeper.shift;
  846. /*
  847. * With NO_HZ we may have to accumulate many cycle_intervals
  848. * (think "ticks") worth of time at once. To do this efficiently,
  849. * we calculate the largest doubling multiple of cycle_intervals
  850. * that is smaller then the offset. We then accumulate that
  851. * chunk in one go, and then try to consume the next smaller
  852. * doubled multiple.
  853. */
  854. shift = ilog2(offset) - ilog2(timekeeper.cycle_interval);
  855. shift = max(0, shift);
  856. /* Bound shift to one less then what overflows tick_length */
  857. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  858. shift = min(shift, maxshift);
  859. while (offset >= timekeeper.cycle_interval) {
  860. offset = logarithmic_accumulation(offset, shift);
  861. if(offset < timekeeper.cycle_interval<<shift)
  862. shift--;
  863. }
  864. /* correct the clock when NTP error is too big */
  865. timekeeping_adjust(offset);
  866. /*
  867. * Since in the loop above, we accumulate any amount of time
  868. * in xtime_nsec over a second into xtime.tv_sec, its possible for
  869. * xtime_nsec to be fairly small after the loop. Further, if we're
  870. * slightly speeding the clocksource up in timekeeping_adjust(),
  871. * its possible the required corrective factor to xtime_nsec could
  872. * cause it to underflow.
  873. *
  874. * Now, we cannot simply roll the accumulated second back, since
  875. * the NTP subsystem has been notified via second_overflow. So
  876. * instead we push xtime_nsec forward by the amount we underflowed,
  877. * and add that amount into the error.
  878. *
  879. * We'll correct this error next time through this function, when
  880. * xtime_nsec is not as small.
  881. */
  882. if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
  883. s64 neg = -(s64)timekeeper.xtime_nsec;
  884. timekeeper.xtime_nsec = 0;
  885. timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
  886. }
  887. /*
  888. * Store full nanoseconds into xtime after rounding it up and
  889. * add the remainder to the error difference.
  890. */
  891. timekeeper.xtime.tv_nsec = ((s64)timekeeper.xtime_nsec >>
  892. timekeeper.shift) + 1;
  893. timekeeper.xtime_nsec -= (s64)timekeeper.xtime.tv_nsec <<
  894. timekeeper.shift;
  895. timekeeper.ntp_error += timekeeper.xtime_nsec <<
  896. timekeeper.ntp_error_shift;
  897. /*
  898. * Finally, make sure that after the rounding
  899. * xtime.tv_nsec isn't larger then NSEC_PER_SEC
  900. */
  901. if (unlikely(timekeeper.xtime.tv_nsec >= NSEC_PER_SEC)) {
  902. timekeeper.xtime.tv_nsec -= NSEC_PER_SEC;
  903. timekeeper.xtime.tv_sec++;
  904. second_overflow();
  905. }
  906. timekeeping_update(false);
  907. out:
  908. write_sequnlock_irqrestore(&timekeeper.lock, flags);
  909. }
  910. /**
  911. * getboottime - Return the real time of system boot.
  912. * @ts: pointer to the timespec to be set
  913. *
  914. * Returns the wall-time of boot in a timespec.
  915. *
  916. * This is based on the wall_to_monotonic offset and the total suspend
  917. * time. Calls to settimeofday will affect the value returned (which
  918. * basically means that however wrong your real time clock is at boot time,
  919. * you get the right time here).
  920. */
  921. void getboottime(struct timespec *ts)
  922. {
  923. struct timespec boottime = {
  924. .tv_sec = timekeeper.wall_to_monotonic.tv_sec +
  925. timekeeper.total_sleep_time.tv_sec,
  926. .tv_nsec = timekeeper.wall_to_monotonic.tv_nsec +
  927. timekeeper.total_sleep_time.tv_nsec
  928. };
  929. set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
  930. }
  931. EXPORT_SYMBOL_GPL(getboottime);
  932. /**
  933. * get_monotonic_boottime - Returns monotonic time since boot
  934. * @ts: pointer to the timespec to be set
  935. *
  936. * Returns the monotonic time since boot in a timespec.
  937. *
  938. * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
  939. * includes the time spent in suspend.
  940. */
  941. void get_monotonic_boottime(struct timespec *ts)
  942. {
  943. struct timespec tomono, sleep;
  944. unsigned int seq;
  945. s64 nsecs;
  946. WARN_ON(timekeeping_suspended);
  947. do {
  948. seq = read_seqbegin(&timekeeper.lock);
  949. *ts = timekeeper.xtime;
  950. tomono = timekeeper.wall_to_monotonic;
  951. sleep = timekeeper.total_sleep_time;
  952. nsecs = timekeeping_get_ns();
  953. } while (read_seqretry(&timekeeper.lock, seq));
  954. set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec + sleep.tv_sec,
  955. ts->tv_nsec + tomono.tv_nsec + sleep.tv_nsec + nsecs);
  956. }
  957. EXPORT_SYMBOL_GPL(get_monotonic_boottime);
  958. /**
  959. * ktime_get_boottime - Returns monotonic time since boot in a ktime
  960. *
  961. * Returns the monotonic time since boot in a ktime
  962. *
  963. * This is similar to CLOCK_MONTONIC/ktime_get, but also
  964. * includes the time spent in suspend.
  965. */
  966. ktime_t ktime_get_boottime(void)
  967. {
  968. struct timespec ts;
  969. get_monotonic_boottime(&ts);
  970. return timespec_to_ktime(ts);
  971. }
  972. EXPORT_SYMBOL_GPL(ktime_get_boottime);
  973. /**
  974. * monotonic_to_bootbased - Convert the monotonic time to boot based.
  975. * @ts: pointer to the timespec to be converted
  976. */
  977. void monotonic_to_bootbased(struct timespec *ts)
  978. {
  979. *ts = timespec_add(*ts, timekeeper.total_sleep_time);
  980. }
  981. EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
  982. unsigned long get_seconds(void)
  983. {
  984. return timekeeper.xtime.tv_sec;
  985. }
  986. EXPORT_SYMBOL(get_seconds);
  987. struct timespec __current_kernel_time(void)
  988. {
  989. return timekeeper.xtime;
  990. }
  991. struct timespec current_kernel_time(void)
  992. {
  993. struct timespec now;
  994. unsigned long seq;
  995. do {
  996. seq = read_seqbegin(&timekeeper.lock);
  997. now = timekeeper.xtime;
  998. } while (read_seqretry(&timekeeper.lock, seq));
  999. return now;
  1000. }
  1001. EXPORT_SYMBOL(current_kernel_time);
  1002. struct timespec get_monotonic_coarse(void)
  1003. {
  1004. struct timespec now, mono;
  1005. unsigned long seq;
  1006. do {
  1007. seq = read_seqbegin(&timekeeper.lock);
  1008. now = timekeeper.xtime;
  1009. mono = timekeeper.wall_to_monotonic;
  1010. } while (read_seqretry(&timekeeper.lock, seq));
  1011. set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
  1012. now.tv_nsec + mono.tv_nsec);
  1013. return now;
  1014. }
  1015. /*
  1016. * The 64-bit jiffies value is not atomic - you MUST NOT read it
  1017. * without sampling the sequence number in xtime_lock.
  1018. * jiffies is defined in the linker script...
  1019. */
  1020. void do_timer(unsigned long ticks)
  1021. {
  1022. jiffies_64 += ticks;
  1023. update_wall_time();
  1024. calc_global_load(ticks);
  1025. }
  1026. /**
  1027. * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
  1028. * and sleep offsets.
  1029. * @xtim: pointer to timespec to be set with xtime
  1030. * @wtom: pointer to timespec to be set with wall_to_monotonic
  1031. * @sleep: pointer to timespec to be set with time in suspend
  1032. */
  1033. void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
  1034. struct timespec *wtom, struct timespec *sleep)
  1035. {
  1036. unsigned long seq;
  1037. do {
  1038. seq = read_seqbegin(&timekeeper.lock);
  1039. *xtim = timekeeper.xtime;
  1040. *wtom = timekeeper.wall_to_monotonic;
  1041. *sleep = timekeeper.total_sleep_time;
  1042. } while (read_seqretry(&timekeeper.lock, seq));
  1043. }
  1044. /**
  1045. * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
  1046. */
  1047. ktime_t ktime_get_monotonic_offset(void)
  1048. {
  1049. unsigned long seq;
  1050. struct timespec wtom;
  1051. do {
  1052. seq = read_seqbegin(&timekeeper.lock);
  1053. wtom = timekeeper.wall_to_monotonic;
  1054. } while (read_seqretry(&timekeeper.lock, seq));
  1055. return timespec_to_ktime(wtom);
  1056. }
  1057. EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
  1058. /**
  1059. * xtime_update() - advances the timekeeping infrastructure
  1060. * @ticks: number of ticks, that have elapsed since the last call.
  1061. *
  1062. * Must be called with interrupts disabled.
  1063. */
  1064. void xtime_update(unsigned long ticks)
  1065. {
  1066. write_seqlock(&xtime_lock);
  1067. do_timer(ticks);
  1068. write_sequnlock(&xtime_lock);
  1069. }