timekeeping.c 67 KB

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