timekeeping.c 34 KB

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