timekeeping.c 55 KB

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