timekeeping.c 65 KB

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