timekeeping.c 64 KB

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