timekeeping.c 65 KB

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