timekeeping.c 71 KB

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