timekeeping.c 57 KB

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