timekeeping.c 56 KB

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