timekeeping.c 55 KB

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