timekeeping.c 70 KB

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