timekeeping.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Kernel timekeeping code and accessor functions. Based on code from
  4. * timer.c, moved in commit 8524070b7982.
  5. */
  6. #include <linux/timekeeper_internal.h>
  7. #include <linux/module.h>
  8. #include <linux/interrupt.h>
  9. #include <linux/percpu.h>
  10. #include <linux/init.h>
  11. #include <linux/mm.h>
  12. #include <linux/nmi.h>
  13. #include <linux/sched.h>
  14. #include <linux/sched/loadavg.h>
  15. #include <linux/sched/clock.h>
  16. #include <linux/syscore_ops.h>
  17. #include <linux/clocksource.h>
  18. #include <linux/jiffies.h>
  19. #include <linux/time.h>
  20. #include <linux/timex.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 <linux/audit.h>
  26. #include <linux/random.h>
  27. #include "tick-internal.h"
  28. #include "ntp_internal.h"
  29. #include "timekeeping_internal.h"
  30. #define TK_CLEAR_NTP (1 << 0)
  31. #define TK_MIRROR (1 << 1)
  32. #define TK_CLOCK_WAS_SET (1 << 2)
  33. enum timekeeping_adv_mode {
  34. /* Update timekeeper when a tick has passed */
  35. TK_ADV_TICK,
  36. /* Update timekeeper on a direct frequency change */
  37. TK_ADV_FREQ
  38. };
  39. DEFINE_RAW_SPINLOCK(timekeeper_lock);
  40. /*
  41. * The most important data for readout fits into a single 64 byte
  42. * cache line.
  43. */
  44. static struct {
  45. seqcount_raw_spinlock_t seq;
  46. struct timekeeper timekeeper;
  47. } tk_core ____cacheline_aligned = {
  48. .seq = SEQCNT_RAW_SPINLOCK_ZERO(tk_core.seq, &timekeeper_lock),
  49. };
  50. static struct timekeeper shadow_timekeeper;
  51. /* flag for if timekeeping is suspended */
  52. int __read_mostly timekeeping_suspended;
  53. /**
  54. * struct tk_fast - NMI safe timekeeper
  55. * @seq: Sequence counter for protecting updates. The lowest bit
  56. * is the index for the tk_read_base array
  57. * @base: tk_read_base array. Access is indexed by the lowest bit of
  58. * @seq.
  59. *
  60. * See @update_fast_timekeeper() below.
  61. */
  62. struct tk_fast {
  63. seqcount_latch_t seq;
  64. struct tk_read_base base[2];
  65. };
  66. /* Suspend-time cycles value for halted fast timekeeper. */
  67. static u64 cycles_at_suspend;
  68. static u64 dummy_clock_read(struct clocksource *cs)
  69. {
  70. if (timekeeping_suspended)
  71. return cycles_at_suspend;
  72. return local_clock();
  73. }
  74. static struct clocksource dummy_clock = {
  75. .read = dummy_clock_read,
  76. };
  77. /*
  78. * Boot time initialization which allows local_clock() to be utilized
  79. * during early boot when clocksources are not available. local_clock()
  80. * returns nanoseconds already so no conversion is required, hence mult=1
  81. * and shift=0. When the first proper clocksource is installed then
  82. * the fast time keepers are updated with the correct values.
  83. */
  84. #define FAST_TK_INIT \
  85. { \
  86. .clock = &dummy_clock, \
  87. .mask = CLOCKSOURCE_MASK(64), \
  88. .mult = 1, \
  89. .shift = 0, \
  90. }
  91. static struct tk_fast tk_fast_mono ____cacheline_aligned = {
  92. .seq = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
  93. .base[0] = FAST_TK_INIT,
  94. .base[1] = FAST_TK_INIT,
  95. };
  96. static struct tk_fast tk_fast_raw ____cacheline_aligned = {
  97. .seq = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
  98. .base[0] = FAST_TK_INIT,
  99. .base[1] = FAST_TK_INIT,
  100. };
  101. static inline void tk_normalize_xtime(struct timekeeper *tk)
  102. {
  103. while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
  104. tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
  105. tk->xtime_sec++;
  106. }
  107. while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
  108. tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
  109. tk->raw_sec++;
  110. }
  111. }
  112. static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
  113. {
  114. struct timespec64 ts;
  115. ts.tv_sec = tk->xtime_sec;
  116. ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
  117. return ts;
  118. }
  119. static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
  120. {
  121. tk->xtime_sec = ts->tv_sec;
  122. tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
  123. }
  124. static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
  125. {
  126. tk->xtime_sec += ts->tv_sec;
  127. tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
  128. tk_normalize_xtime(tk);
  129. }
  130. static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
  131. {
  132. struct timespec64 tmp;
  133. /*
  134. * Verify consistency of: offset_real = -wall_to_monotonic
  135. * before modifying anything
  136. */
  137. set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
  138. -tk->wall_to_monotonic.tv_nsec);
  139. WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
  140. tk->wall_to_monotonic = wtm;
  141. set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
  142. tk->offs_real = timespec64_to_ktime(tmp);
  143. tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
  144. }
  145. static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
  146. {
  147. tk->offs_boot = ktime_add(tk->offs_boot, delta);
  148. /*
  149. * Timespec representation for VDSO update to avoid 64bit division
  150. * on every update.
  151. */
  152. tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
  153. }
  154. /*
  155. * tk_clock_read - atomic clocksource read() helper
  156. *
  157. * This helper is necessary to use in the read paths because, while the
  158. * seqcount ensures we don't return a bad value while structures are updated,
  159. * it doesn't protect from potential crashes. There is the possibility that
  160. * the tkr's clocksource may change between the read reference, and the
  161. * clock reference passed to the read function. This can cause crashes if
  162. * the wrong clocksource is passed to the wrong read function.
  163. * This isn't necessary to use when holding the timekeeper_lock or doing
  164. * a read of the fast-timekeeper tkrs (which is protected by its own locking
  165. * and update logic).
  166. */
  167. static inline u64 tk_clock_read(const struct tk_read_base *tkr)
  168. {
  169. struct clocksource *clock = READ_ONCE(tkr->clock);
  170. return clock->read(clock);
  171. }
  172. /**
  173. * tk_setup_internals - Set up internals to use clocksource clock.
  174. *
  175. * @tk: The target timekeeper to setup.
  176. * @clock: Pointer to clocksource.
  177. *
  178. * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
  179. * pair and interval request.
  180. *
  181. * Unless you're the timekeeping code, you should not be using this!
  182. */
  183. static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
  184. {
  185. u64 interval;
  186. u64 tmp, ntpinterval;
  187. struct clocksource *old_clock;
  188. ++tk->cs_was_changed_seq;
  189. old_clock = tk->tkr_mono.clock;
  190. tk->tkr_mono.clock = clock;
  191. tk->tkr_mono.mask = clock->mask;
  192. tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
  193. tk->tkr_raw.clock = clock;
  194. tk->tkr_raw.mask = clock->mask;
  195. tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
  196. /* Do the ns -> cycle conversion first, using original mult */
  197. tmp = NTP_INTERVAL_LENGTH;
  198. tmp <<= clock->shift;
  199. ntpinterval = tmp;
  200. tmp += clock->mult/2;
  201. do_div(tmp, clock->mult);
  202. if (tmp == 0)
  203. tmp = 1;
  204. interval = (u64) tmp;
  205. tk->cycle_interval = interval;
  206. /* Go back from cycles -> shifted ns */
  207. tk->xtime_interval = interval * clock->mult;
  208. tk->xtime_remainder = ntpinterval - tk->xtime_interval;
  209. tk->raw_interval = interval * clock->mult;
  210. /* if changing clocks, convert xtime_nsec shift units */
  211. if (old_clock) {
  212. int shift_change = clock->shift - old_clock->shift;
  213. if (shift_change < 0) {
  214. tk->tkr_mono.xtime_nsec >>= -shift_change;
  215. tk->tkr_raw.xtime_nsec >>= -shift_change;
  216. } else {
  217. tk->tkr_mono.xtime_nsec <<= shift_change;
  218. tk->tkr_raw.xtime_nsec <<= shift_change;
  219. }
  220. }
  221. tk->tkr_mono.shift = clock->shift;
  222. tk->tkr_raw.shift = clock->shift;
  223. tk->ntp_error = 0;
  224. tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
  225. tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
  226. /*
  227. * The timekeeper keeps its own mult values for the currently
  228. * active clocksource. These value will be adjusted via NTP
  229. * to counteract clock drifting.
  230. */
  231. tk->tkr_mono.mult = clock->mult;
  232. tk->tkr_raw.mult = clock->mult;
  233. tk->ntp_err_mult = 0;
  234. tk->skip_second_overflow = 0;
  235. }
  236. /* Timekeeper helper functions. */
  237. static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta)
  238. {
  239. return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift);
  240. }
  241. static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
  242. {
  243. /* Calculate the delta since the last update_wall_time() */
  244. u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask;
  245. /*
  246. * This detects both negative motion and the case where the delta
  247. * overflows the multiplication with tkr->mult.
  248. */
  249. if (unlikely(delta > tkr->clock->max_cycles)) {
  250. /*
  251. * Handle clocksource inconsistency between CPUs to prevent
  252. * time from going backwards by checking for the MSB of the
  253. * mask being set in the delta.
  254. */
  255. if (delta & ~(mask >> 1))
  256. return tkr->xtime_nsec >> tkr->shift;
  257. return delta_to_ns_safe(tkr, delta);
  258. }
  259. return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift;
  260. }
  261. static __always_inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
  262. {
  263. return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr));
  264. }
  265. /**
  266. * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
  267. * @tkr: Timekeeping readout base from which we take the update
  268. * @tkf: Pointer to NMI safe timekeeper
  269. *
  270. * We want to use this from any context including NMI and tracing /
  271. * instrumenting the timekeeping code itself.
  272. *
  273. * Employ the latch technique; see @raw_write_seqcount_latch.
  274. *
  275. * So if a NMI hits the update of base[0] then it will use base[1]
  276. * which is still consistent. In the worst case this can result is a
  277. * slightly wrong timestamp (a few nanoseconds). See
  278. * @ktime_get_mono_fast_ns.
  279. */
  280. static void update_fast_timekeeper(const struct tk_read_base *tkr,
  281. struct tk_fast *tkf)
  282. {
  283. struct tk_read_base *base = tkf->base;
  284. /* Force readers off to base[1] */
  285. raw_write_seqcount_latch(&tkf->seq);
  286. /* Update base[0] */
  287. memcpy(base, tkr, sizeof(*base));
  288. /* Force readers back to base[0] */
  289. raw_write_seqcount_latch(&tkf->seq);
  290. /* Update base[1] */
  291. memcpy(base + 1, base, sizeof(*base));
  292. }
  293. static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
  294. {
  295. struct tk_read_base *tkr;
  296. unsigned int seq;
  297. u64 now;
  298. do {
  299. seq = raw_read_seqcount_latch(&tkf->seq);
  300. tkr = tkf->base + (seq & 0x01);
  301. now = ktime_to_ns(tkr->base);
  302. now += timekeeping_get_ns(tkr);
  303. } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
  304. return now;
  305. }
  306. /**
  307. * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
  308. *
  309. * This timestamp is not guaranteed to be monotonic across an update.
  310. * The timestamp is calculated by:
  311. *
  312. * now = base_mono + clock_delta * slope
  313. *
  314. * So if the update lowers the slope, readers who are forced to the
  315. * not yet updated second array are still using the old steeper slope.
  316. *
  317. * tmono
  318. * ^
  319. * | o n
  320. * | o n
  321. * | u
  322. * | o
  323. * |o
  324. * |12345678---> reader order
  325. *
  326. * o = old slope
  327. * u = update
  328. * n = new slope
  329. *
  330. * So reader 6 will observe time going backwards versus reader 5.
  331. *
  332. * While other CPUs are likely to be able to observe that, the only way
  333. * for a CPU local observation is when an NMI hits in the middle of
  334. * the update. Timestamps taken from that NMI context might be ahead
  335. * of the following timestamps. Callers need to be aware of that and
  336. * deal with it.
  337. */
  338. u64 notrace ktime_get_mono_fast_ns(void)
  339. {
  340. return __ktime_get_fast_ns(&tk_fast_mono);
  341. }
  342. EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
  343. /**
  344. * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
  345. *
  346. * Contrary to ktime_get_mono_fast_ns() this is always correct because the
  347. * conversion factor is not affected by NTP/PTP correction.
  348. */
  349. u64 notrace ktime_get_raw_fast_ns(void)
  350. {
  351. return __ktime_get_fast_ns(&tk_fast_raw);
  352. }
  353. EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
  354. /**
  355. * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
  356. *
  357. * To keep it NMI safe since we're accessing from tracing, we're not using a
  358. * separate timekeeper with updates to monotonic clock and boot offset
  359. * protected with seqcounts. This has the following minor side effects:
  360. *
  361. * (1) Its possible that a timestamp be taken after the boot offset is updated
  362. * but before the timekeeper is updated. If this happens, the new boot offset
  363. * is added to the old timekeeping making the clock appear to update slightly
  364. * earlier:
  365. * CPU 0 CPU 1
  366. * timekeeping_inject_sleeptime64()
  367. * __timekeeping_inject_sleeptime(tk, delta);
  368. * timestamp();
  369. * timekeeping_update(tk, TK_CLEAR_NTP...);
  370. *
  371. * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
  372. * partially updated. Since the tk->offs_boot update is a rare event, this
  373. * should be a rare occurrence which postprocessing should be able to handle.
  374. *
  375. * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
  376. * apply as well.
  377. */
  378. u64 notrace ktime_get_boot_fast_ns(void)
  379. {
  380. struct timekeeper *tk = &tk_core.timekeeper;
  381. return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
  382. }
  383. EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
  384. /**
  385. * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
  386. *
  387. * The same limitations as described for ktime_get_boot_fast_ns() apply. The
  388. * mono time and the TAI offset are not read atomically which may yield wrong
  389. * readouts. However, an update of the TAI offset is an rare event e.g., caused
  390. * by settime or adjtimex with an offset. The user of this function has to deal
  391. * with the possibility of wrong timestamps in post processing.
  392. */
  393. u64 notrace ktime_get_tai_fast_ns(void)
  394. {
  395. struct timekeeper *tk = &tk_core.timekeeper;
  396. return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
  397. }
  398. EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
  399. static __always_inline u64 __ktime_get_real_fast(struct tk_fast *tkf, u64 *mono)
  400. {
  401. struct tk_read_base *tkr;
  402. u64 basem, baser, delta;
  403. unsigned int seq;
  404. do {
  405. seq = raw_read_seqcount_latch(&tkf->seq);
  406. tkr = tkf->base + (seq & 0x01);
  407. basem = ktime_to_ns(tkr->base);
  408. baser = ktime_to_ns(tkr->base_real);
  409. delta = timekeeping_get_ns(tkr);
  410. } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
  411. if (mono)
  412. *mono = basem + delta;
  413. return baser + delta;
  414. }
  415. /**
  416. * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
  417. *
  418. * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
  419. */
  420. u64 ktime_get_real_fast_ns(void)
  421. {
  422. return __ktime_get_real_fast(&tk_fast_mono, NULL);
  423. }
  424. EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
  425. /**
  426. * ktime_get_fast_timestamps: - NMI safe timestamps
  427. * @snapshot: Pointer to timestamp storage
  428. *
  429. * Stores clock monotonic, boottime and realtime timestamps.
  430. *
  431. * Boot time is a racy access on 32bit systems if the sleep time injection
  432. * happens late during resume and not in timekeeping_resume(). That could
  433. * be avoided by expanding struct tk_read_base with boot offset for 32bit
  434. * and adding more overhead to the update. As this is a hard to observe
  435. * once per resume event which can be filtered with reasonable effort using
  436. * the accurate mono/real timestamps, it's probably not worth the trouble.
  437. *
  438. * Aside of that it might be possible on 32 and 64 bit to observe the
  439. * following when the sleep time injection happens late:
  440. *
  441. * CPU 0 CPU 1
  442. * timekeeping_resume()
  443. * ktime_get_fast_timestamps()
  444. * mono, real = __ktime_get_real_fast()
  445. * inject_sleep_time()
  446. * update boot offset
  447. * boot = mono + bootoffset;
  448. *
  449. * That means that boot time already has the sleep time adjustment, but
  450. * real time does not. On the next readout both are in sync again.
  451. *
  452. * Preventing this for 64bit is not really feasible without destroying the
  453. * careful cache layout of the timekeeper because the sequence count and
  454. * struct tk_read_base would then need two cache lines instead of one.
  455. *
  456. * Access to the time keeper clock source is disabled across the innermost
  457. * steps of suspend/resume. The accessors still work, but the timestamps
  458. * are frozen until time keeping is resumed which happens very early.
  459. *
  460. * For regular suspend/resume there is no observable difference vs. sched
  461. * clock, but it might affect some of the nasty low level debug printks.
  462. *
  463. * OTOH, access to sched clock is not guaranteed across suspend/resume on
  464. * all systems either so it depends on the hardware in use.
  465. *
  466. * If that turns out to be a real problem then this could be mitigated by
  467. * using sched clock in a similar way as during early boot. But it's not as
  468. * trivial as on early boot because it needs some careful protection
  469. * against the clock monotonic timestamp jumping backwards on resume.
  470. */
  471. void ktime_get_fast_timestamps(struct ktime_timestamps *snapshot)
  472. {
  473. struct timekeeper *tk = &tk_core.timekeeper;
  474. snapshot->real = __ktime_get_real_fast(&tk_fast_mono, &snapshot->mono);
  475. snapshot->boot = snapshot->mono + ktime_to_ns(data_race(tk->offs_boot));
  476. }
  477. /**
  478. * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
  479. * @tk: Timekeeper to snapshot.
  480. *
  481. * It generally is unsafe to access the clocksource after timekeeping has been
  482. * suspended, so take a snapshot of the readout base of @tk and use it as the
  483. * fast timekeeper's readout base while suspended. It will return the same
  484. * number of cycles every time until timekeeping is resumed at which time the
  485. * proper readout base for the fast timekeeper will be restored automatically.
  486. */
  487. static void halt_fast_timekeeper(const struct timekeeper *tk)
  488. {
  489. static struct tk_read_base tkr_dummy;
  490. const struct tk_read_base *tkr = &tk->tkr_mono;
  491. memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
  492. cycles_at_suspend = tk_clock_read(tkr);
  493. tkr_dummy.clock = &dummy_clock;
  494. tkr_dummy.base_real = tkr->base + tk->offs_real;
  495. update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
  496. tkr = &tk->tkr_raw;
  497. memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
  498. tkr_dummy.clock = &dummy_clock;
  499. update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
  500. }
  501. static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
  502. static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
  503. {
  504. raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
  505. }
  506. /**
  507. * pvclock_gtod_register_notifier - register a pvclock timedata update listener
  508. * @nb: Pointer to the notifier block to register
  509. */
  510. int pvclock_gtod_register_notifier(struct notifier_block *nb)
  511. {
  512. struct timekeeper *tk = &tk_core.timekeeper;
  513. unsigned long flags;
  514. int ret;
  515. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  516. ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
  517. update_pvclock_gtod(tk, true);
  518. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  519. return ret;
  520. }
  521. EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
  522. /**
  523. * pvclock_gtod_unregister_notifier - unregister a pvclock
  524. * timedata update listener
  525. * @nb: Pointer to the notifier block to unregister
  526. */
  527. int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
  528. {
  529. unsigned long flags;
  530. int ret;
  531. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  532. ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
  533. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  534. return ret;
  535. }
  536. EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
  537. /*
  538. * tk_update_leap_state - helper to update the next_leap_ktime
  539. */
  540. static inline void tk_update_leap_state(struct timekeeper *tk)
  541. {
  542. tk->next_leap_ktime = ntp_get_next_leap();
  543. if (tk->next_leap_ktime != KTIME_MAX)
  544. /* Convert to monotonic time */
  545. tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
  546. }
  547. /*
  548. * Update the ktime_t based scalar nsec members of the timekeeper
  549. */
  550. static inline void tk_update_ktime_data(struct timekeeper *tk)
  551. {
  552. u64 seconds;
  553. u32 nsec;
  554. /*
  555. * The xtime based monotonic readout is:
  556. * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
  557. * The ktime based monotonic readout is:
  558. * nsec = base_mono + now();
  559. * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
  560. */
  561. seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
  562. nsec = (u32) tk->wall_to_monotonic.tv_nsec;
  563. tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
  564. /*
  565. * The sum of the nanoseconds portions of xtime and
  566. * wall_to_monotonic can be greater/equal one second. Take
  567. * this into account before updating tk->ktime_sec.
  568. */
  569. nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
  570. if (nsec >= NSEC_PER_SEC)
  571. seconds++;
  572. tk->ktime_sec = seconds;
  573. /* Update the monotonic raw base */
  574. tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
  575. }
  576. /* must hold timekeeper_lock */
  577. static void timekeeping_update(struct timekeeper *tk, unsigned int action)
  578. {
  579. if (action & TK_CLEAR_NTP) {
  580. tk->ntp_error = 0;
  581. ntp_clear();
  582. }
  583. tk_update_leap_state(tk);
  584. tk_update_ktime_data(tk);
  585. update_vsyscall(tk);
  586. update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
  587. tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
  588. update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
  589. update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
  590. if (action & TK_CLOCK_WAS_SET)
  591. tk->clock_was_set_seq++;
  592. /*
  593. * The mirroring of the data to the shadow-timekeeper needs
  594. * to happen last here to ensure we don't over-write the
  595. * timekeeper structure on the next update with stale data
  596. */
  597. if (action & TK_MIRROR)
  598. memcpy(&shadow_timekeeper, &tk_core.timekeeper,
  599. sizeof(tk_core.timekeeper));
  600. }
  601. /**
  602. * timekeeping_forward_now - update clock to the current time
  603. * @tk: Pointer to the timekeeper to update
  604. *
  605. * Forward the current clock to update its state since the last call to
  606. * update_wall_time(). This is useful before significant clock changes,
  607. * as it avoids having to deal with this time offset explicitly.
  608. */
  609. static void timekeeping_forward_now(struct timekeeper *tk)
  610. {
  611. u64 cycle_now, delta;
  612. cycle_now = tk_clock_read(&tk->tkr_mono);
  613. delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
  614. tk->tkr_mono.clock->max_raw_delta);
  615. tk->tkr_mono.cycle_last = cycle_now;
  616. tk->tkr_raw.cycle_last = cycle_now;
  617. while (delta > 0) {
  618. u64 max = tk->tkr_mono.clock->max_cycles;
  619. u64 incr = delta < max ? delta : max;
  620. tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
  621. tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
  622. tk_normalize_xtime(tk);
  623. delta -= incr;
  624. }
  625. }
  626. /**
  627. * ktime_get_real_ts64 - Returns the time of day in a timespec64.
  628. * @ts: pointer to the timespec to be set
  629. *
  630. * Returns the time of day in a timespec64 (WARN if suspended).
  631. */
  632. void ktime_get_real_ts64(struct timespec64 *ts)
  633. {
  634. struct timekeeper *tk = &tk_core.timekeeper;
  635. unsigned int seq;
  636. u64 nsecs;
  637. WARN_ON(timekeeping_suspended);
  638. do {
  639. seq = read_seqcount_begin(&tk_core.seq);
  640. ts->tv_sec = tk->xtime_sec;
  641. nsecs = timekeeping_get_ns(&tk->tkr_mono);
  642. } while (read_seqcount_retry(&tk_core.seq, seq));
  643. ts->tv_nsec = 0;
  644. timespec64_add_ns(ts, nsecs);
  645. }
  646. EXPORT_SYMBOL(ktime_get_real_ts64);
  647. ktime_t ktime_get(void)
  648. {
  649. struct timekeeper *tk = &tk_core.timekeeper;
  650. unsigned int seq;
  651. ktime_t base;
  652. u64 nsecs;
  653. WARN_ON(timekeeping_suspended);
  654. do {
  655. seq = read_seqcount_begin(&tk_core.seq);
  656. base = tk->tkr_mono.base;
  657. nsecs = timekeeping_get_ns(&tk->tkr_mono);
  658. } while (read_seqcount_retry(&tk_core.seq, seq));
  659. return ktime_add_ns(base, nsecs);
  660. }
  661. EXPORT_SYMBOL_GPL(ktime_get);
  662. u32 ktime_get_resolution_ns(void)
  663. {
  664. struct timekeeper *tk = &tk_core.timekeeper;
  665. unsigned int seq;
  666. u32 nsecs;
  667. WARN_ON(timekeeping_suspended);
  668. do {
  669. seq = read_seqcount_begin(&tk_core.seq);
  670. nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
  671. } while (read_seqcount_retry(&tk_core.seq, seq));
  672. return nsecs;
  673. }
  674. EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
  675. static ktime_t *offsets[TK_OFFS_MAX] = {
  676. [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
  677. [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
  678. [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
  679. };
  680. ktime_t ktime_get_with_offset(enum tk_offsets offs)
  681. {
  682. struct timekeeper *tk = &tk_core.timekeeper;
  683. unsigned int seq;
  684. ktime_t base, *offset = offsets[offs];
  685. u64 nsecs;
  686. WARN_ON(timekeeping_suspended);
  687. do {
  688. seq = read_seqcount_begin(&tk_core.seq);
  689. base = ktime_add(tk->tkr_mono.base, *offset);
  690. nsecs = timekeeping_get_ns(&tk->tkr_mono);
  691. } while (read_seqcount_retry(&tk_core.seq, seq));
  692. return ktime_add_ns(base, nsecs);
  693. }
  694. EXPORT_SYMBOL_GPL(ktime_get_with_offset);
  695. ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
  696. {
  697. struct timekeeper *tk = &tk_core.timekeeper;
  698. unsigned int seq;
  699. ktime_t base, *offset = offsets[offs];
  700. u64 nsecs;
  701. WARN_ON(timekeeping_suspended);
  702. do {
  703. seq = read_seqcount_begin(&tk_core.seq);
  704. base = ktime_add(tk->tkr_mono.base, *offset);
  705. nsecs = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
  706. } while (read_seqcount_retry(&tk_core.seq, seq));
  707. return ktime_add_ns(base, nsecs);
  708. }
  709. EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
  710. /**
  711. * ktime_mono_to_any() - convert monotonic time to any other time
  712. * @tmono: time to convert.
  713. * @offs: which offset to use
  714. */
  715. ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
  716. {
  717. ktime_t *offset = offsets[offs];
  718. unsigned int seq;
  719. ktime_t tconv;
  720. do {
  721. seq = read_seqcount_begin(&tk_core.seq);
  722. tconv = ktime_add(tmono, *offset);
  723. } while (read_seqcount_retry(&tk_core.seq, seq));
  724. return tconv;
  725. }
  726. EXPORT_SYMBOL_GPL(ktime_mono_to_any);
  727. /**
  728. * ktime_get_raw - Returns the raw monotonic time in ktime_t format
  729. */
  730. ktime_t ktime_get_raw(void)
  731. {
  732. struct timekeeper *tk = &tk_core.timekeeper;
  733. unsigned int seq;
  734. ktime_t base;
  735. u64 nsecs;
  736. do {
  737. seq = read_seqcount_begin(&tk_core.seq);
  738. base = tk->tkr_raw.base;
  739. nsecs = timekeeping_get_ns(&tk->tkr_raw);
  740. } while (read_seqcount_retry(&tk_core.seq, seq));
  741. return ktime_add_ns(base, nsecs);
  742. }
  743. EXPORT_SYMBOL_GPL(ktime_get_raw);
  744. /**
  745. * ktime_get_ts64 - get the monotonic clock in timespec64 format
  746. * @ts: pointer to timespec variable
  747. *
  748. * The function calculates the monotonic clock from the realtime
  749. * clock and the wall_to_monotonic offset and stores the result
  750. * in normalized timespec64 format in the variable pointed to by @ts.
  751. */
  752. void ktime_get_ts64(struct timespec64 *ts)
  753. {
  754. struct timekeeper *tk = &tk_core.timekeeper;
  755. struct timespec64 tomono;
  756. unsigned int seq;
  757. u64 nsec;
  758. WARN_ON(timekeeping_suspended);
  759. do {
  760. seq = read_seqcount_begin(&tk_core.seq);
  761. ts->tv_sec = tk->xtime_sec;
  762. nsec = timekeeping_get_ns(&tk->tkr_mono);
  763. tomono = tk->wall_to_monotonic;
  764. } while (read_seqcount_retry(&tk_core.seq, seq));
  765. ts->tv_sec += tomono.tv_sec;
  766. ts->tv_nsec = 0;
  767. timespec64_add_ns(ts, nsec + tomono.tv_nsec);
  768. }
  769. EXPORT_SYMBOL_GPL(ktime_get_ts64);
  770. /**
  771. * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
  772. *
  773. * Returns the seconds portion of CLOCK_MONOTONIC with a single non
  774. * serialized read. tk->ktime_sec is of type 'unsigned long' so this
  775. * works on both 32 and 64 bit systems. On 32 bit systems the readout
  776. * covers ~136 years of uptime which should be enough to prevent
  777. * premature wrap arounds.
  778. */
  779. time64_t ktime_get_seconds(void)
  780. {
  781. struct timekeeper *tk = &tk_core.timekeeper;
  782. WARN_ON(timekeeping_suspended);
  783. return tk->ktime_sec;
  784. }
  785. EXPORT_SYMBOL_GPL(ktime_get_seconds);
  786. /**
  787. * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
  788. *
  789. * Returns the wall clock seconds since 1970.
  790. *
  791. * For 64bit systems the fast access to tk->xtime_sec is preserved. On
  792. * 32bit systems the access must be protected with the sequence
  793. * counter to provide "atomic" access to the 64bit tk->xtime_sec
  794. * value.
  795. */
  796. time64_t ktime_get_real_seconds(void)
  797. {
  798. struct timekeeper *tk = &tk_core.timekeeper;
  799. time64_t seconds;
  800. unsigned int seq;
  801. if (IS_ENABLED(CONFIG_64BIT))
  802. return tk->xtime_sec;
  803. do {
  804. seq = read_seqcount_begin(&tk_core.seq);
  805. seconds = tk->xtime_sec;
  806. } while (read_seqcount_retry(&tk_core.seq, seq));
  807. return seconds;
  808. }
  809. EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
  810. /**
  811. * __ktime_get_real_seconds - The same as ktime_get_real_seconds
  812. * but without the sequence counter protect. This internal function
  813. * is called just when timekeeping lock is already held.
  814. */
  815. noinstr time64_t __ktime_get_real_seconds(void)
  816. {
  817. struct timekeeper *tk = &tk_core.timekeeper;
  818. return tk->xtime_sec;
  819. }
  820. /**
  821. * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
  822. * @systime_snapshot: pointer to struct receiving the system time snapshot
  823. */
  824. void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
  825. {
  826. struct timekeeper *tk = &tk_core.timekeeper;
  827. unsigned int seq;
  828. ktime_t base_raw;
  829. ktime_t base_real;
  830. u64 nsec_raw;
  831. u64 nsec_real;
  832. u64 now;
  833. WARN_ON_ONCE(timekeeping_suspended);
  834. do {
  835. seq = read_seqcount_begin(&tk_core.seq);
  836. now = tk_clock_read(&tk->tkr_mono);
  837. systime_snapshot->cs_id = tk->tkr_mono.clock->id;
  838. systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
  839. systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
  840. base_real = ktime_add(tk->tkr_mono.base,
  841. tk_core.timekeeper.offs_real);
  842. base_raw = tk->tkr_raw.base;
  843. nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
  844. nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
  845. } while (read_seqcount_retry(&tk_core.seq, seq));
  846. systime_snapshot->cycles = now;
  847. systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
  848. systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
  849. }
  850. EXPORT_SYMBOL_GPL(ktime_get_snapshot);
  851. /* Scale base by mult/div checking for overflow */
  852. static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
  853. {
  854. u64 tmp, rem;
  855. tmp = div64_u64_rem(*base, div, &rem);
  856. if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
  857. ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
  858. return -EOVERFLOW;
  859. tmp *= mult;
  860. rem = div64_u64(rem * mult, div);
  861. *base = tmp + rem;
  862. return 0;
  863. }
  864. /**
  865. * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
  866. * @history: Snapshot representing start of history
  867. * @partial_history_cycles: Cycle offset into history (fractional part)
  868. * @total_history_cycles: Total history length in cycles
  869. * @discontinuity: True indicates clock was set on history period
  870. * @ts: Cross timestamp that should be adjusted using
  871. * partial/total ratio
  872. *
  873. * Helper function used by get_device_system_crosststamp() to correct the
  874. * crosstimestamp corresponding to the start of the current interval to the
  875. * system counter value (timestamp point) provided by the driver. The
  876. * total_history_* quantities are the total history starting at the provided
  877. * reference point and ending at the start of the current interval. The cycle
  878. * count between the driver timestamp point and the start of the current
  879. * interval is partial_history_cycles.
  880. */
  881. static int adjust_historical_crosststamp(struct system_time_snapshot *history,
  882. u64 partial_history_cycles,
  883. u64 total_history_cycles,
  884. bool discontinuity,
  885. struct system_device_crosststamp *ts)
  886. {
  887. struct timekeeper *tk = &tk_core.timekeeper;
  888. u64 corr_raw, corr_real;
  889. bool interp_forward;
  890. int ret;
  891. if (total_history_cycles == 0 || partial_history_cycles == 0)
  892. return 0;
  893. /* Interpolate shortest distance from beginning or end of history */
  894. interp_forward = partial_history_cycles > total_history_cycles / 2;
  895. partial_history_cycles = interp_forward ?
  896. total_history_cycles - partial_history_cycles :
  897. partial_history_cycles;
  898. /*
  899. * Scale the monotonic raw time delta by:
  900. * partial_history_cycles / total_history_cycles
  901. */
  902. corr_raw = (u64)ktime_to_ns(
  903. ktime_sub(ts->sys_monoraw, history->raw));
  904. ret = scale64_check_overflow(partial_history_cycles,
  905. total_history_cycles, &corr_raw);
  906. if (ret)
  907. return ret;
  908. /*
  909. * If there is a discontinuity in the history, scale monotonic raw
  910. * correction by:
  911. * mult(real)/mult(raw) yielding the realtime correction
  912. * Otherwise, calculate the realtime correction similar to monotonic
  913. * raw calculation
  914. */
  915. if (discontinuity) {
  916. corr_real = mul_u64_u32_div
  917. (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
  918. } else {
  919. corr_real = (u64)ktime_to_ns(
  920. ktime_sub(ts->sys_realtime, history->real));
  921. ret = scale64_check_overflow(partial_history_cycles,
  922. total_history_cycles, &corr_real);
  923. if (ret)
  924. return ret;
  925. }
  926. /* Fixup monotonic raw and real time time values */
  927. if (interp_forward) {
  928. ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
  929. ts->sys_realtime = ktime_add_ns(history->real, corr_real);
  930. } else {
  931. ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
  932. ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
  933. }
  934. return 0;
  935. }
  936. /*
  937. * timestamp_in_interval - true if ts is chronologically in [start, end]
  938. *
  939. * True if ts occurs chronologically at or after start, and before or at end.
  940. */
  941. static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
  942. {
  943. if (ts >= start && ts <= end)
  944. return true;
  945. if (start > end && (ts >= start || ts <= end))
  946. return true;
  947. return false;
  948. }
  949. static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
  950. {
  951. u64 rem, res;
  952. if (!numerator || !denominator)
  953. return false;
  954. res = div64_u64_rem(*val, denominator, &rem) * numerator;
  955. *val = res + div_u64(rem * numerator, denominator);
  956. return true;
  957. }
  958. static bool convert_base_to_cs(struct system_counterval_t *scv)
  959. {
  960. struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
  961. struct clocksource_base *base;
  962. u32 num, den;
  963. /* The timestamp was taken from the time keeper clock source */
  964. if (cs->id == scv->cs_id)
  965. return true;
  966. /*
  967. * Check whether cs_id matches the base clock. Prevent the compiler from
  968. * re-evaluating @base as the clocksource might change concurrently.
  969. */
  970. base = READ_ONCE(cs->base);
  971. if (!base || base->id != scv->cs_id)
  972. return false;
  973. num = scv->use_nsecs ? cs->freq_khz : base->numerator;
  974. den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
  975. if (!convert_clock(&scv->cycles, num, den))
  976. return false;
  977. scv->cycles += base->offset;
  978. return true;
  979. }
  980. static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
  981. {
  982. struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
  983. struct clocksource_base *base;
  984. /*
  985. * Check whether base_id matches the base clock. Prevent the compiler from
  986. * re-evaluating @base as the clocksource might change concurrently.
  987. */
  988. base = READ_ONCE(cs->base);
  989. if (!base || base->id != base_id)
  990. return false;
  991. *cycles -= base->offset;
  992. if (!convert_clock(cycles, base->denominator, base->numerator))
  993. return false;
  994. return true;
  995. }
  996. static bool convert_ns_to_cs(u64 *delta)
  997. {
  998. struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
  999. if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
  1000. return false;
  1001. *delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
  1002. return true;
  1003. }
  1004. /**
  1005. * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
  1006. * @treal: CLOCK_REALTIME timestamp to convert
  1007. * @base_id: base clocksource id
  1008. * @cycles: pointer to store the converted base clock timestamp
  1009. *
  1010. * Converts a supplied, future realtime clock value to the corresponding base clock value.
  1011. *
  1012. * Return: true if the conversion is successful, false otherwise.
  1013. */
  1014. bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
  1015. {
  1016. struct timekeeper *tk = &tk_core.timekeeper;
  1017. unsigned int seq;
  1018. u64 delta;
  1019. do {
  1020. seq = read_seqcount_begin(&tk_core.seq);
  1021. if ((u64)treal < tk->tkr_mono.base_real)
  1022. return false;
  1023. delta = (u64)treal - tk->tkr_mono.base_real;
  1024. if (!convert_ns_to_cs(&delta))
  1025. return false;
  1026. *cycles = tk->tkr_mono.cycle_last + delta;
  1027. if (!convert_cs_to_base(cycles, base_id))
  1028. return false;
  1029. } while (read_seqcount_retry(&tk_core.seq, seq));
  1030. return true;
  1031. }
  1032. EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
  1033. /**
  1034. * get_device_system_crosststamp - Synchronously capture system/device timestamp
  1035. * @get_time_fn: Callback to get simultaneous device time and
  1036. * system counter from the device driver
  1037. * @ctx: Context passed to get_time_fn()
  1038. * @history_begin: Historical reference point used to interpolate system
  1039. * time when counter provided by the driver is before the current interval
  1040. * @xtstamp: Receives simultaneously captured system and device time
  1041. *
  1042. * Reads a timestamp from a device and correlates it to system time
  1043. */
  1044. int get_device_system_crosststamp(int (*get_time_fn)
  1045. (ktime_t *device_time,
  1046. struct system_counterval_t *sys_counterval,
  1047. void *ctx),
  1048. void *ctx,
  1049. struct system_time_snapshot *history_begin,
  1050. struct system_device_crosststamp *xtstamp)
  1051. {
  1052. struct system_counterval_t system_counterval = {};
  1053. struct timekeeper *tk = &tk_core.timekeeper;
  1054. u64 cycles, now, interval_start;
  1055. unsigned int clock_was_set_seq = 0;
  1056. ktime_t base_real, base_raw;
  1057. u64 nsec_real, nsec_raw;
  1058. u8 cs_was_changed_seq;
  1059. unsigned int seq;
  1060. bool do_interp;
  1061. int ret;
  1062. do {
  1063. seq = read_seqcount_begin(&tk_core.seq);
  1064. /*
  1065. * Try to synchronously capture device time and a system
  1066. * counter value calling back into the device driver
  1067. */
  1068. ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
  1069. if (ret)
  1070. return ret;
  1071. /*
  1072. * Verify that the clocksource ID associated with the captured
  1073. * system counter value is the same as for the currently
  1074. * installed timekeeper clocksource
  1075. */
  1076. if (system_counterval.cs_id == CSID_GENERIC ||
  1077. !convert_base_to_cs(&system_counterval))
  1078. return -ENODEV;
  1079. cycles = system_counterval.cycles;
  1080. /*
  1081. * Check whether the system counter value provided by the
  1082. * device driver is on the current timekeeping interval.
  1083. */
  1084. now = tk_clock_read(&tk->tkr_mono);
  1085. interval_start = tk->tkr_mono.cycle_last;
  1086. if (!timestamp_in_interval(interval_start, now, cycles)) {
  1087. clock_was_set_seq = tk->clock_was_set_seq;
  1088. cs_was_changed_seq = tk->cs_was_changed_seq;
  1089. cycles = interval_start;
  1090. do_interp = true;
  1091. } else {
  1092. do_interp = false;
  1093. }
  1094. base_real = ktime_add(tk->tkr_mono.base,
  1095. tk_core.timekeeper.offs_real);
  1096. base_raw = tk->tkr_raw.base;
  1097. nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
  1098. nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
  1099. } while (read_seqcount_retry(&tk_core.seq, seq));
  1100. xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
  1101. xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
  1102. /*
  1103. * Interpolate if necessary, adjusting back from the start of the
  1104. * current interval
  1105. */
  1106. if (do_interp) {
  1107. u64 partial_history_cycles, total_history_cycles;
  1108. bool discontinuity;
  1109. /*
  1110. * Check that the counter value is not before the provided
  1111. * history reference and that the history doesn't cross a
  1112. * clocksource change
  1113. */
  1114. if (!history_begin ||
  1115. !timestamp_in_interval(history_begin->cycles,
  1116. cycles, system_counterval.cycles) ||
  1117. history_begin->cs_was_changed_seq != cs_was_changed_seq)
  1118. return -EINVAL;
  1119. partial_history_cycles = cycles - system_counterval.cycles;
  1120. total_history_cycles = cycles - history_begin->cycles;
  1121. discontinuity =
  1122. history_begin->clock_was_set_seq != clock_was_set_seq;
  1123. ret = adjust_historical_crosststamp(history_begin,
  1124. partial_history_cycles,
  1125. total_history_cycles,
  1126. discontinuity, xtstamp);
  1127. if (ret)
  1128. return ret;
  1129. }
  1130. return 0;
  1131. }
  1132. EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
  1133. /**
  1134. * timekeeping_clocksource_has_base - Check whether the current clocksource
  1135. * is based on given a base clock
  1136. * @id: base clocksource ID
  1137. *
  1138. * Note: The return value is a snapshot which can become invalid right
  1139. * after the function returns.
  1140. *
  1141. * Return: true if the timekeeper clocksource has a base clock with @id,
  1142. * false otherwise
  1143. */
  1144. bool timekeeping_clocksource_has_base(enum clocksource_ids id)
  1145. {
  1146. /*
  1147. * This is a snapshot, so no point in using the sequence
  1148. * count. Just prevent the compiler from re-evaluating @base as the
  1149. * clocksource might change concurrently.
  1150. */
  1151. struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
  1152. return base ? base->id == id : false;
  1153. }
  1154. EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
  1155. /**
  1156. * do_settimeofday64 - Sets the time of day.
  1157. * @ts: pointer to the timespec64 variable containing the new time
  1158. *
  1159. * Sets the time of day to the new time and update NTP and notify hrtimers
  1160. */
  1161. int do_settimeofday64(const struct timespec64 *ts)
  1162. {
  1163. struct timekeeper *tk = &tk_core.timekeeper;
  1164. struct timespec64 ts_delta, xt;
  1165. unsigned long flags;
  1166. int ret = 0;
  1167. if (!timespec64_valid_settod(ts))
  1168. return -EINVAL;
  1169. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1170. write_seqcount_begin(&tk_core.seq);
  1171. timekeeping_forward_now(tk);
  1172. xt = tk_xtime(tk);
  1173. ts_delta = timespec64_sub(*ts, xt);
  1174. if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
  1175. ret = -EINVAL;
  1176. goto out;
  1177. }
  1178. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
  1179. tk_set_xtime(tk, ts);
  1180. out:
  1181. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  1182. write_seqcount_end(&tk_core.seq);
  1183. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1184. /* Signal hrtimers about time change */
  1185. clock_was_set(CLOCK_SET_WALL);
  1186. if (!ret) {
  1187. audit_tk_injoffset(ts_delta);
  1188. add_device_randomness(ts, sizeof(*ts));
  1189. }
  1190. return ret;
  1191. }
  1192. EXPORT_SYMBOL(do_settimeofday64);
  1193. /**
  1194. * timekeeping_inject_offset - Adds or subtracts from the current time.
  1195. * @ts: Pointer to the timespec variable containing the offset
  1196. *
  1197. * Adds or subtracts an offset value from the current time.
  1198. */
  1199. static int timekeeping_inject_offset(const struct timespec64 *ts)
  1200. {
  1201. struct timekeeper *tk = &tk_core.timekeeper;
  1202. unsigned long flags;
  1203. struct timespec64 tmp;
  1204. int ret = 0;
  1205. if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
  1206. return -EINVAL;
  1207. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1208. write_seqcount_begin(&tk_core.seq);
  1209. timekeeping_forward_now(tk);
  1210. /* Make sure the proposed value is valid */
  1211. tmp = timespec64_add(tk_xtime(tk), *ts);
  1212. if (timespec64_compare(&tk->wall_to_monotonic, ts) > 0 ||
  1213. !timespec64_valid_settod(&tmp)) {
  1214. ret = -EINVAL;
  1215. goto error;
  1216. }
  1217. tk_xtime_add(tk, ts);
  1218. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *ts));
  1219. error: /* even if we error out, we forwarded the time, so call update */
  1220. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  1221. write_seqcount_end(&tk_core.seq);
  1222. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1223. /* Signal hrtimers about time change */
  1224. clock_was_set(CLOCK_SET_WALL);
  1225. return ret;
  1226. }
  1227. /*
  1228. * Indicates if there is an offset between the system clock and the hardware
  1229. * clock/persistent clock/rtc.
  1230. */
  1231. int persistent_clock_is_local;
  1232. /*
  1233. * Adjust the time obtained from the CMOS to be UTC time instead of
  1234. * local time.
  1235. *
  1236. * This is ugly, but preferable to the alternatives. Otherwise we
  1237. * would either need to write a program to do it in /etc/rc (and risk
  1238. * confusion if the program gets run more than once; it would also be
  1239. * hard to make the program warp the clock precisely n hours) or
  1240. * compile in the timezone information into the kernel. Bad, bad....
  1241. *
  1242. * - TYT, 1992-01-01
  1243. *
  1244. * The best thing to do is to keep the CMOS clock in universal time (UTC)
  1245. * as real UNIX machines always do it. This avoids all headaches about
  1246. * daylight saving times and warping kernel clocks.
  1247. */
  1248. void timekeeping_warp_clock(void)
  1249. {
  1250. if (sys_tz.tz_minuteswest != 0) {
  1251. struct timespec64 adjust;
  1252. persistent_clock_is_local = 1;
  1253. adjust.tv_sec = sys_tz.tz_minuteswest * 60;
  1254. adjust.tv_nsec = 0;
  1255. timekeeping_inject_offset(&adjust);
  1256. }
  1257. }
  1258. /*
  1259. * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
  1260. */
  1261. static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
  1262. {
  1263. tk->tai_offset = tai_offset;
  1264. tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
  1265. }
  1266. /*
  1267. * change_clocksource - Swaps clocksources if a new one is available
  1268. *
  1269. * Accumulates current time interval and initializes new clocksource
  1270. */
  1271. static int change_clocksource(void *data)
  1272. {
  1273. struct timekeeper *tk = &tk_core.timekeeper;
  1274. struct clocksource *new, *old = NULL;
  1275. unsigned long flags;
  1276. bool change = false;
  1277. new = (struct clocksource *) data;
  1278. /*
  1279. * If the cs is in module, get a module reference. Succeeds
  1280. * for built-in code (owner == NULL) as well.
  1281. */
  1282. if (try_module_get(new->owner)) {
  1283. if (!new->enable || new->enable(new) == 0)
  1284. change = true;
  1285. else
  1286. module_put(new->owner);
  1287. }
  1288. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1289. write_seqcount_begin(&tk_core.seq);
  1290. timekeeping_forward_now(tk);
  1291. if (change) {
  1292. old = tk->tkr_mono.clock;
  1293. tk_setup_internals(tk, new);
  1294. }
  1295. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  1296. write_seqcount_end(&tk_core.seq);
  1297. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1298. if (old) {
  1299. if (old->disable)
  1300. old->disable(old);
  1301. module_put(old->owner);
  1302. }
  1303. return 0;
  1304. }
  1305. /**
  1306. * timekeeping_notify - Install a new clock source
  1307. * @clock: pointer to the clock source
  1308. *
  1309. * This function is called from clocksource.c after a new, better clock
  1310. * source has been registered. The caller holds the clocksource_mutex.
  1311. */
  1312. int timekeeping_notify(struct clocksource *clock)
  1313. {
  1314. struct timekeeper *tk = &tk_core.timekeeper;
  1315. if (tk->tkr_mono.clock == clock)
  1316. return 0;
  1317. stop_machine(change_clocksource, clock, NULL);
  1318. tick_clock_notify();
  1319. return tk->tkr_mono.clock == clock ? 0 : -1;
  1320. }
  1321. /**
  1322. * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
  1323. * @ts: pointer to the timespec64 to be set
  1324. *
  1325. * Returns the raw monotonic time (completely un-modified by ntp)
  1326. */
  1327. void ktime_get_raw_ts64(struct timespec64 *ts)
  1328. {
  1329. struct timekeeper *tk = &tk_core.timekeeper;
  1330. unsigned int seq;
  1331. u64 nsecs;
  1332. do {
  1333. seq = read_seqcount_begin(&tk_core.seq);
  1334. ts->tv_sec = tk->raw_sec;
  1335. nsecs = timekeeping_get_ns(&tk->tkr_raw);
  1336. } while (read_seqcount_retry(&tk_core.seq, seq));
  1337. ts->tv_nsec = 0;
  1338. timespec64_add_ns(ts, nsecs);
  1339. }
  1340. EXPORT_SYMBOL(ktime_get_raw_ts64);
  1341. /**
  1342. * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
  1343. */
  1344. int timekeeping_valid_for_hres(void)
  1345. {
  1346. struct timekeeper *tk = &tk_core.timekeeper;
  1347. unsigned int seq;
  1348. int ret;
  1349. do {
  1350. seq = read_seqcount_begin(&tk_core.seq);
  1351. ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  1352. } while (read_seqcount_retry(&tk_core.seq, seq));
  1353. return ret;
  1354. }
  1355. /**
  1356. * timekeeping_max_deferment - Returns max time the clocksource can be deferred
  1357. */
  1358. u64 timekeeping_max_deferment(void)
  1359. {
  1360. struct timekeeper *tk = &tk_core.timekeeper;
  1361. unsigned int seq;
  1362. u64 ret;
  1363. do {
  1364. seq = read_seqcount_begin(&tk_core.seq);
  1365. ret = tk->tkr_mono.clock->max_idle_ns;
  1366. } while (read_seqcount_retry(&tk_core.seq, seq));
  1367. return ret;
  1368. }
  1369. /**
  1370. * read_persistent_clock64 - Return time from the persistent clock.
  1371. * @ts: Pointer to the storage for the readout value
  1372. *
  1373. * Weak dummy function for arches that do not yet support it.
  1374. * Reads the time from the battery backed persistent clock.
  1375. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  1376. *
  1377. * XXX - Do be sure to remove it once all arches implement it.
  1378. */
  1379. void __weak read_persistent_clock64(struct timespec64 *ts)
  1380. {
  1381. ts->tv_sec = 0;
  1382. ts->tv_nsec = 0;
  1383. }
  1384. /**
  1385. * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
  1386. * from the boot.
  1387. * @wall_time: current time as returned by persistent clock
  1388. * @boot_offset: offset that is defined as wall_time - boot_time
  1389. *
  1390. * Weak dummy function for arches that do not yet support it.
  1391. *
  1392. * The default function calculates offset based on the current value of
  1393. * local_clock(). This way architectures that support sched_clock() but don't
  1394. * support dedicated boot time clock will provide the best estimate of the
  1395. * boot time.
  1396. */
  1397. void __weak __init
  1398. read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
  1399. struct timespec64 *boot_offset)
  1400. {
  1401. read_persistent_clock64(wall_time);
  1402. *boot_offset = ns_to_timespec64(local_clock());
  1403. }
  1404. /*
  1405. * Flag reflecting whether timekeeping_resume() has injected sleeptime.
  1406. *
  1407. * The flag starts of false and is only set when a suspend reaches
  1408. * timekeeping_suspend(), timekeeping_resume() sets it to false when the
  1409. * timekeeper clocksource is not stopping across suspend and has been
  1410. * used to update sleep time. If the timekeeper clocksource has stopped
  1411. * then the flag stays true and is used by the RTC resume code to decide
  1412. * whether sleeptime must be injected and if so the flag gets false then.
  1413. *
  1414. * If a suspend fails before reaching timekeeping_resume() then the flag
  1415. * stays false and prevents erroneous sleeptime injection.
  1416. */
  1417. static bool suspend_timing_needed;
  1418. /* Flag for if there is a persistent clock on this platform */
  1419. static bool persistent_clock_exists;
  1420. /*
  1421. * timekeeping_init - Initializes the clocksource and common timekeeping values
  1422. */
  1423. void __init timekeeping_init(void)
  1424. {
  1425. struct timespec64 wall_time, boot_offset, wall_to_mono;
  1426. struct timekeeper *tk = &tk_core.timekeeper;
  1427. struct clocksource *clock;
  1428. unsigned long flags;
  1429. read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
  1430. if (timespec64_valid_settod(&wall_time) &&
  1431. timespec64_to_ns(&wall_time) > 0) {
  1432. persistent_clock_exists = true;
  1433. } else if (timespec64_to_ns(&wall_time) != 0) {
  1434. pr_warn("Persistent clock returned invalid value");
  1435. wall_time = (struct timespec64){0};
  1436. }
  1437. if (timespec64_compare(&wall_time, &boot_offset) < 0)
  1438. boot_offset = (struct timespec64){0};
  1439. /*
  1440. * We want set wall_to_mono, so the following is true:
  1441. * wall time + wall_to_mono = boot time
  1442. */
  1443. wall_to_mono = timespec64_sub(boot_offset, wall_time);
  1444. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1445. write_seqcount_begin(&tk_core.seq);
  1446. ntp_init();
  1447. clock = clocksource_default_clock();
  1448. if (clock->enable)
  1449. clock->enable(clock);
  1450. tk_setup_internals(tk, clock);
  1451. tk_set_xtime(tk, &wall_time);
  1452. tk->raw_sec = 0;
  1453. tk_set_wall_to_mono(tk, wall_to_mono);
  1454. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  1455. write_seqcount_end(&tk_core.seq);
  1456. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1457. }
  1458. /* time in seconds when suspend began for persistent clock */
  1459. static struct timespec64 timekeeping_suspend_time;
  1460. /**
  1461. * __timekeeping_inject_sleeptime - Internal function to add sleep interval
  1462. * @tk: Pointer to the timekeeper to be updated
  1463. * @delta: Pointer to the delta value in timespec64 format
  1464. *
  1465. * Takes a timespec offset measuring a suspend interval and properly
  1466. * adds the sleep offset to the timekeeping variables.
  1467. */
  1468. static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
  1469. const struct timespec64 *delta)
  1470. {
  1471. if (!timespec64_valid_strict(delta)) {
  1472. printk_deferred(KERN_WARNING
  1473. "__timekeeping_inject_sleeptime: Invalid "
  1474. "sleep delta value!\n");
  1475. return;
  1476. }
  1477. tk_xtime_add(tk, delta);
  1478. tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
  1479. tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
  1480. tk_debug_account_sleep_time(delta);
  1481. }
  1482. #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
  1483. /*
  1484. * We have three kinds of time sources to use for sleep time
  1485. * injection, the preference order is:
  1486. * 1) non-stop clocksource
  1487. * 2) persistent clock (ie: RTC accessible when irqs are off)
  1488. * 3) RTC
  1489. *
  1490. * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
  1491. * If system has neither 1) nor 2), 3) will be used finally.
  1492. *
  1493. *
  1494. * If timekeeping has injected sleeptime via either 1) or 2),
  1495. * 3) becomes needless, so in this case we don't need to call
  1496. * rtc_resume(), and this is what timekeeping_rtc_skipresume()
  1497. * means.
  1498. */
  1499. bool timekeeping_rtc_skipresume(void)
  1500. {
  1501. return !suspend_timing_needed;
  1502. }
  1503. /*
  1504. * 1) can be determined whether to use or not only when doing
  1505. * timekeeping_resume() which is invoked after rtc_suspend(),
  1506. * so we can't skip rtc_suspend() surely if system has 1).
  1507. *
  1508. * But if system has 2), 2) will definitely be used, so in this
  1509. * case we don't need to call rtc_suspend(), and this is what
  1510. * timekeeping_rtc_skipsuspend() means.
  1511. */
  1512. bool timekeeping_rtc_skipsuspend(void)
  1513. {
  1514. return persistent_clock_exists;
  1515. }
  1516. /**
  1517. * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
  1518. * @delta: pointer to a timespec64 delta value
  1519. *
  1520. * This hook is for architectures that cannot support read_persistent_clock64
  1521. * because their RTC/persistent clock is only accessible when irqs are enabled.
  1522. * and also don't have an effective nonstop clocksource.
  1523. *
  1524. * This function should only be called by rtc_resume(), and allows
  1525. * a suspend offset to be injected into the timekeeping values.
  1526. */
  1527. void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
  1528. {
  1529. struct timekeeper *tk = &tk_core.timekeeper;
  1530. unsigned long flags;
  1531. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1532. write_seqcount_begin(&tk_core.seq);
  1533. suspend_timing_needed = false;
  1534. timekeeping_forward_now(tk);
  1535. __timekeeping_inject_sleeptime(tk, delta);
  1536. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  1537. write_seqcount_end(&tk_core.seq);
  1538. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1539. /* Signal hrtimers about time change */
  1540. clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
  1541. }
  1542. #endif
  1543. /**
  1544. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  1545. */
  1546. void timekeeping_resume(void)
  1547. {
  1548. struct timekeeper *tk = &tk_core.timekeeper;
  1549. struct clocksource *clock = tk->tkr_mono.clock;
  1550. unsigned long flags;
  1551. struct timespec64 ts_new, ts_delta;
  1552. u64 cycle_now, nsec;
  1553. bool inject_sleeptime = false;
  1554. read_persistent_clock64(&ts_new);
  1555. clockevents_resume();
  1556. clocksource_resume();
  1557. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1558. write_seqcount_begin(&tk_core.seq);
  1559. /*
  1560. * After system resumes, we need to calculate the suspended time and
  1561. * compensate it for the OS time. There are 3 sources that could be
  1562. * used: Nonstop clocksource during suspend, persistent clock and rtc
  1563. * device.
  1564. *
  1565. * One specific platform may have 1 or 2 or all of them, and the
  1566. * preference will be:
  1567. * suspend-nonstop clocksource -> persistent clock -> rtc
  1568. * The less preferred source will only be tried if there is no better
  1569. * usable source. The rtc part is handled separately in rtc core code.
  1570. */
  1571. cycle_now = tk_clock_read(&tk->tkr_mono);
  1572. nsec = clocksource_stop_suspend_timing(clock, cycle_now);
  1573. if (nsec > 0) {
  1574. ts_delta = ns_to_timespec64(nsec);
  1575. inject_sleeptime = true;
  1576. } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
  1577. ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
  1578. inject_sleeptime = true;
  1579. }
  1580. if (inject_sleeptime) {
  1581. suspend_timing_needed = false;
  1582. __timekeeping_inject_sleeptime(tk, &ts_delta);
  1583. }
  1584. /* Re-base the last cycle value */
  1585. tk->tkr_mono.cycle_last = cycle_now;
  1586. tk->tkr_raw.cycle_last = cycle_now;
  1587. tk->ntp_error = 0;
  1588. timekeeping_suspended = 0;
  1589. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  1590. write_seqcount_end(&tk_core.seq);
  1591. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1592. touch_softlockup_watchdog();
  1593. /* Resume the clockevent device(s) and hrtimers */
  1594. tick_resume();
  1595. /* Notify timerfd as resume is equivalent to clock_was_set() */
  1596. timerfd_resume();
  1597. }
  1598. int timekeeping_suspend(void)
  1599. {
  1600. struct timekeeper *tk = &tk_core.timekeeper;
  1601. unsigned long flags;
  1602. struct timespec64 delta, delta_delta;
  1603. static struct timespec64 old_delta;
  1604. struct clocksource *curr_clock;
  1605. u64 cycle_now;
  1606. read_persistent_clock64(&timekeeping_suspend_time);
  1607. /*
  1608. * On some systems the persistent_clock can not be detected at
  1609. * timekeeping_init by its return value, so if we see a valid
  1610. * value returned, update the persistent_clock_exists flag.
  1611. */
  1612. if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
  1613. persistent_clock_exists = true;
  1614. suspend_timing_needed = true;
  1615. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1616. write_seqcount_begin(&tk_core.seq);
  1617. timekeeping_forward_now(tk);
  1618. timekeeping_suspended = 1;
  1619. /*
  1620. * Since we've called forward_now, cycle_last stores the value
  1621. * just read from the current clocksource. Save this to potentially
  1622. * use in suspend timing.
  1623. */
  1624. curr_clock = tk->tkr_mono.clock;
  1625. cycle_now = tk->tkr_mono.cycle_last;
  1626. clocksource_start_suspend_timing(curr_clock, cycle_now);
  1627. if (persistent_clock_exists) {
  1628. /*
  1629. * To avoid drift caused by repeated suspend/resumes,
  1630. * which each can add ~1 second drift error,
  1631. * try to compensate so the difference in system time
  1632. * and persistent_clock time stays close to constant.
  1633. */
  1634. delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
  1635. delta_delta = timespec64_sub(delta, old_delta);
  1636. if (abs(delta_delta.tv_sec) >= 2) {
  1637. /*
  1638. * if delta_delta is too large, assume time correction
  1639. * has occurred and set old_delta to the current delta.
  1640. */
  1641. old_delta = delta;
  1642. } else {
  1643. /* Otherwise try to adjust old_system to compensate */
  1644. timekeeping_suspend_time =
  1645. timespec64_add(timekeeping_suspend_time, delta_delta);
  1646. }
  1647. }
  1648. timekeeping_update(tk, TK_MIRROR);
  1649. halt_fast_timekeeper(tk);
  1650. write_seqcount_end(&tk_core.seq);
  1651. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1652. tick_suspend();
  1653. clocksource_suspend();
  1654. clockevents_suspend();
  1655. return 0;
  1656. }
  1657. /* sysfs resume/suspend bits for timekeeping */
  1658. static struct syscore_ops timekeeping_syscore_ops = {
  1659. .resume = timekeeping_resume,
  1660. .suspend = timekeeping_suspend,
  1661. };
  1662. static int __init timekeeping_init_ops(void)
  1663. {
  1664. register_syscore_ops(&timekeeping_syscore_ops);
  1665. return 0;
  1666. }
  1667. device_initcall(timekeeping_init_ops);
  1668. /*
  1669. * Apply a multiplier adjustment to the timekeeper
  1670. */
  1671. static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
  1672. s64 offset,
  1673. s32 mult_adj)
  1674. {
  1675. s64 interval = tk->cycle_interval;
  1676. if (mult_adj == 0) {
  1677. return;
  1678. } else if (mult_adj == -1) {
  1679. interval = -interval;
  1680. offset = -offset;
  1681. } else if (mult_adj != 1) {
  1682. interval *= mult_adj;
  1683. offset *= mult_adj;
  1684. }
  1685. /*
  1686. * So the following can be confusing.
  1687. *
  1688. * To keep things simple, lets assume mult_adj == 1 for now.
  1689. *
  1690. * When mult_adj != 1, remember that the interval and offset values
  1691. * have been appropriately scaled so the math is the same.
  1692. *
  1693. * The basic idea here is that we're increasing the multiplier
  1694. * by one, this causes the xtime_interval to be incremented by
  1695. * one cycle_interval. This is because:
  1696. * xtime_interval = cycle_interval * mult
  1697. * So if mult is being incremented by one:
  1698. * xtime_interval = cycle_interval * (mult + 1)
  1699. * Its the same as:
  1700. * xtime_interval = (cycle_interval * mult) + cycle_interval
  1701. * Which can be shortened to:
  1702. * xtime_interval += cycle_interval
  1703. *
  1704. * So offset stores the non-accumulated cycles. Thus the current
  1705. * time (in shifted nanoseconds) is:
  1706. * now = (offset * adj) + xtime_nsec
  1707. * Now, even though we're adjusting the clock frequency, we have
  1708. * to keep time consistent. In other words, we can't jump back
  1709. * in time, and we also want to avoid jumping forward in time.
  1710. *
  1711. * So given the same offset value, we need the time to be the same
  1712. * both before and after the freq adjustment.
  1713. * now = (offset * adj_1) + xtime_nsec_1
  1714. * now = (offset * adj_2) + xtime_nsec_2
  1715. * So:
  1716. * (offset * adj_1) + xtime_nsec_1 =
  1717. * (offset * adj_2) + xtime_nsec_2
  1718. * And we know:
  1719. * adj_2 = adj_1 + 1
  1720. * So:
  1721. * (offset * adj_1) + xtime_nsec_1 =
  1722. * (offset * (adj_1+1)) + xtime_nsec_2
  1723. * (offset * adj_1) + xtime_nsec_1 =
  1724. * (offset * adj_1) + offset + xtime_nsec_2
  1725. * Canceling the sides:
  1726. * xtime_nsec_1 = offset + xtime_nsec_2
  1727. * Which gives us:
  1728. * xtime_nsec_2 = xtime_nsec_1 - offset
  1729. * Which simplifies to:
  1730. * xtime_nsec -= offset
  1731. */
  1732. if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
  1733. /* NTP adjustment caused clocksource mult overflow */
  1734. WARN_ON_ONCE(1);
  1735. return;
  1736. }
  1737. tk->tkr_mono.mult += mult_adj;
  1738. tk->xtime_interval += interval;
  1739. tk->tkr_mono.xtime_nsec -= offset;
  1740. }
  1741. /*
  1742. * Adjust the timekeeper's multiplier to the correct frequency
  1743. * and also to reduce the accumulated error value.
  1744. */
  1745. static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
  1746. {
  1747. u32 mult;
  1748. /*
  1749. * Determine the multiplier from the current NTP tick length.
  1750. * Avoid expensive division when the tick length doesn't change.
  1751. */
  1752. if (likely(tk->ntp_tick == ntp_tick_length())) {
  1753. mult = tk->tkr_mono.mult - tk->ntp_err_mult;
  1754. } else {
  1755. tk->ntp_tick = ntp_tick_length();
  1756. mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
  1757. tk->xtime_remainder, tk->cycle_interval);
  1758. }
  1759. /*
  1760. * If the clock is behind the NTP time, increase the multiplier by 1
  1761. * to catch up with it. If it's ahead and there was a remainder in the
  1762. * tick division, the clock will slow down. Otherwise it will stay
  1763. * ahead until the tick length changes to a non-divisible value.
  1764. */
  1765. tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
  1766. mult += tk->ntp_err_mult;
  1767. timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
  1768. if (unlikely(tk->tkr_mono.clock->maxadj &&
  1769. (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
  1770. > tk->tkr_mono.clock->maxadj))) {
  1771. printk_once(KERN_WARNING
  1772. "Adjusting %s more than 11%% (%ld vs %ld)\n",
  1773. tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
  1774. (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
  1775. }
  1776. /*
  1777. * It may be possible that when we entered this function, xtime_nsec
  1778. * was very small. Further, if we're slightly speeding the clocksource
  1779. * in the code above, its possible the required corrective factor to
  1780. * xtime_nsec could cause it to underflow.
  1781. *
  1782. * Now, since we have already accumulated the second and the NTP
  1783. * subsystem has been notified via second_overflow(), we need to skip
  1784. * the next update.
  1785. */
  1786. if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
  1787. tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
  1788. tk->tkr_mono.shift;
  1789. tk->xtime_sec--;
  1790. tk->skip_second_overflow = 1;
  1791. }
  1792. }
  1793. /*
  1794. * accumulate_nsecs_to_secs - Accumulates nsecs into secs
  1795. *
  1796. * Helper function that accumulates the nsecs greater than a second
  1797. * from the xtime_nsec field to the xtime_secs field.
  1798. * It also calls into the NTP code to handle leapsecond processing.
  1799. */
  1800. static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
  1801. {
  1802. u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
  1803. unsigned int clock_set = 0;
  1804. while (tk->tkr_mono.xtime_nsec >= nsecps) {
  1805. int leap;
  1806. tk->tkr_mono.xtime_nsec -= nsecps;
  1807. tk->xtime_sec++;
  1808. /*
  1809. * Skip NTP update if this second was accumulated before,
  1810. * i.e. xtime_nsec underflowed in timekeeping_adjust()
  1811. */
  1812. if (unlikely(tk->skip_second_overflow)) {
  1813. tk->skip_second_overflow = 0;
  1814. continue;
  1815. }
  1816. /* Figure out if its a leap sec and apply if needed */
  1817. leap = second_overflow(tk->xtime_sec);
  1818. if (unlikely(leap)) {
  1819. struct timespec64 ts;
  1820. tk->xtime_sec += leap;
  1821. ts.tv_sec = leap;
  1822. ts.tv_nsec = 0;
  1823. tk_set_wall_to_mono(tk,
  1824. timespec64_sub(tk->wall_to_monotonic, ts));
  1825. __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
  1826. clock_set = TK_CLOCK_WAS_SET;
  1827. }
  1828. }
  1829. return clock_set;
  1830. }
  1831. /*
  1832. * logarithmic_accumulation - shifted accumulation of cycles
  1833. *
  1834. * This functions accumulates a shifted interval of cycles into
  1835. * a shifted interval nanoseconds. Allows for O(log) accumulation
  1836. * loop.
  1837. *
  1838. * Returns the unconsumed cycles.
  1839. */
  1840. static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
  1841. u32 shift, unsigned int *clock_set)
  1842. {
  1843. u64 interval = tk->cycle_interval << shift;
  1844. u64 snsec_per_sec;
  1845. /* If the offset is smaller than a shifted interval, do nothing */
  1846. if (offset < interval)
  1847. return offset;
  1848. /* Accumulate one shifted interval */
  1849. offset -= interval;
  1850. tk->tkr_mono.cycle_last += interval;
  1851. tk->tkr_raw.cycle_last += interval;
  1852. tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
  1853. *clock_set |= accumulate_nsecs_to_secs(tk);
  1854. /* Accumulate raw time */
  1855. tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
  1856. snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
  1857. while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
  1858. tk->tkr_raw.xtime_nsec -= snsec_per_sec;
  1859. tk->raw_sec++;
  1860. }
  1861. /* Accumulate error between NTP and clock interval */
  1862. tk->ntp_error += tk->ntp_tick << shift;
  1863. tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
  1864. (tk->ntp_error_shift + shift);
  1865. return offset;
  1866. }
  1867. /*
  1868. * timekeeping_advance - Updates the timekeeper to the current time and
  1869. * current NTP tick length
  1870. */
  1871. static bool timekeeping_advance(enum timekeeping_adv_mode mode)
  1872. {
  1873. struct timekeeper *real_tk = &tk_core.timekeeper;
  1874. struct timekeeper *tk = &shadow_timekeeper;
  1875. u64 offset;
  1876. int shift = 0, maxshift;
  1877. unsigned int clock_set = 0;
  1878. unsigned long flags;
  1879. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1880. /* Make sure we're fully resumed: */
  1881. if (unlikely(timekeeping_suspended))
  1882. goto out;
  1883. offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
  1884. tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
  1885. tk->tkr_mono.clock->max_raw_delta);
  1886. /* Check if there's really nothing to do */
  1887. if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
  1888. goto out;
  1889. /*
  1890. * With NO_HZ we may have to accumulate many cycle_intervals
  1891. * (think "ticks") worth of time at once. To do this efficiently,
  1892. * we calculate the largest doubling multiple of cycle_intervals
  1893. * that is smaller than the offset. We then accumulate that
  1894. * chunk in one go, and then try to consume the next smaller
  1895. * doubled multiple.
  1896. */
  1897. shift = ilog2(offset) - ilog2(tk->cycle_interval);
  1898. shift = max(0, shift);
  1899. /* Bound shift to one less than what overflows tick_length */
  1900. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  1901. shift = min(shift, maxshift);
  1902. while (offset >= tk->cycle_interval) {
  1903. offset = logarithmic_accumulation(tk, offset, shift,
  1904. &clock_set);
  1905. if (offset < tk->cycle_interval<<shift)
  1906. shift--;
  1907. }
  1908. /* Adjust the multiplier to correct NTP error */
  1909. timekeeping_adjust(tk, offset);
  1910. /*
  1911. * Finally, make sure that after the rounding
  1912. * xtime_nsec isn't larger than NSEC_PER_SEC
  1913. */
  1914. clock_set |= accumulate_nsecs_to_secs(tk);
  1915. write_seqcount_begin(&tk_core.seq);
  1916. /*
  1917. * Update the real timekeeper.
  1918. *
  1919. * We could avoid this memcpy by switching pointers, but that
  1920. * requires changes to all other timekeeper usage sites as
  1921. * well, i.e. move the timekeeper pointer getter into the
  1922. * spinlocked/seqcount protected sections. And we trade this
  1923. * memcpy under the tk_core.seq against one before we start
  1924. * updating.
  1925. */
  1926. timekeeping_update(tk, clock_set);
  1927. memcpy(real_tk, tk, sizeof(*tk));
  1928. /* The memcpy must come last. Do not put anything here! */
  1929. write_seqcount_end(&tk_core.seq);
  1930. out:
  1931. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1932. return !!clock_set;
  1933. }
  1934. /**
  1935. * update_wall_time - Uses the current clocksource to increment the wall time
  1936. *
  1937. */
  1938. void update_wall_time(void)
  1939. {
  1940. if (timekeeping_advance(TK_ADV_TICK))
  1941. clock_was_set_delayed();
  1942. }
  1943. /**
  1944. * getboottime64 - Return the real time of system boot.
  1945. * @ts: pointer to the timespec64 to be set
  1946. *
  1947. * Returns the wall-time of boot in a timespec64.
  1948. *
  1949. * This is based on the wall_to_monotonic offset and the total suspend
  1950. * time. Calls to settimeofday will affect the value returned (which
  1951. * basically means that however wrong your real time clock is at boot time,
  1952. * you get the right time here).
  1953. */
  1954. void getboottime64(struct timespec64 *ts)
  1955. {
  1956. struct timekeeper *tk = &tk_core.timekeeper;
  1957. ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
  1958. *ts = ktime_to_timespec64(t);
  1959. }
  1960. EXPORT_SYMBOL_GPL(getboottime64);
  1961. void ktime_get_coarse_real_ts64(struct timespec64 *ts)
  1962. {
  1963. struct timekeeper *tk = &tk_core.timekeeper;
  1964. unsigned int seq;
  1965. do {
  1966. seq = read_seqcount_begin(&tk_core.seq);
  1967. *ts = tk_xtime(tk);
  1968. } while (read_seqcount_retry(&tk_core.seq, seq));
  1969. }
  1970. EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
  1971. void ktime_get_coarse_ts64(struct timespec64 *ts)
  1972. {
  1973. struct timekeeper *tk = &tk_core.timekeeper;
  1974. struct timespec64 now, mono;
  1975. unsigned int seq;
  1976. do {
  1977. seq = read_seqcount_begin(&tk_core.seq);
  1978. now = tk_xtime(tk);
  1979. mono = tk->wall_to_monotonic;
  1980. } while (read_seqcount_retry(&tk_core.seq, seq));
  1981. set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
  1982. now.tv_nsec + mono.tv_nsec);
  1983. }
  1984. EXPORT_SYMBOL(ktime_get_coarse_ts64);
  1985. /*
  1986. * Must hold jiffies_lock
  1987. */
  1988. void do_timer(unsigned long ticks)
  1989. {
  1990. jiffies_64 += ticks;
  1991. calc_global_load();
  1992. }
  1993. /**
  1994. * ktime_get_update_offsets_now - hrtimer helper
  1995. * @cwsseq: pointer to check and store the clock was set sequence number
  1996. * @offs_real: pointer to storage for monotonic -> realtime offset
  1997. * @offs_boot: pointer to storage for monotonic -> boottime offset
  1998. * @offs_tai: pointer to storage for monotonic -> clock tai offset
  1999. *
  2000. * Returns current monotonic time and updates the offsets if the
  2001. * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
  2002. * different.
  2003. *
  2004. * Called from hrtimer_interrupt() or retrigger_next_event()
  2005. */
  2006. ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
  2007. ktime_t *offs_boot, ktime_t *offs_tai)
  2008. {
  2009. struct timekeeper *tk = &tk_core.timekeeper;
  2010. unsigned int seq;
  2011. ktime_t base;
  2012. u64 nsecs;
  2013. do {
  2014. seq = read_seqcount_begin(&tk_core.seq);
  2015. base = tk->tkr_mono.base;
  2016. nsecs = timekeeping_get_ns(&tk->tkr_mono);
  2017. base = ktime_add_ns(base, nsecs);
  2018. if (*cwsseq != tk->clock_was_set_seq) {
  2019. *cwsseq = tk->clock_was_set_seq;
  2020. *offs_real = tk->offs_real;
  2021. *offs_boot = tk->offs_boot;
  2022. *offs_tai = tk->offs_tai;
  2023. }
  2024. /* Handle leapsecond insertion adjustments */
  2025. if (unlikely(base >= tk->next_leap_ktime))
  2026. *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
  2027. } while (read_seqcount_retry(&tk_core.seq, seq));
  2028. return base;
  2029. }
  2030. /*
  2031. * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
  2032. */
  2033. static int timekeeping_validate_timex(const struct __kernel_timex *txc)
  2034. {
  2035. if (txc->modes & ADJ_ADJTIME) {
  2036. /* singleshot must not be used with any other mode bits */
  2037. if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
  2038. return -EINVAL;
  2039. if (!(txc->modes & ADJ_OFFSET_READONLY) &&
  2040. !capable(CAP_SYS_TIME))
  2041. return -EPERM;
  2042. } else {
  2043. /* In order to modify anything, you gotta be super-user! */
  2044. if (txc->modes && !capable(CAP_SYS_TIME))
  2045. return -EPERM;
  2046. /*
  2047. * if the quartz is off by more than 10% then
  2048. * something is VERY wrong!
  2049. */
  2050. if (txc->modes & ADJ_TICK &&
  2051. (txc->tick < 900000/USER_HZ ||
  2052. txc->tick > 1100000/USER_HZ))
  2053. return -EINVAL;
  2054. }
  2055. if (txc->modes & ADJ_SETOFFSET) {
  2056. /* In order to inject time, you gotta be super-user! */
  2057. if (!capable(CAP_SYS_TIME))
  2058. return -EPERM;
  2059. /*
  2060. * Validate if a timespec/timeval used to inject a time
  2061. * offset is valid. Offsets can be positive or negative, so
  2062. * we don't check tv_sec. The value of the timeval/timespec
  2063. * is the sum of its fields,but *NOTE*:
  2064. * The field tv_usec/tv_nsec must always be non-negative and
  2065. * we can't have more nanoseconds/microseconds than a second.
  2066. */
  2067. if (txc->time.tv_usec < 0)
  2068. return -EINVAL;
  2069. if (txc->modes & ADJ_NANO) {
  2070. if (txc->time.tv_usec >= NSEC_PER_SEC)
  2071. return -EINVAL;
  2072. } else {
  2073. if (txc->time.tv_usec >= USEC_PER_SEC)
  2074. return -EINVAL;
  2075. }
  2076. }
  2077. /*
  2078. * Check for potential multiplication overflows that can
  2079. * only happen on 64-bit systems:
  2080. */
  2081. if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
  2082. if (LLONG_MIN / PPM_SCALE > txc->freq)
  2083. return -EINVAL;
  2084. if (LLONG_MAX / PPM_SCALE < txc->freq)
  2085. return -EINVAL;
  2086. }
  2087. return 0;
  2088. }
  2089. /**
  2090. * random_get_entropy_fallback - Returns the raw clock source value,
  2091. * used by random.c for platforms with no valid random_get_entropy().
  2092. */
  2093. unsigned long random_get_entropy_fallback(void)
  2094. {
  2095. struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
  2096. struct clocksource *clock = READ_ONCE(tkr->clock);
  2097. if (unlikely(timekeeping_suspended || !clock))
  2098. return 0;
  2099. return clock->read(clock);
  2100. }
  2101. EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
  2102. /**
  2103. * do_adjtimex() - Accessor function to NTP __do_adjtimex function
  2104. * @txc: Pointer to kernel_timex structure containing NTP parameters
  2105. */
  2106. int do_adjtimex(struct __kernel_timex *txc)
  2107. {
  2108. struct timekeeper *tk = &tk_core.timekeeper;
  2109. struct audit_ntp_data ad;
  2110. bool offset_set = false;
  2111. bool clock_set = false;
  2112. struct timespec64 ts;
  2113. unsigned long flags;
  2114. s32 orig_tai, tai;
  2115. int ret;
  2116. /* Validate the data before disabling interrupts */
  2117. ret = timekeeping_validate_timex(txc);
  2118. if (ret)
  2119. return ret;
  2120. add_device_randomness(txc, sizeof(*txc));
  2121. if (txc->modes & ADJ_SETOFFSET) {
  2122. struct timespec64 delta;
  2123. delta.tv_sec = txc->time.tv_sec;
  2124. delta.tv_nsec = txc->time.tv_usec;
  2125. if (!(txc->modes & ADJ_NANO))
  2126. delta.tv_nsec *= 1000;
  2127. ret = timekeeping_inject_offset(&delta);
  2128. if (ret)
  2129. return ret;
  2130. offset_set = delta.tv_sec != 0;
  2131. audit_tk_injoffset(delta);
  2132. }
  2133. audit_ntp_init(&ad);
  2134. ktime_get_real_ts64(&ts);
  2135. add_device_randomness(&ts, sizeof(ts));
  2136. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  2137. write_seqcount_begin(&tk_core.seq);
  2138. orig_tai = tai = tk->tai_offset;
  2139. ret = __do_adjtimex(txc, &ts, &tai, &ad);
  2140. if (tai != orig_tai) {
  2141. __timekeeping_set_tai_offset(tk, tai);
  2142. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  2143. clock_set = true;
  2144. }
  2145. tk_update_leap_state(tk);
  2146. write_seqcount_end(&tk_core.seq);
  2147. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  2148. audit_ntp_log(&ad);
  2149. /* Update the multiplier immediately if frequency was set directly */
  2150. if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
  2151. clock_set |= timekeeping_advance(TK_ADV_FREQ);
  2152. if (clock_set)
  2153. clock_was_set(CLOCK_SET_WALL);
  2154. ntp_notify_cmos_timer(offset_set);
  2155. return ret;
  2156. }
  2157. #ifdef CONFIG_NTP_PPS
  2158. /**
  2159. * hardpps() - Accessor function to NTP __hardpps function
  2160. * @phase_ts: Pointer to timespec64 structure representing phase timestamp
  2161. * @raw_ts: Pointer to timespec64 structure representing raw timestamp
  2162. */
  2163. void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
  2164. {
  2165. unsigned long flags;
  2166. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  2167. write_seqcount_begin(&tk_core.seq);
  2168. __hardpps(phase_ts, raw_ts);
  2169. write_seqcount_end(&tk_core.seq);
  2170. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  2171. }
  2172. EXPORT_SYMBOL(hardpps);
  2173. #endif /* CONFIG_NTP_PPS */