timekeeping.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  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/timekeeper_internal.h>
  11. #include <linux/module.h>
  12. #include <linux/interrupt.h>
  13. #include <linux/percpu.h>
  14. #include <linux/init.h>
  15. #include <linux/mm.h>
  16. #include <linux/sched.h>
  17. #include <linux/syscore_ops.h>
  18. #include <linux/clocksource.h>
  19. #include <linux/jiffies.h>
  20. #include <linux/time.h>
  21. #include <linux/tick.h>
  22. #include <linux/stop_machine.h>
  23. #include <linux/pvclock_gtod.h>
  24. #include <linux/compiler.h>
  25. #include "tick-internal.h"
  26. #include "ntp_internal.h"
  27. #include "timekeeping_internal.h"
  28. #define TK_CLEAR_NTP (1 << 0)
  29. #define TK_MIRROR (1 << 1)
  30. #define TK_CLOCK_WAS_SET (1 << 2)
  31. /*
  32. * The most important data for readout fits into a single 64 byte
  33. * cache line.
  34. */
  35. static struct {
  36. seqcount_t seq;
  37. struct timekeeper timekeeper;
  38. } tk_core ____cacheline_aligned;
  39. static DEFINE_RAW_SPINLOCK(timekeeper_lock);
  40. static struct timekeeper shadow_timekeeper;
  41. /**
  42. * struct tk_fast - NMI safe timekeeper
  43. * @seq: Sequence counter for protecting updates. The lowest bit
  44. * is the index for the tk_read_base array
  45. * @base: tk_read_base array. Access is indexed by the lowest bit of
  46. * @seq.
  47. *
  48. * See @update_fast_timekeeper() below.
  49. */
  50. struct tk_fast {
  51. seqcount_t seq;
  52. struct tk_read_base base[2];
  53. };
  54. static struct tk_fast tk_fast_mono ____cacheline_aligned;
  55. /* flag for if timekeeping is suspended */
  56. int __read_mostly timekeeping_suspended;
  57. /* Flag for if there is a persistent clock on this platform */
  58. bool __read_mostly persistent_clock_exist = false;
  59. static inline void tk_normalize_xtime(struct timekeeper *tk)
  60. {
  61. while (tk->tkr.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr.shift)) {
  62. tk->tkr.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr.shift;
  63. tk->xtime_sec++;
  64. }
  65. }
  66. static inline struct timespec64 tk_xtime(struct timekeeper *tk)
  67. {
  68. struct timespec64 ts;
  69. ts.tv_sec = tk->xtime_sec;
  70. ts.tv_nsec = (long)(tk->tkr.xtime_nsec >> tk->tkr.shift);
  71. return ts;
  72. }
  73. static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
  74. {
  75. tk->xtime_sec = ts->tv_sec;
  76. tk->tkr.xtime_nsec = (u64)ts->tv_nsec << tk->tkr.shift;
  77. }
  78. static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
  79. {
  80. tk->xtime_sec += ts->tv_sec;
  81. tk->tkr.xtime_nsec += (u64)ts->tv_nsec << tk->tkr.shift;
  82. tk_normalize_xtime(tk);
  83. }
  84. static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
  85. {
  86. struct timespec64 tmp;
  87. /*
  88. * Verify consistency of: offset_real = -wall_to_monotonic
  89. * before modifying anything
  90. */
  91. set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
  92. -tk->wall_to_monotonic.tv_nsec);
  93. WARN_ON_ONCE(tk->offs_real.tv64 != timespec64_to_ktime(tmp).tv64);
  94. tk->wall_to_monotonic = wtm;
  95. set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
  96. tk->offs_real = timespec64_to_ktime(tmp);
  97. tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
  98. }
  99. static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
  100. {
  101. tk->offs_boot = ktime_add(tk->offs_boot, delta);
  102. }
  103. /**
  104. * tk_setup_internals - Set up internals to use clocksource clock.
  105. *
  106. * @tk: The target timekeeper to setup.
  107. * @clock: Pointer to clocksource.
  108. *
  109. * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
  110. * pair and interval request.
  111. *
  112. * Unless you're the timekeeping code, you should not be using this!
  113. */
  114. static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
  115. {
  116. cycle_t interval;
  117. u64 tmp, ntpinterval;
  118. struct clocksource *old_clock;
  119. old_clock = tk->tkr.clock;
  120. tk->tkr.clock = clock;
  121. tk->tkr.read = clock->read;
  122. tk->tkr.mask = clock->mask;
  123. tk->tkr.cycle_last = tk->tkr.read(clock);
  124. /* Do the ns -> cycle conversion first, using original mult */
  125. tmp = NTP_INTERVAL_LENGTH;
  126. tmp <<= clock->shift;
  127. ntpinterval = tmp;
  128. tmp += clock->mult/2;
  129. do_div(tmp, clock->mult);
  130. if (tmp == 0)
  131. tmp = 1;
  132. interval = (cycle_t) tmp;
  133. tk->cycle_interval = interval;
  134. /* Go back from cycles -> shifted ns */
  135. tk->xtime_interval = (u64) interval * clock->mult;
  136. tk->xtime_remainder = ntpinterval - tk->xtime_interval;
  137. tk->raw_interval =
  138. ((u64) interval * clock->mult) >> clock->shift;
  139. /* if changing clocks, convert xtime_nsec shift units */
  140. if (old_clock) {
  141. int shift_change = clock->shift - old_clock->shift;
  142. if (shift_change < 0)
  143. tk->tkr.xtime_nsec >>= -shift_change;
  144. else
  145. tk->tkr.xtime_nsec <<= shift_change;
  146. }
  147. tk->tkr.shift = clock->shift;
  148. tk->ntp_error = 0;
  149. tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
  150. tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
  151. /*
  152. * The timekeeper keeps its own mult values for the currently
  153. * active clocksource. These value will be adjusted via NTP
  154. * to counteract clock drifting.
  155. */
  156. tk->tkr.mult = clock->mult;
  157. tk->ntp_err_mult = 0;
  158. }
  159. /* Timekeeper helper functions. */
  160. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  161. static u32 default_arch_gettimeoffset(void) { return 0; }
  162. u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
  163. #else
  164. static inline u32 arch_gettimeoffset(void) { return 0; }
  165. #endif
  166. static inline s64 timekeeping_get_ns(struct tk_read_base *tkr)
  167. {
  168. cycle_t cycle_now, delta;
  169. s64 nsec;
  170. /* read clocksource: */
  171. cycle_now = tkr->read(tkr->clock);
  172. /* calculate the delta since the last update_wall_time: */
  173. delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
  174. nsec = delta * tkr->mult + tkr->xtime_nsec;
  175. nsec >>= tkr->shift;
  176. /* If arch requires, add in get_arch_timeoffset() */
  177. return nsec + arch_gettimeoffset();
  178. }
  179. static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
  180. {
  181. struct clocksource *clock = tk->tkr.clock;
  182. cycle_t cycle_now, delta;
  183. s64 nsec;
  184. /* read clocksource: */
  185. cycle_now = tk->tkr.read(clock);
  186. /* calculate the delta since the last update_wall_time: */
  187. delta = clocksource_delta(cycle_now, tk->tkr.cycle_last, tk->tkr.mask);
  188. /* convert delta to nanoseconds. */
  189. nsec = clocksource_cyc2ns(delta, clock->mult, clock->shift);
  190. /* If arch requires, add in get_arch_timeoffset() */
  191. return nsec + arch_gettimeoffset();
  192. }
  193. /**
  194. * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
  195. * @tk: The timekeeper from which we take the update
  196. * @tkf: The fast timekeeper to update
  197. * @tbase: The time base for the fast timekeeper (mono/raw)
  198. *
  199. * We want to use this from any context including NMI and tracing /
  200. * instrumenting the timekeeping code itself.
  201. *
  202. * So we handle this differently than the other timekeeping accessor
  203. * functions which retry when the sequence count has changed. The
  204. * update side does:
  205. *
  206. * smp_wmb(); <- Ensure that the last base[1] update is visible
  207. * tkf->seq++;
  208. * smp_wmb(); <- Ensure that the seqcount update is visible
  209. * update(tkf->base[0], tk);
  210. * smp_wmb(); <- Ensure that the base[0] update is visible
  211. * tkf->seq++;
  212. * smp_wmb(); <- Ensure that the seqcount update is visible
  213. * update(tkf->base[1], tk);
  214. *
  215. * The reader side does:
  216. *
  217. * do {
  218. * seq = tkf->seq;
  219. * smp_rmb();
  220. * idx = seq & 0x01;
  221. * now = now(tkf->base[idx]);
  222. * smp_rmb();
  223. * } while (seq != tkf->seq)
  224. *
  225. * As long as we update base[0] readers are forced off to
  226. * base[1]. Once base[0] is updated readers are redirected to base[0]
  227. * and the base[1] update takes place.
  228. *
  229. * So if a NMI hits the update of base[0] then it will use base[1]
  230. * which is still consistent. In the worst case this can result is a
  231. * slightly wrong timestamp (a few nanoseconds). See
  232. * @ktime_get_mono_fast_ns.
  233. */
  234. static void update_fast_timekeeper(struct timekeeper *tk)
  235. {
  236. struct tk_read_base *base = tk_fast_mono.base;
  237. /* Force readers off to base[1] */
  238. raw_write_seqcount_latch(&tk_fast_mono.seq);
  239. /* Update base[0] */
  240. memcpy(base, &tk->tkr, sizeof(*base));
  241. /* Force readers back to base[0] */
  242. raw_write_seqcount_latch(&tk_fast_mono.seq);
  243. /* Update base[1] */
  244. memcpy(base + 1, base, sizeof(*base));
  245. }
  246. /**
  247. * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
  248. *
  249. * This timestamp is not guaranteed to be monotonic across an update.
  250. * The timestamp is calculated by:
  251. *
  252. * now = base_mono + clock_delta * slope
  253. *
  254. * So if the update lowers the slope, readers who are forced to the
  255. * not yet updated second array are still using the old steeper slope.
  256. *
  257. * tmono
  258. * ^
  259. * | o n
  260. * | o n
  261. * | u
  262. * | o
  263. * |o
  264. * |12345678---> reader order
  265. *
  266. * o = old slope
  267. * u = update
  268. * n = new slope
  269. *
  270. * So reader 6 will observe time going backwards versus reader 5.
  271. *
  272. * While other CPUs are likely to be able observe that, the only way
  273. * for a CPU local observation is when an NMI hits in the middle of
  274. * the update. Timestamps taken from that NMI context might be ahead
  275. * of the following timestamps. Callers need to be aware of that and
  276. * deal with it.
  277. */
  278. u64 notrace ktime_get_mono_fast_ns(void)
  279. {
  280. struct tk_read_base *tkr;
  281. unsigned int seq;
  282. u64 now;
  283. do {
  284. seq = raw_read_seqcount(&tk_fast_mono.seq);
  285. tkr = tk_fast_mono.base + (seq & 0x01);
  286. now = ktime_to_ns(tkr->base_mono) + timekeeping_get_ns(tkr);
  287. } while (read_seqcount_retry(&tk_fast_mono.seq, seq));
  288. return now;
  289. }
  290. EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
  291. #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
  292. static inline void update_vsyscall(struct timekeeper *tk)
  293. {
  294. struct timespec xt, wm;
  295. xt = timespec64_to_timespec(tk_xtime(tk));
  296. wm = timespec64_to_timespec(tk->wall_to_monotonic);
  297. update_vsyscall_old(&xt, &wm, tk->tkr.clock, tk->tkr.mult,
  298. tk->tkr.cycle_last);
  299. }
  300. static inline void old_vsyscall_fixup(struct timekeeper *tk)
  301. {
  302. s64 remainder;
  303. /*
  304. * Store only full nanoseconds into xtime_nsec after rounding
  305. * it up and add the remainder to the error difference.
  306. * XXX - This is necessary to avoid small 1ns inconsistnecies caused
  307. * by truncating the remainder in vsyscalls. However, it causes
  308. * additional work to be done in timekeeping_adjust(). Once
  309. * the vsyscall implementations are converted to use xtime_nsec
  310. * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
  311. * users are removed, this can be killed.
  312. */
  313. remainder = tk->tkr.xtime_nsec & ((1ULL << tk->tkr.shift) - 1);
  314. tk->tkr.xtime_nsec -= remainder;
  315. tk->tkr.xtime_nsec += 1ULL << tk->tkr.shift;
  316. tk->ntp_error += remainder << tk->ntp_error_shift;
  317. tk->ntp_error -= (1ULL << tk->tkr.shift) << tk->ntp_error_shift;
  318. }
  319. #else
  320. #define old_vsyscall_fixup(tk)
  321. #endif
  322. static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
  323. static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
  324. {
  325. raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
  326. }
  327. /**
  328. * pvclock_gtod_register_notifier - register a pvclock timedata update listener
  329. */
  330. int pvclock_gtod_register_notifier(struct notifier_block *nb)
  331. {
  332. struct timekeeper *tk = &tk_core.timekeeper;
  333. unsigned long flags;
  334. int ret;
  335. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  336. ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
  337. update_pvclock_gtod(tk, true);
  338. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  339. return ret;
  340. }
  341. EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
  342. /**
  343. * pvclock_gtod_unregister_notifier - unregister a pvclock
  344. * timedata update listener
  345. */
  346. int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
  347. {
  348. unsigned long flags;
  349. int ret;
  350. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  351. ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
  352. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  353. return ret;
  354. }
  355. EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
  356. /*
  357. * Update the ktime_t based scalar nsec members of the timekeeper
  358. */
  359. static inline void tk_update_ktime_data(struct timekeeper *tk)
  360. {
  361. s64 nsec;
  362. /*
  363. * The xtime based monotonic readout is:
  364. * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
  365. * The ktime based monotonic readout is:
  366. * nsec = base_mono + now();
  367. * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
  368. */
  369. nsec = (s64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
  370. nsec *= NSEC_PER_SEC;
  371. nsec += tk->wall_to_monotonic.tv_nsec;
  372. tk->tkr.base_mono = ns_to_ktime(nsec);
  373. /* Update the monotonic raw base */
  374. tk->base_raw = timespec64_to_ktime(tk->raw_time);
  375. }
  376. /* must hold timekeeper_lock */
  377. static void timekeeping_update(struct timekeeper *tk, unsigned int action)
  378. {
  379. if (action & TK_CLEAR_NTP) {
  380. tk->ntp_error = 0;
  381. ntp_clear();
  382. }
  383. tk_update_ktime_data(tk);
  384. update_vsyscall(tk);
  385. update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
  386. if (action & TK_MIRROR)
  387. memcpy(&shadow_timekeeper, &tk_core.timekeeper,
  388. sizeof(tk_core.timekeeper));
  389. update_fast_timekeeper(tk);
  390. }
  391. /**
  392. * timekeeping_forward_now - update clock to the current time
  393. *
  394. * Forward the current clock to update its state since the last call to
  395. * update_wall_time(). This is useful before significant clock changes,
  396. * as it avoids having to deal with this time offset explicitly.
  397. */
  398. static void timekeeping_forward_now(struct timekeeper *tk)
  399. {
  400. struct clocksource *clock = tk->tkr.clock;
  401. cycle_t cycle_now, delta;
  402. s64 nsec;
  403. cycle_now = tk->tkr.read(clock);
  404. delta = clocksource_delta(cycle_now, tk->tkr.cycle_last, tk->tkr.mask);
  405. tk->tkr.cycle_last = cycle_now;
  406. tk->tkr.xtime_nsec += delta * tk->tkr.mult;
  407. /* If arch requires, add in get_arch_timeoffset() */
  408. tk->tkr.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr.shift;
  409. tk_normalize_xtime(tk);
  410. nsec = clocksource_cyc2ns(delta, clock->mult, clock->shift);
  411. timespec64_add_ns(&tk->raw_time, nsec);
  412. }
  413. /**
  414. * __getnstimeofday64 - Returns the time of day in a timespec64.
  415. * @ts: pointer to the timespec to be set
  416. *
  417. * Updates the time of day in the timespec.
  418. * Returns 0 on success, or -ve when suspended (timespec will be undefined).
  419. */
  420. int __getnstimeofday64(struct timespec64 *ts)
  421. {
  422. struct timekeeper *tk = &tk_core.timekeeper;
  423. unsigned long seq;
  424. s64 nsecs = 0;
  425. do {
  426. seq = read_seqcount_begin(&tk_core.seq);
  427. ts->tv_sec = tk->xtime_sec;
  428. nsecs = timekeeping_get_ns(&tk->tkr);
  429. } while (read_seqcount_retry(&tk_core.seq, seq));
  430. ts->tv_nsec = 0;
  431. timespec64_add_ns(ts, nsecs);
  432. /*
  433. * Do not bail out early, in case there were callers still using
  434. * the value, even in the face of the WARN_ON.
  435. */
  436. if (unlikely(timekeeping_suspended))
  437. return -EAGAIN;
  438. return 0;
  439. }
  440. EXPORT_SYMBOL(__getnstimeofday64);
  441. /**
  442. * getnstimeofday64 - Returns the time of day in a timespec64.
  443. * @ts: pointer to the timespec to be set
  444. *
  445. * Returns the time of day in a timespec (WARN if suspended).
  446. */
  447. void getnstimeofday64(struct timespec64 *ts)
  448. {
  449. WARN_ON(__getnstimeofday64(ts));
  450. }
  451. EXPORT_SYMBOL(getnstimeofday64);
  452. ktime_t ktime_get(void)
  453. {
  454. struct timekeeper *tk = &tk_core.timekeeper;
  455. unsigned int seq;
  456. ktime_t base;
  457. s64 nsecs;
  458. WARN_ON(timekeeping_suspended);
  459. do {
  460. seq = read_seqcount_begin(&tk_core.seq);
  461. base = tk->tkr.base_mono;
  462. nsecs = timekeeping_get_ns(&tk->tkr);
  463. } while (read_seqcount_retry(&tk_core.seq, seq));
  464. return ktime_add_ns(base, nsecs);
  465. }
  466. EXPORT_SYMBOL_GPL(ktime_get);
  467. static ktime_t *offsets[TK_OFFS_MAX] = {
  468. [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
  469. [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
  470. [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
  471. };
  472. ktime_t ktime_get_with_offset(enum tk_offsets offs)
  473. {
  474. struct timekeeper *tk = &tk_core.timekeeper;
  475. unsigned int seq;
  476. ktime_t base, *offset = offsets[offs];
  477. s64 nsecs;
  478. WARN_ON(timekeeping_suspended);
  479. do {
  480. seq = read_seqcount_begin(&tk_core.seq);
  481. base = ktime_add(tk->tkr.base_mono, *offset);
  482. nsecs = timekeeping_get_ns(&tk->tkr);
  483. } while (read_seqcount_retry(&tk_core.seq, seq));
  484. return ktime_add_ns(base, nsecs);
  485. }
  486. EXPORT_SYMBOL_GPL(ktime_get_with_offset);
  487. /**
  488. * ktime_mono_to_any() - convert mononotic time to any other time
  489. * @tmono: time to convert.
  490. * @offs: which offset to use
  491. */
  492. ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
  493. {
  494. ktime_t *offset = offsets[offs];
  495. unsigned long seq;
  496. ktime_t tconv;
  497. do {
  498. seq = read_seqcount_begin(&tk_core.seq);
  499. tconv = ktime_add(tmono, *offset);
  500. } while (read_seqcount_retry(&tk_core.seq, seq));
  501. return tconv;
  502. }
  503. EXPORT_SYMBOL_GPL(ktime_mono_to_any);
  504. /**
  505. * ktime_get_raw - Returns the raw monotonic time in ktime_t format
  506. */
  507. ktime_t ktime_get_raw(void)
  508. {
  509. struct timekeeper *tk = &tk_core.timekeeper;
  510. unsigned int seq;
  511. ktime_t base;
  512. s64 nsecs;
  513. do {
  514. seq = read_seqcount_begin(&tk_core.seq);
  515. base = tk->base_raw;
  516. nsecs = timekeeping_get_ns_raw(tk);
  517. } while (read_seqcount_retry(&tk_core.seq, seq));
  518. return ktime_add_ns(base, nsecs);
  519. }
  520. EXPORT_SYMBOL_GPL(ktime_get_raw);
  521. /**
  522. * ktime_get_ts64 - get the monotonic clock in timespec64 format
  523. * @ts: pointer to timespec variable
  524. *
  525. * The function calculates the monotonic clock from the realtime
  526. * clock and the wall_to_monotonic offset and stores the result
  527. * in normalized timespec format in the variable pointed to by @ts.
  528. */
  529. void ktime_get_ts64(struct timespec64 *ts)
  530. {
  531. struct timekeeper *tk = &tk_core.timekeeper;
  532. struct timespec64 tomono;
  533. s64 nsec;
  534. unsigned int seq;
  535. WARN_ON(timekeeping_suspended);
  536. do {
  537. seq = read_seqcount_begin(&tk_core.seq);
  538. ts->tv_sec = tk->xtime_sec;
  539. nsec = timekeeping_get_ns(&tk->tkr);
  540. tomono = tk->wall_to_monotonic;
  541. } while (read_seqcount_retry(&tk_core.seq, seq));
  542. ts->tv_sec += tomono.tv_sec;
  543. ts->tv_nsec = 0;
  544. timespec64_add_ns(ts, nsec + tomono.tv_nsec);
  545. }
  546. EXPORT_SYMBOL_GPL(ktime_get_ts64);
  547. #ifdef CONFIG_NTP_PPS
  548. /**
  549. * getnstime_raw_and_real - get day and raw monotonic time in timespec format
  550. * @ts_raw: pointer to the timespec to be set to raw monotonic time
  551. * @ts_real: pointer to the timespec to be set to the time of day
  552. *
  553. * This function reads both the time of day and raw monotonic time at the
  554. * same time atomically and stores the resulting timestamps in timespec
  555. * format.
  556. */
  557. void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
  558. {
  559. struct timekeeper *tk = &tk_core.timekeeper;
  560. unsigned long seq;
  561. s64 nsecs_raw, nsecs_real;
  562. WARN_ON_ONCE(timekeeping_suspended);
  563. do {
  564. seq = read_seqcount_begin(&tk_core.seq);
  565. *ts_raw = timespec64_to_timespec(tk->raw_time);
  566. ts_real->tv_sec = tk->xtime_sec;
  567. ts_real->tv_nsec = 0;
  568. nsecs_raw = timekeeping_get_ns_raw(tk);
  569. nsecs_real = timekeeping_get_ns(&tk->tkr);
  570. } while (read_seqcount_retry(&tk_core.seq, seq));
  571. timespec_add_ns(ts_raw, nsecs_raw);
  572. timespec_add_ns(ts_real, nsecs_real);
  573. }
  574. EXPORT_SYMBOL(getnstime_raw_and_real);
  575. #endif /* CONFIG_NTP_PPS */
  576. /**
  577. * do_gettimeofday - Returns the time of day in a timeval
  578. * @tv: pointer to the timeval to be set
  579. *
  580. * NOTE: Users should be converted to using getnstimeofday()
  581. */
  582. void do_gettimeofday(struct timeval *tv)
  583. {
  584. struct timespec64 now;
  585. getnstimeofday64(&now);
  586. tv->tv_sec = now.tv_sec;
  587. tv->tv_usec = now.tv_nsec/1000;
  588. }
  589. EXPORT_SYMBOL(do_gettimeofday);
  590. /**
  591. * do_settimeofday - Sets the time of day
  592. * @tv: pointer to the timespec variable containing the new time
  593. *
  594. * Sets the time of day to the new time and update NTP and notify hrtimers
  595. */
  596. int do_settimeofday(const struct timespec *tv)
  597. {
  598. struct timekeeper *tk = &tk_core.timekeeper;
  599. struct timespec64 ts_delta, xt, tmp;
  600. unsigned long flags;
  601. if (!timespec_valid_strict(tv))
  602. return -EINVAL;
  603. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  604. write_seqcount_begin(&tk_core.seq);
  605. timekeeping_forward_now(tk);
  606. xt = tk_xtime(tk);
  607. ts_delta.tv_sec = tv->tv_sec - xt.tv_sec;
  608. ts_delta.tv_nsec = tv->tv_nsec - xt.tv_nsec;
  609. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
  610. tmp = timespec_to_timespec64(*tv);
  611. tk_set_xtime(tk, &tmp);
  612. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  613. write_seqcount_end(&tk_core.seq);
  614. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  615. /* signal hrtimers about time change */
  616. clock_was_set();
  617. return 0;
  618. }
  619. EXPORT_SYMBOL(do_settimeofday);
  620. /**
  621. * timekeeping_inject_offset - Adds or subtracts from the current time.
  622. * @tv: pointer to the timespec variable containing the offset
  623. *
  624. * Adds or subtracts an offset value from the current time.
  625. */
  626. int timekeeping_inject_offset(struct timespec *ts)
  627. {
  628. struct timekeeper *tk = &tk_core.timekeeper;
  629. unsigned long flags;
  630. struct timespec64 ts64, tmp;
  631. int ret = 0;
  632. if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
  633. return -EINVAL;
  634. ts64 = timespec_to_timespec64(*ts);
  635. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  636. write_seqcount_begin(&tk_core.seq);
  637. timekeeping_forward_now(tk);
  638. /* Make sure the proposed value is valid */
  639. tmp = timespec64_add(tk_xtime(tk), ts64);
  640. if (!timespec64_valid_strict(&tmp)) {
  641. ret = -EINVAL;
  642. goto error;
  643. }
  644. tk_xtime_add(tk, &ts64);
  645. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
  646. error: /* even if we error out, we forwarded the time, so call update */
  647. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  648. write_seqcount_end(&tk_core.seq);
  649. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  650. /* signal hrtimers about time change */
  651. clock_was_set();
  652. return ret;
  653. }
  654. EXPORT_SYMBOL(timekeeping_inject_offset);
  655. /**
  656. * timekeeping_get_tai_offset - Returns current TAI offset from UTC
  657. *
  658. */
  659. s32 timekeeping_get_tai_offset(void)
  660. {
  661. struct timekeeper *tk = &tk_core.timekeeper;
  662. unsigned int seq;
  663. s32 ret;
  664. do {
  665. seq = read_seqcount_begin(&tk_core.seq);
  666. ret = tk->tai_offset;
  667. } while (read_seqcount_retry(&tk_core.seq, seq));
  668. return ret;
  669. }
  670. /**
  671. * __timekeeping_set_tai_offset - Lock free worker function
  672. *
  673. */
  674. static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
  675. {
  676. tk->tai_offset = tai_offset;
  677. tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
  678. }
  679. /**
  680. * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
  681. *
  682. */
  683. void timekeeping_set_tai_offset(s32 tai_offset)
  684. {
  685. struct timekeeper *tk = &tk_core.timekeeper;
  686. unsigned long flags;
  687. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  688. write_seqcount_begin(&tk_core.seq);
  689. __timekeeping_set_tai_offset(tk, tai_offset);
  690. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  691. write_seqcount_end(&tk_core.seq);
  692. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  693. clock_was_set();
  694. }
  695. /**
  696. * change_clocksource - Swaps clocksources if a new one is available
  697. *
  698. * Accumulates current time interval and initializes new clocksource
  699. */
  700. static int change_clocksource(void *data)
  701. {
  702. struct timekeeper *tk = &tk_core.timekeeper;
  703. struct clocksource *new, *old;
  704. unsigned long flags;
  705. new = (struct clocksource *) data;
  706. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  707. write_seqcount_begin(&tk_core.seq);
  708. timekeeping_forward_now(tk);
  709. /*
  710. * If the cs is in module, get a module reference. Succeeds
  711. * for built-in code (owner == NULL) as well.
  712. */
  713. if (try_module_get(new->owner)) {
  714. if (!new->enable || new->enable(new) == 0) {
  715. old = tk->tkr.clock;
  716. tk_setup_internals(tk, new);
  717. if (old->disable)
  718. old->disable(old);
  719. module_put(old->owner);
  720. } else {
  721. module_put(new->owner);
  722. }
  723. }
  724. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  725. write_seqcount_end(&tk_core.seq);
  726. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  727. return 0;
  728. }
  729. /**
  730. * timekeeping_notify - Install a new clock source
  731. * @clock: pointer to the clock source
  732. *
  733. * This function is called from clocksource.c after a new, better clock
  734. * source has been registered. The caller holds the clocksource_mutex.
  735. */
  736. int timekeeping_notify(struct clocksource *clock)
  737. {
  738. struct timekeeper *tk = &tk_core.timekeeper;
  739. if (tk->tkr.clock == clock)
  740. return 0;
  741. stop_machine(change_clocksource, clock, NULL);
  742. tick_clock_notify();
  743. return tk->tkr.clock == clock ? 0 : -1;
  744. }
  745. /**
  746. * getrawmonotonic - Returns the raw monotonic time in a timespec
  747. * @ts: pointer to the timespec to be set
  748. *
  749. * Returns the raw monotonic time (completely un-modified by ntp)
  750. */
  751. void getrawmonotonic(struct timespec *ts)
  752. {
  753. struct timekeeper *tk = &tk_core.timekeeper;
  754. struct timespec64 ts64;
  755. unsigned long seq;
  756. s64 nsecs;
  757. do {
  758. seq = read_seqcount_begin(&tk_core.seq);
  759. nsecs = timekeeping_get_ns_raw(tk);
  760. ts64 = tk->raw_time;
  761. } while (read_seqcount_retry(&tk_core.seq, seq));
  762. timespec64_add_ns(&ts64, nsecs);
  763. *ts = timespec64_to_timespec(ts64);
  764. }
  765. EXPORT_SYMBOL(getrawmonotonic);
  766. /**
  767. * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
  768. */
  769. int timekeeping_valid_for_hres(void)
  770. {
  771. struct timekeeper *tk = &tk_core.timekeeper;
  772. unsigned long seq;
  773. int ret;
  774. do {
  775. seq = read_seqcount_begin(&tk_core.seq);
  776. ret = tk->tkr.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  777. } while (read_seqcount_retry(&tk_core.seq, seq));
  778. return ret;
  779. }
  780. /**
  781. * timekeeping_max_deferment - Returns max time the clocksource can be deferred
  782. */
  783. u64 timekeeping_max_deferment(void)
  784. {
  785. struct timekeeper *tk = &tk_core.timekeeper;
  786. unsigned long seq;
  787. u64 ret;
  788. do {
  789. seq = read_seqcount_begin(&tk_core.seq);
  790. ret = tk->tkr.clock->max_idle_ns;
  791. } while (read_seqcount_retry(&tk_core.seq, seq));
  792. return ret;
  793. }
  794. /**
  795. * read_persistent_clock - Return time from the persistent clock.
  796. *
  797. * Weak dummy function for arches that do not yet support it.
  798. * Reads the time from the battery backed persistent clock.
  799. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  800. *
  801. * XXX - Do be sure to remove it once all arches implement it.
  802. */
  803. void __weak read_persistent_clock(struct timespec *ts)
  804. {
  805. ts->tv_sec = 0;
  806. ts->tv_nsec = 0;
  807. }
  808. /**
  809. * read_boot_clock - Return time of the system start.
  810. *
  811. * Weak dummy function for arches that do not yet support it.
  812. * Function to read the exact time the system has been started.
  813. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  814. *
  815. * XXX - Do be sure to remove it once all arches implement it.
  816. */
  817. void __weak read_boot_clock(struct timespec *ts)
  818. {
  819. ts->tv_sec = 0;
  820. ts->tv_nsec = 0;
  821. }
  822. /*
  823. * timekeeping_init - Initializes the clocksource and common timekeeping values
  824. */
  825. void __init timekeeping_init(void)
  826. {
  827. struct timekeeper *tk = &tk_core.timekeeper;
  828. struct clocksource *clock;
  829. unsigned long flags;
  830. struct timespec64 now, boot, tmp;
  831. struct timespec ts;
  832. read_persistent_clock(&ts);
  833. now = timespec_to_timespec64(ts);
  834. if (!timespec64_valid_strict(&now)) {
  835. pr_warn("WARNING: Persistent clock returned invalid value!\n"
  836. " Check your CMOS/BIOS settings.\n");
  837. now.tv_sec = 0;
  838. now.tv_nsec = 0;
  839. } else if (now.tv_sec || now.tv_nsec)
  840. persistent_clock_exist = true;
  841. read_boot_clock(&ts);
  842. boot = timespec_to_timespec64(ts);
  843. if (!timespec64_valid_strict(&boot)) {
  844. pr_warn("WARNING: Boot clock returned invalid value!\n"
  845. " Check your CMOS/BIOS settings.\n");
  846. boot.tv_sec = 0;
  847. boot.tv_nsec = 0;
  848. }
  849. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  850. write_seqcount_begin(&tk_core.seq);
  851. ntp_init();
  852. clock = clocksource_default_clock();
  853. if (clock->enable)
  854. clock->enable(clock);
  855. tk_setup_internals(tk, clock);
  856. tk_set_xtime(tk, &now);
  857. tk->raw_time.tv_sec = 0;
  858. tk->raw_time.tv_nsec = 0;
  859. tk->base_raw.tv64 = 0;
  860. if (boot.tv_sec == 0 && boot.tv_nsec == 0)
  861. boot = tk_xtime(tk);
  862. set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
  863. tk_set_wall_to_mono(tk, tmp);
  864. timekeeping_update(tk, TK_MIRROR);
  865. write_seqcount_end(&tk_core.seq);
  866. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  867. }
  868. /* time in seconds when suspend began */
  869. static struct timespec64 timekeeping_suspend_time;
  870. /**
  871. * __timekeeping_inject_sleeptime - Internal function to add sleep interval
  872. * @delta: pointer to a timespec delta value
  873. *
  874. * Takes a timespec offset measuring a suspend interval and properly
  875. * adds the sleep offset to the timekeeping variables.
  876. */
  877. static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
  878. struct timespec64 *delta)
  879. {
  880. if (!timespec64_valid_strict(delta)) {
  881. printk_deferred(KERN_WARNING
  882. "__timekeeping_inject_sleeptime: Invalid "
  883. "sleep delta value!\n");
  884. return;
  885. }
  886. tk_xtime_add(tk, delta);
  887. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
  888. tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
  889. tk_debug_account_sleep_time(delta);
  890. }
  891. /**
  892. * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
  893. * @delta: pointer to a timespec delta value
  894. *
  895. * This hook is for architectures that cannot support read_persistent_clock
  896. * because their RTC/persistent clock is only accessible when irqs are enabled.
  897. *
  898. * This function should only be called by rtc_resume(), and allows
  899. * a suspend offset to be injected into the timekeeping values.
  900. */
  901. void timekeeping_inject_sleeptime(struct timespec *delta)
  902. {
  903. struct timekeeper *tk = &tk_core.timekeeper;
  904. struct timespec64 tmp;
  905. unsigned long flags;
  906. /*
  907. * Make sure we don't set the clock twice, as timekeeping_resume()
  908. * already did it
  909. */
  910. if (has_persistent_clock())
  911. return;
  912. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  913. write_seqcount_begin(&tk_core.seq);
  914. timekeeping_forward_now(tk);
  915. tmp = timespec_to_timespec64(*delta);
  916. __timekeeping_inject_sleeptime(tk, &tmp);
  917. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  918. write_seqcount_end(&tk_core.seq);
  919. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  920. /* signal hrtimers about time change */
  921. clock_was_set();
  922. }
  923. /**
  924. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  925. *
  926. * This is for the generic clocksource timekeeping.
  927. * xtime/wall_to_monotonic/jiffies/etc are
  928. * still managed by arch specific suspend/resume code.
  929. */
  930. static void timekeeping_resume(void)
  931. {
  932. struct timekeeper *tk = &tk_core.timekeeper;
  933. struct clocksource *clock = tk->tkr.clock;
  934. unsigned long flags;
  935. struct timespec64 ts_new, ts_delta;
  936. struct timespec tmp;
  937. cycle_t cycle_now, cycle_delta;
  938. bool suspendtime_found = false;
  939. read_persistent_clock(&tmp);
  940. ts_new = timespec_to_timespec64(tmp);
  941. clockevents_resume();
  942. clocksource_resume();
  943. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  944. write_seqcount_begin(&tk_core.seq);
  945. /*
  946. * After system resumes, we need to calculate the suspended time and
  947. * compensate it for the OS time. There are 3 sources that could be
  948. * used: Nonstop clocksource during suspend, persistent clock and rtc
  949. * device.
  950. *
  951. * One specific platform may have 1 or 2 or all of them, and the
  952. * preference will be:
  953. * suspend-nonstop clocksource -> persistent clock -> rtc
  954. * The less preferred source will only be tried if there is no better
  955. * usable source. The rtc part is handled separately in rtc core code.
  956. */
  957. cycle_now = tk->tkr.read(clock);
  958. if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
  959. cycle_now > tk->tkr.cycle_last) {
  960. u64 num, max = ULLONG_MAX;
  961. u32 mult = clock->mult;
  962. u32 shift = clock->shift;
  963. s64 nsec = 0;
  964. cycle_delta = clocksource_delta(cycle_now, tk->tkr.cycle_last,
  965. tk->tkr.mask);
  966. /*
  967. * "cycle_delta * mutl" may cause 64 bits overflow, if the
  968. * suspended time is too long. In that case we need do the
  969. * 64 bits math carefully
  970. */
  971. do_div(max, mult);
  972. if (cycle_delta > max) {
  973. num = div64_u64(cycle_delta, max);
  974. nsec = (((u64) max * mult) >> shift) * num;
  975. cycle_delta -= num * max;
  976. }
  977. nsec += ((u64) cycle_delta * mult) >> shift;
  978. ts_delta = ns_to_timespec64(nsec);
  979. suspendtime_found = true;
  980. } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
  981. ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
  982. suspendtime_found = true;
  983. }
  984. if (suspendtime_found)
  985. __timekeeping_inject_sleeptime(tk, &ts_delta);
  986. /* Re-base the last cycle value */
  987. tk->tkr.cycle_last = cycle_now;
  988. tk->ntp_error = 0;
  989. timekeeping_suspended = 0;
  990. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  991. write_seqcount_end(&tk_core.seq);
  992. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  993. touch_softlockup_watchdog();
  994. clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
  995. /* Resume hrtimers */
  996. hrtimers_resume();
  997. }
  998. static int timekeeping_suspend(void)
  999. {
  1000. struct timekeeper *tk = &tk_core.timekeeper;
  1001. unsigned long flags;
  1002. struct timespec64 delta, delta_delta;
  1003. static struct timespec64 old_delta;
  1004. struct timespec tmp;
  1005. read_persistent_clock(&tmp);
  1006. timekeeping_suspend_time = timespec_to_timespec64(tmp);
  1007. /*
  1008. * On some systems the persistent_clock can not be detected at
  1009. * timekeeping_init by its return value, so if we see a valid
  1010. * value returned, update the persistent_clock_exists flag.
  1011. */
  1012. if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
  1013. persistent_clock_exist = true;
  1014. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1015. write_seqcount_begin(&tk_core.seq);
  1016. timekeeping_forward_now(tk);
  1017. timekeeping_suspended = 1;
  1018. /*
  1019. * To avoid drift caused by repeated suspend/resumes,
  1020. * which each can add ~1 second drift error,
  1021. * try to compensate so the difference in system time
  1022. * and persistent_clock time stays close to constant.
  1023. */
  1024. delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
  1025. delta_delta = timespec64_sub(delta, old_delta);
  1026. if (abs(delta_delta.tv_sec) >= 2) {
  1027. /*
  1028. * if delta_delta is too large, assume time correction
  1029. * has occured and set old_delta to the current delta.
  1030. */
  1031. old_delta = delta;
  1032. } else {
  1033. /* Otherwise try to adjust old_system to compensate */
  1034. timekeeping_suspend_time =
  1035. timespec64_add(timekeeping_suspend_time, delta_delta);
  1036. }
  1037. timekeeping_update(tk, TK_MIRROR);
  1038. write_seqcount_end(&tk_core.seq);
  1039. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1040. clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
  1041. clocksource_suspend();
  1042. clockevents_suspend();
  1043. return 0;
  1044. }
  1045. /* sysfs resume/suspend bits for timekeeping */
  1046. static struct syscore_ops timekeeping_syscore_ops = {
  1047. .resume = timekeeping_resume,
  1048. .suspend = timekeeping_suspend,
  1049. };
  1050. static int __init timekeeping_init_ops(void)
  1051. {
  1052. register_syscore_ops(&timekeeping_syscore_ops);
  1053. return 0;
  1054. }
  1055. device_initcall(timekeeping_init_ops);
  1056. /*
  1057. * Apply a multiplier adjustment to the timekeeper
  1058. */
  1059. static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
  1060. s64 offset,
  1061. bool negative,
  1062. int adj_scale)
  1063. {
  1064. s64 interval = tk->cycle_interval;
  1065. s32 mult_adj = 1;
  1066. if (negative) {
  1067. mult_adj = -mult_adj;
  1068. interval = -interval;
  1069. offset = -offset;
  1070. }
  1071. mult_adj <<= adj_scale;
  1072. interval <<= adj_scale;
  1073. offset <<= adj_scale;
  1074. /*
  1075. * So the following can be confusing.
  1076. *
  1077. * To keep things simple, lets assume mult_adj == 1 for now.
  1078. *
  1079. * When mult_adj != 1, remember that the interval and offset values
  1080. * have been appropriately scaled so the math is the same.
  1081. *
  1082. * The basic idea here is that we're increasing the multiplier
  1083. * by one, this causes the xtime_interval to be incremented by
  1084. * one cycle_interval. This is because:
  1085. * xtime_interval = cycle_interval * mult
  1086. * So if mult is being incremented by one:
  1087. * xtime_interval = cycle_interval * (mult + 1)
  1088. * Its the same as:
  1089. * xtime_interval = (cycle_interval * mult) + cycle_interval
  1090. * Which can be shortened to:
  1091. * xtime_interval += cycle_interval
  1092. *
  1093. * So offset stores the non-accumulated cycles. Thus the current
  1094. * time (in shifted nanoseconds) is:
  1095. * now = (offset * adj) + xtime_nsec
  1096. * Now, even though we're adjusting the clock frequency, we have
  1097. * to keep time consistent. In other words, we can't jump back
  1098. * in time, and we also want to avoid jumping forward in time.
  1099. *
  1100. * So given the same offset value, we need the time to be the same
  1101. * both before and after the freq adjustment.
  1102. * now = (offset * adj_1) + xtime_nsec_1
  1103. * now = (offset * adj_2) + xtime_nsec_2
  1104. * So:
  1105. * (offset * adj_1) + xtime_nsec_1 =
  1106. * (offset * adj_2) + xtime_nsec_2
  1107. * And we know:
  1108. * adj_2 = adj_1 + 1
  1109. * So:
  1110. * (offset * adj_1) + xtime_nsec_1 =
  1111. * (offset * (adj_1+1)) + xtime_nsec_2
  1112. * (offset * adj_1) + xtime_nsec_1 =
  1113. * (offset * adj_1) + offset + xtime_nsec_2
  1114. * Canceling the sides:
  1115. * xtime_nsec_1 = offset + xtime_nsec_2
  1116. * Which gives us:
  1117. * xtime_nsec_2 = xtime_nsec_1 - offset
  1118. * Which simplfies to:
  1119. * xtime_nsec -= offset
  1120. *
  1121. * XXX - TODO: Doc ntp_error calculation.
  1122. */
  1123. tk->tkr.mult += mult_adj;
  1124. tk->xtime_interval += interval;
  1125. tk->tkr.xtime_nsec -= offset;
  1126. tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
  1127. }
  1128. /*
  1129. * Calculate the multiplier adjustment needed to match the frequency
  1130. * specified by NTP
  1131. */
  1132. static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
  1133. s64 offset)
  1134. {
  1135. s64 interval = tk->cycle_interval;
  1136. s64 xinterval = tk->xtime_interval;
  1137. s64 tick_error;
  1138. bool negative;
  1139. u32 adj;
  1140. /* Remove any current error adj from freq calculation */
  1141. if (tk->ntp_err_mult)
  1142. xinterval -= tk->cycle_interval;
  1143. tk->ntp_tick = ntp_tick_length();
  1144. /* Calculate current error per tick */
  1145. tick_error = ntp_tick_length() >> tk->ntp_error_shift;
  1146. tick_error -= (xinterval + tk->xtime_remainder);
  1147. /* Don't worry about correcting it if its small */
  1148. if (likely((tick_error >= 0) && (tick_error <= interval)))
  1149. return;
  1150. /* preserve the direction of correction */
  1151. negative = (tick_error < 0);
  1152. /* Sort out the magnitude of the correction */
  1153. tick_error = abs(tick_error);
  1154. for (adj = 0; tick_error > interval; adj++)
  1155. tick_error >>= 1;
  1156. /* scale the corrections */
  1157. timekeeping_apply_adjustment(tk, offset, negative, adj);
  1158. }
  1159. /*
  1160. * Adjust the timekeeper's multiplier to the correct frequency
  1161. * and also to reduce the accumulated error value.
  1162. */
  1163. static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
  1164. {
  1165. /* Correct for the current frequency error */
  1166. timekeeping_freqadjust(tk, offset);
  1167. /* Next make a small adjustment to fix any cumulative error */
  1168. if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
  1169. tk->ntp_err_mult = 1;
  1170. timekeeping_apply_adjustment(tk, offset, 0, 0);
  1171. } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
  1172. /* Undo any existing error adjustment */
  1173. timekeeping_apply_adjustment(tk, offset, 1, 0);
  1174. tk->ntp_err_mult = 0;
  1175. }
  1176. if (unlikely(tk->tkr.clock->maxadj &&
  1177. (tk->tkr.mult > tk->tkr.clock->mult + tk->tkr.clock->maxadj))) {
  1178. printk_once(KERN_WARNING
  1179. "Adjusting %s more than 11%% (%ld vs %ld)\n",
  1180. tk->tkr.clock->name, (long)tk->tkr.mult,
  1181. (long)tk->tkr.clock->mult + tk->tkr.clock->maxadj);
  1182. }
  1183. /*
  1184. * It may be possible that when we entered this function, xtime_nsec
  1185. * was very small. Further, if we're slightly speeding the clocksource
  1186. * in the code above, its possible the required corrective factor to
  1187. * xtime_nsec could cause it to underflow.
  1188. *
  1189. * Now, since we already accumulated the second, cannot simply roll
  1190. * the accumulated second back, since the NTP subsystem has been
  1191. * notified via second_overflow. So instead we push xtime_nsec forward
  1192. * by the amount we underflowed, and add that amount into the error.
  1193. *
  1194. * We'll correct this error next time through this function, when
  1195. * xtime_nsec is not as small.
  1196. */
  1197. if (unlikely((s64)tk->tkr.xtime_nsec < 0)) {
  1198. s64 neg = -(s64)tk->tkr.xtime_nsec;
  1199. tk->tkr.xtime_nsec = 0;
  1200. tk->ntp_error += neg << tk->ntp_error_shift;
  1201. }
  1202. }
  1203. /**
  1204. * accumulate_nsecs_to_secs - Accumulates nsecs into secs
  1205. *
  1206. * Helper function that accumulates a the nsecs greater then a second
  1207. * from the xtime_nsec field to the xtime_secs field.
  1208. * It also calls into the NTP code to handle leapsecond processing.
  1209. *
  1210. */
  1211. static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
  1212. {
  1213. u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr.shift;
  1214. unsigned int clock_set = 0;
  1215. while (tk->tkr.xtime_nsec >= nsecps) {
  1216. int leap;
  1217. tk->tkr.xtime_nsec -= nsecps;
  1218. tk->xtime_sec++;
  1219. /* Figure out if its a leap sec and apply if needed */
  1220. leap = second_overflow(tk->xtime_sec);
  1221. if (unlikely(leap)) {
  1222. struct timespec64 ts;
  1223. tk->xtime_sec += leap;
  1224. ts.tv_sec = leap;
  1225. ts.tv_nsec = 0;
  1226. tk_set_wall_to_mono(tk,
  1227. timespec64_sub(tk->wall_to_monotonic, ts));
  1228. __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
  1229. clock_set = TK_CLOCK_WAS_SET;
  1230. }
  1231. }
  1232. return clock_set;
  1233. }
  1234. /**
  1235. * logarithmic_accumulation - shifted accumulation of cycles
  1236. *
  1237. * This functions accumulates a shifted interval of cycles into
  1238. * into a shifted interval nanoseconds. Allows for O(log) accumulation
  1239. * loop.
  1240. *
  1241. * Returns the unconsumed cycles.
  1242. */
  1243. static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
  1244. u32 shift,
  1245. unsigned int *clock_set)
  1246. {
  1247. cycle_t interval = tk->cycle_interval << shift;
  1248. u64 raw_nsecs;
  1249. /* If the offset is smaller then a shifted interval, do nothing */
  1250. if (offset < interval)
  1251. return offset;
  1252. /* Accumulate one shifted interval */
  1253. offset -= interval;
  1254. tk->tkr.cycle_last += interval;
  1255. tk->tkr.xtime_nsec += tk->xtime_interval << shift;
  1256. *clock_set |= accumulate_nsecs_to_secs(tk);
  1257. /* Accumulate raw time */
  1258. raw_nsecs = (u64)tk->raw_interval << shift;
  1259. raw_nsecs += tk->raw_time.tv_nsec;
  1260. if (raw_nsecs >= NSEC_PER_SEC) {
  1261. u64 raw_secs = raw_nsecs;
  1262. raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
  1263. tk->raw_time.tv_sec += raw_secs;
  1264. }
  1265. tk->raw_time.tv_nsec = raw_nsecs;
  1266. /* Accumulate error between NTP and clock interval */
  1267. tk->ntp_error += tk->ntp_tick << shift;
  1268. tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
  1269. (tk->ntp_error_shift + shift);
  1270. return offset;
  1271. }
  1272. /**
  1273. * update_wall_time - Uses the current clocksource to increment the wall time
  1274. *
  1275. */
  1276. void update_wall_time(void)
  1277. {
  1278. struct timekeeper *real_tk = &tk_core.timekeeper;
  1279. struct timekeeper *tk = &shadow_timekeeper;
  1280. cycle_t offset;
  1281. int shift = 0, maxshift;
  1282. unsigned int clock_set = 0;
  1283. unsigned long flags;
  1284. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1285. /* Make sure we're fully resumed: */
  1286. if (unlikely(timekeeping_suspended))
  1287. goto out;
  1288. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  1289. offset = real_tk->cycle_interval;
  1290. #else
  1291. offset = clocksource_delta(tk->tkr.read(tk->tkr.clock),
  1292. tk->tkr.cycle_last, tk->tkr.mask);
  1293. #endif
  1294. /* Check if there's really nothing to do */
  1295. if (offset < real_tk->cycle_interval)
  1296. goto out;
  1297. /*
  1298. * With NO_HZ we may have to accumulate many cycle_intervals
  1299. * (think "ticks") worth of time at once. To do this efficiently,
  1300. * we calculate the largest doubling multiple of cycle_intervals
  1301. * that is smaller than the offset. We then accumulate that
  1302. * chunk in one go, and then try to consume the next smaller
  1303. * doubled multiple.
  1304. */
  1305. shift = ilog2(offset) - ilog2(tk->cycle_interval);
  1306. shift = max(0, shift);
  1307. /* Bound shift to one less than what overflows tick_length */
  1308. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  1309. shift = min(shift, maxshift);
  1310. while (offset >= tk->cycle_interval) {
  1311. offset = logarithmic_accumulation(tk, offset, shift,
  1312. &clock_set);
  1313. if (offset < tk->cycle_interval<<shift)
  1314. shift--;
  1315. }
  1316. /* correct the clock when NTP error is too big */
  1317. timekeeping_adjust(tk, offset);
  1318. /*
  1319. * XXX This can be killed once everyone converts
  1320. * to the new update_vsyscall.
  1321. */
  1322. old_vsyscall_fixup(tk);
  1323. /*
  1324. * Finally, make sure that after the rounding
  1325. * xtime_nsec isn't larger than NSEC_PER_SEC
  1326. */
  1327. clock_set |= accumulate_nsecs_to_secs(tk);
  1328. write_seqcount_begin(&tk_core.seq);
  1329. /*
  1330. * Update the real timekeeper.
  1331. *
  1332. * We could avoid this memcpy by switching pointers, but that
  1333. * requires changes to all other timekeeper usage sites as
  1334. * well, i.e. move the timekeeper pointer getter into the
  1335. * spinlocked/seqcount protected sections. And we trade this
  1336. * memcpy under the tk_core.seq against one before we start
  1337. * updating.
  1338. */
  1339. memcpy(real_tk, tk, sizeof(*tk));
  1340. timekeeping_update(real_tk, clock_set);
  1341. write_seqcount_end(&tk_core.seq);
  1342. out:
  1343. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1344. if (clock_set)
  1345. /* Have to call _delayed version, since in irq context*/
  1346. clock_was_set_delayed();
  1347. }
  1348. /**
  1349. * getboottime - Return the real time of system boot.
  1350. * @ts: pointer to the timespec to be set
  1351. *
  1352. * Returns the wall-time of boot in a timespec.
  1353. *
  1354. * This is based on the wall_to_monotonic offset and the total suspend
  1355. * time. Calls to settimeofday will affect the value returned (which
  1356. * basically means that however wrong your real time clock is at boot time,
  1357. * you get the right time here).
  1358. */
  1359. void getboottime(struct timespec *ts)
  1360. {
  1361. struct timekeeper *tk = &tk_core.timekeeper;
  1362. ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
  1363. *ts = ktime_to_timespec(t);
  1364. }
  1365. EXPORT_SYMBOL_GPL(getboottime);
  1366. unsigned long get_seconds(void)
  1367. {
  1368. struct timekeeper *tk = &tk_core.timekeeper;
  1369. return tk->xtime_sec;
  1370. }
  1371. EXPORT_SYMBOL(get_seconds);
  1372. struct timespec __current_kernel_time(void)
  1373. {
  1374. struct timekeeper *tk = &tk_core.timekeeper;
  1375. return timespec64_to_timespec(tk_xtime(tk));
  1376. }
  1377. struct timespec current_kernel_time(void)
  1378. {
  1379. struct timekeeper *tk = &tk_core.timekeeper;
  1380. struct timespec64 now;
  1381. unsigned long seq;
  1382. do {
  1383. seq = read_seqcount_begin(&tk_core.seq);
  1384. now = tk_xtime(tk);
  1385. } while (read_seqcount_retry(&tk_core.seq, seq));
  1386. return timespec64_to_timespec(now);
  1387. }
  1388. EXPORT_SYMBOL(current_kernel_time);
  1389. struct timespec get_monotonic_coarse(void)
  1390. {
  1391. struct timekeeper *tk = &tk_core.timekeeper;
  1392. struct timespec64 now, mono;
  1393. unsigned long seq;
  1394. do {
  1395. seq = read_seqcount_begin(&tk_core.seq);
  1396. now = tk_xtime(tk);
  1397. mono = tk->wall_to_monotonic;
  1398. } while (read_seqcount_retry(&tk_core.seq, seq));
  1399. set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
  1400. now.tv_nsec + mono.tv_nsec);
  1401. return timespec64_to_timespec(now);
  1402. }
  1403. /*
  1404. * Must hold jiffies_lock
  1405. */
  1406. void do_timer(unsigned long ticks)
  1407. {
  1408. jiffies_64 += ticks;
  1409. calc_global_load(ticks);
  1410. }
  1411. /**
  1412. * ktime_get_update_offsets_tick - hrtimer helper
  1413. * @offs_real: pointer to storage for monotonic -> realtime offset
  1414. * @offs_boot: pointer to storage for monotonic -> boottime offset
  1415. * @offs_tai: pointer to storage for monotonic -> clock tai offset
  1416. *
  1417. * Returns monotonic time at last tick and various offsets
  1418. */
  1419. ktime_t ktime_get_update_offsets_tick(ktime_t *offs_real, ktime_t *offs_boot,
  1420. ktime_t *offs_tai)
  1421. {
  1422. struct timekeeper *tk = &tk_core.timekeeper;
  1423. unsigned int seq;
  1424. ktime_t base;
  1425. u64 nsecs;
  1426. do {
  1427. seq = read_seqcount_begin(&tk_core.seq);
  1428. base = tk->tkr.base_mono;
  1429. nsecs = tk->tkr.xtime_nsec >> tk->tkr.shift;
  1430. *offs_real = tk->offs_real;
  1431. *offs_boot = tk->offs_boot;
  1432. *offs_tai = tk->offs_tai;
  1433. } while (read_seqcount_retry(&tk_core.seq, seq));
  1434. return ktime_add_ns(base, nsecs);
  1435. }
  1436. #ifdef CONFIG_HIGH_RES_TIMERS
  1437. /**
  1438. * ktime_get_update_offsets_now - hrtimer helper
  1439. * @offs_real: pointer to storage for monotonic -> realtime offset
  1440. * @offs_boot: pointer to storage for monotonic -> boottime offset
  1441. * @offs_tai: pointer to storage for monotonic -> clock tai offset
  1442. *
  1443. * Returns current monotonic time and updates the offsets
  1444. * Called from hrtimer_interrupt() or retrigger_next_event()
  1445. */
  1446. ktime_t ktime_get_update_offsets_now(ktime_t *offs_real, ktime_t *offs_boot,
  1447. ktime_t *offs_tai)
  1448. {
  1449. struct timekeeper *tk = &tk_core.timekeeper;
  1450. unsigned int seq;
  1451. ktime_t base;
  1452. u64 nsecs;
  1453. do {
  1454. seq = read_seqcount_begin(&tk_core.seq);
  1455. base = tk->tkr.base_mono;
  1456. nsecs = timekeeping_get_ns(&tk->tkr);
  1457. *offs_real = tk->offs_real;
  1458. *offs_boot = tk->offs_boot;
  1459. *offs_tai = tk->offs_tai;
  1460. } while (read_seqcount_retry(&tk_core.seq, seq));
  1461. return ktime_add_ns(base, nsecs);
  1462. }
  1463. #endif
  1464. /**
  1465. * do_adjtimex() - Accessor function to NTP __do_adjtimex function
  1466. */
  1467. int do_adjtimex(struct timex *txc)
  1468. {
  1469. struct timekeeper *tk = &tk_core.timekeeper;
  1470. unsigned long flags;
  1471. struct timespec64 ts;
  1472. s32 orig_tai, tai;
  1473. int ret;
  1474. /* Validate the data before disabling interrupts */
  1475. ret = ntp_validate_timex(txc);
  1476. if (ret)
  1477. return ret;
  1478. if (txc->modes & ADJ_SETOFFSET) {
  1479. struct timespec delta;
  1480. delta.tv_sec = txc->time.tv_sec;
  1481. delta.tv_nsec = txc->time.tv_usec;
  1482. if (!(txc->modes & ADJ_NANO))
  1483. delta.tv_nsec *= 1000;
  1484. ret = timekeeping_inject_offset(&delta);
  1485. if (ret)
  1486. return ret;
  1487. }
  1488. getnstimeofday64(&ts);
  1489. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1490. write_seqcount_begin(&tk_core.seq);
  1491. orig_tai = tai = tk->tai_offset;
  1492. ret = __do_adjtimex(txc, &ts, &tai);
  1493. if (tai != orig_tai) {
  1494. __timekeeping_set_tai_offset(tk, tai);
  1495. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  1496. }
  1497. write_seqcount_end(&tk_core.seq);
  1498. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1499. if (tai != orig_tai)
  1500. clock_was_set();
  1501. ntp_notify_cmos_timer();
  1502. return ret;
  1503. }
  1504. #ifdef CONFIG_NTP_PPS
  1505. /**
  1506. * hardpps() - Accessor function to NTP __hardpps function
  1507. */
  1508. void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
  1509. {
  1510. unsigned long flags;
  1511. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1512. write_seqcount_begin(&tk_core.seq);
  1513. __hardpps(phase_ts, raw_ts);
  1514. write_seqcount_end(&tk_core.seq);
  1515. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1516. }
  1517. EXPORT_SYMBOL(hardpps);
  1518. #endif
  1519. /**
  1520. * xtime_update() - advances the timekeeping infrastructure
  1521. * @ticks: number of ticks, that have elapsed since the last call.
  1522. *
  1523. * Must be called with interrupts disabled.
  1524. */
  1525. void xtime_update(unsigned long ticks)
  1526. {
  1527. write_seqlock(&jiffies_lock);
  1528. do_timer(ticks);
  1529. write_sequnlock(&jiffies_lock);
  1530. update_wall_time();
  1531. }