timekeeping.c 56 KB

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