timekeeping.c 67 KB

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