timekeeping.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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 "tick-internal.h"
  25. #include "ntp_internal.h"
  26. #include "timekeeping_internal.h"
  27. #define TK_CLEAR_NTP (1 << 0)
  28. #define TK_MIRROR (1 << 1)
  29. #define TK_CLOCK_WAS_SET (1 << 2)
  30. static struct timekeeper timekeeper;
  31. static DEFINE_RAW_SPINLOCK(timekeeper_lock);
  32. static seqcount_t timekeeper_seq;
  33. static struct timekeeper shadow_timekeeper;
  34. /* flag for if timekeeping is suspended */
  35. int __read_mostly timekeeping_suspended;
  36. /* Flag for if there is a persistent clock on this platform */
  37. bool __read_mostly persistent_clock_exist = false;
  38. static inline void tk_normalize_xtime(struct timekeeper *tk)
  39. {
  40. while (tk->xtime_nsec >= ((u64)NSEC_PER_SEC << tk->shift)) {
  41. tk->xtime_nsec -= (u64)NSEC_PER_SEC << tk->shift;
  42. tk->xtime_sec++;
  43. }
  44. }
  45. static void tk_set_xtime(struct timekeeper *tk, const struct timespec *ts)
  46. {
  47. tk->xtime_sec = ts->tv_sec;
  48. tk->xtime_nsec = (u64)ts->tv_nsec << tk->shift;
  49. }
  50. static void tk_xtime_add(struct timekeeper *tk, const struct timespec *ts)
  51. {
  52. tk->xtime_sec += ts->tv_sec;
  53. tk->xtime_nsec += (u64)ts->tv_nsec << tk->shift;
  54. tk_normalize_xtime(tk);
  55. }
  56. static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec wtm)
  57. {
  58. struct timespec tmp;
  59. /*
  60. * Verify consistency of: offset_real = -wall_to_monotonic
  61. * before modifying anything
  62. */
  63. set_normalized_timespec(&tmp, -tk->wall_to_monotonic.tv_sec,
  64. -tk->wall_to_monotonic.tv_nsec);
  65. WARN_ON_ONCE(tk->offs_real.tv64 != timespec_to_ktime(tmp).tv64);
  66. tk->wall_to_monotonic = wtm;
  67. set_normalized_timespec(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
  68. tk->offs_real = timespec_to_ktime(tmp);
  69. tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tk->tai_offset, 0));
  70. }
  71. static void tk_set_sleep_time(struct timekeeper *tk, struct timespec t)
  72. {
  73. /* Verify consistency before modifying */
  74. WARN_ON_ONCE(tk->offs_boot.tv64 != timespec_to_ktime(tk->total_sleep_time).tv64);
  75. tk->total_sleep_time = t;
  76. tk->offs_boot = timespec_to_ktime(t);
  77. }
  78. /**
  79. * timekeeper_setup_internals - Set up internals to use clocksource clock.
  80. *
  81. * @clock: Pointer to clocksource.
  82. *
  83. * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
  84. * pair and interval request.
  85. *
  86. * Unless you're the timekeeping code, you should not be using this!
  87. */
  88. static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
  89. {
  90. cycle_t interval;
  91. u64 tmp, ntpinterval;
  92. struct clocksource *old_clock;
  93. old_clock = tk->clock;
  94. tk->clock = clock;
  95. tk->cycle_last = clock->cycle_last = clock->read(clock);
  96. /* Do the ns -> cycle conversion first, using original mult */
  97. tmp = NTP_INTERVAL_LENGTH;
  98. tmp <<= clock->shift;
  99. ntpinterval = tmp;
  100. tmp += clock->mult/2;
  101. do_div(tmp, clock->mult);
  102. if (tmp == 0)
  103. tmp = 1;
  104. interval = (cycle_t) tmp;
  105. tk->cycle_interval = interval;
  106. /* Go back from cycles -> shifted ns */
  107. tk->xtime_interval = (u64) interval * clock->mult;
  108. tk->xtime_remainder = ntpinterval - tk->xtime_interval;
  109. tk->raw_interval =
  110. ((u64) interval * clock->mult) >> clock->shift;
  111. /* if changing clocks, convert xtime_nsec shift units */
  112. if (old_clock) {
  113. int shift_change = clock->shift - old_clock->shift;
  114. if (shift_change < 0)
  115. tk->xtime_nsec >>= -shift_change;
  116. else
  117. tk->xtime_nsec <<= shift_change;
  118. }
  119. tk->shift = clock->shift;
  120. tk->ntp_error = 0;
  121. tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
  122. /*
  123. * The timekeeper keeps its own mult values for the currently
  124. * active clocksource. These value will be adjusted via NTP
  125. * to counteract clock drifting.
  126. */
  127. tk->mult = clock->mult;
  128. }
  129. /* Timekeeper helper functions. */
  130. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  131. u32 (*arch_gettimeoffset)(void);
  132. u32 get_arch_timeoffset(void)
  133. {
  134. if (likely(arch_gettimeoffset))
  135. return arch_gettimeoffset();
  136. return 0;
  137. }
  138. #else
  139. static inline u32 get_arch_timeoffset(void) { return 0; }
  140. #endif
  141. static inline s64 timekeeping_get_ns(struct timekeeper *tk)
  142. {
  143. cycle_t cycle_now, cycle_delta;
  144. struct clocksource *clock;
  145. s64 nsec;
  146. /* read clocksource: */
  147. clock = tk->clock;
  148. cycle_now = clock->read(clock);
  149. /* calculate the delta since the last update_wall_time: */
  150. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  151. nsec = cycle_delta * tk->mult + tk->xtime_nsec;
  152. nsec >>= tk->shift;
  153. /* If arch requires, add in get_arch_timeoffset() */
  154. return nsec + get_arch_timeoffset();
  155. }
  156. static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
  157. {
  158. cycle_t cycle_now, cycle_delta;
  159. struct clocksource *clock;
  160. s64 nsec;
  161. /* read clocksource: */
  162. clock = tk->clock;
  163. cycle_now = clock->read(clock);
  164. /* calculate the delta since the last update_wall_time: */
  165. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  166. /* convert delta to nanoseconds. */
  167. nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
  168. /* If arch requires, add in get_arch_timeoffset() */
  169. return nsec + get_arch_timeoffset();
  170. }
  171. static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
  172. static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
  173. {
  174. raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
  175. }
  176. /**
  177. * pvclock_gtod_register_notifier - register a pvclock timedata update listener
  178. */
  179. int pvclock_gtod_register_notifier(struct notifier_block *nb)
  180. {
  181. struct timekeeper *tk = &timekeeper;
  182. unsigned long flags;
  183. int ret;
  184. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  185. ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
  186. update_pvclock_gtod(tk, true);
  187. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  188. return ret;
  189. }
  190. EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
  191. /**
  192. * pvclock_gtod_unregister_notifier - unregister a pvclock
  193. * timedata update listener
  194. */
  195. int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
  196. {
  197. unsigned long flags;
  198. int ret;
  199. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  200. ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
  201. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  202. return ret;
  203. }
  204. EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
  205. /* must hold timekeeper_lock */
  206. static void timekeeping_update(struct timekeeper *tk, unsigned int action)
  207. {
  208. if (action & TK_CLEAR_NTP) {
  209. tk->ntp_error = 0;
  210. ntp_clear();
  211. }
  212. update_vsyscall(tk);
  213. update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
  214. if (action & TK_MIRROR)
  215. memcpy(&shadow_timekeeper, &timekeeper, sizeof(timekeeper));
  216. }
  217. /**
  218. * timekeeping_forward_now - update clock to the current time
  219. *
  220. * Forward the current clock to update its state since the last call to
  221. * update_wall_time(). This is useful before significant clock changes,
  222. * as it avoids having to deal with this time offset explicitly.
  223. */
  224. static void timekeeping_forward_now(struct timekeeper *tk)
  225. {
  226. cycle_t cycle_now, cycle_delta;
  227. struct clocksource *clock;
  228. s64 nsec;
  229. clock = tk->clock;
  230. cycle_now = clock->read(clock);
  231. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  232. tk->cycle_last = clock->cycle_last = cycle_now;
  233. tk->xtime_nsec += cycle_delta * tk->mult;
  234. /* If arch requires, add in get_arch_timeoffset() */
  235. tk->xtime_nsec += (u64)get_arch_timeoffset() << tk->shift;
  236. tk_normalize_xtime(tk);
  237. nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
  238. timespec_add_ns(&tk->raw_time, nsec);
  239. }
  240. /**
  241. * __getnstimeofday - Returns the time of day in a timespec.
  242. * @ts: pointer to the timespec to be set
  243. *
  244. * Updates the time of day in the timespec.
  245. * Returns 0 on success, or -ve when suspended (timespec will be undefined).
  246. */
  247. int __getnstimeofday(struct timespec *ts)
  248. {
  249. struct timekeeper *tk = &timekeeper;
  250. unsigned long seq;
  251. s64 nsecs = 0;
  252. do {
  253. seq = read_seqcount_begin(&timekeeper_seq);
  254. ts->tv_sec = tk->xtime_sec;
  255. nsecs = timekeeping_get_ns(tk);
  256. } while (read_seqcount_retry(&timekeeper_seq, seq));
  257. ts->tv_nsec = 0;
  258. timespec_add_ns(ts, nsecs);
  259. /*
  260. * Do not bail out early, in case there were callers still using
  261. * the value, even in the face of the WARN_ON.
  262. */
  263. if (unlikely(timekeeping_suspended))
  264. return -EAGAIN;
  265. return 0;
  266. }
  267. EXPORT_SYMBOL(__getnstimeofday);
  268. /**
  269. * getnstimeofday - Returns the time of day in a timespec.
  270. * @ts: pointer to the timespec to be set
  271. *
  272. * Returns the time of day in a timespec (WARN if suspended).
  273. */
  274. void getnstimeofday(struct timespec *ts)
  275. {
  276. WARN_ON(__getnstimeofday(ts));
  277. }
  278. EXPORT_SYMBOL(getnstimeofday);
  279. ktime_t ktime_get(void)
  280. {
  281. struct timekeeper *tk = &timekeeper;
  282. unsigned int seq;
  283. s64 secs, nsecs;
  284. WARN_ON(timekeeping_suspended);
  285. do {
  286. seq = read_seqcount_begin(&timekeeper_seq);
  287. secs = tk->xtime_sec + tk->wall_to_monotonic.tv_sec;
  288. nsecs = timekeeping_get_ns(tk) + tk->wall_to_monotonic.tv_nsec;
  289. } while (read_seqcount_retry(&timekeeper_seq, seq));
  290. /*
  291. * Use ktime_set/ktime_add_ns to create a proper ktime on
  292. * 32-bit architectures without CONFIG_KTIME_SCALAR.
  293. */
  294. return ktime_add_ns(ktime_set(secs, 0), nsecs);
  295. }
  296. EXPORT_SYMBOL_GPL(ktime_get);
  297. /**
  298. * ktime_get_ts - get the monotonic clock in timespec format
  299. * @ts: pointer to timespec variable
  300. *
  301. * The function calculates the monotonic clock from the realtime
  302. * clock and the wall_to_monotonic offset and stores the result
  303. * in normalized timespec format in the variable pointed to by @ts.
  304. */
  305. void ktime_get_ts(struct timespec *ts)
  306. {
  307. struct timekeeper *tk = &timekeeper;
  308. struct timespec tomono;
  309. s64 nsec;
  310. unsigned int seq;
  311. WARN_ON(timekeeping_suspended);
  312. do {
  313. seq = read_seqcount_begin(&timekeeper_seq);
  314. ts->tv_sec = tk->xtime_sec;
  315. nsec = timekeeping_get_ns(tk);
  316. tomono = tk->wall_to_monotonic;
  317. } while (read_seqcount_retry(&timekeeper_seq, seq));
  318. ts->tv_sec += tomono.tv_sec;
  319. ts->tv_nsec = 0;
  320. timespec_add_ns(ts, nsec + tomono.tv_nsec);
  321. }
  322. EXPORT_SYMBOL_GPL(ktime_get_ts);
  323. /**
  324. * timekeeping_clocktai - Returns the TAI time of day in a timespec
  325. * @ts: pointer to the timespec to be set
  326. *
  327. * Returns the time of day in a timespec.
  328. */
  329. void timekeeping_clocktai(struct timespec *ts)
  330. {
  331. struct timekeeper *tk = &timekeeper;
  332. unsigned long seq;
  333. u64 nsecs;
  334. WARN_ON(timekeeping_suspended);
  335. do {
  336. seq = read_seqcount_begin(&timekeeper_seq);
  337. ts->tv_sec = tk->xtime_sec + tk->tai_offset;
  338. nsecs = timekeeping_get_ns(tk);
  339. } while (read_seqcount_retry(&timekeeper_seq, seq));
  340. ts->tv_nsec = 0;
  341. timespec_add_ns(ts, nsecs);
  342. }
  343. EXPORT_SYMBOL(timekeeping_clocktai);
  344. /**
  345. * ktime_get_clocktai - Returns the TAI time of day in a ktime
  346. *
  347. * Returns the time of day in a ktime.
  348. */
  349. ktime_t ktime_get_clocktai(void)
  350. {
  351. struct timespec ts;
  352. timekeeping_clocktai(&ts);
  353. return timespec_to_ktime(ts);
  354. }
  355. EXPORT_SYMBOL(ktime_get_clocktai);
  356. #ifdef CONFIG_NTP_PPS
  357. /**
  358. * getnstime_raw_and_real - get day and raw monotonic time in timespec format
  359. * @ts_raw: pointer to the timespec to be set to raw monotonic time
  360. * @ts_real: pointer to the timespec to be set to the time of day
  361. *
  362. * This function reads both the time of day and raw monotonic time at the
  363. * same time atomically and stores the resulting timestamps in timespec
  364. * format.
  365. */
  366. void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
  367. {
  368. struct timekeeper *tk = &timekeeper;
  369. unsigned long seq;
  370. s64 nsecs_raw, nsecs_real;
  371. WARN_ON_ONCE(timekeeping_suspended);
  372. do {
  373. seq = read_seqcount_begin(&timekeeper_seq);
  374. *ts_raw = tk->raw_time;
  375. ts_real->tv_sec = tk->xtime_sec;
  376. ts_real->tv_nsec = 0;
  377. nsecs_raw = timekeeping_get_ns_raw(tk);
  378. nsecs_real = timekeeping_get_ns(tk);
  379. } while (read_seqcount_retry(&timekeeper_seq, seq));
  380. timespec_add_ns(ts_raw, nsecs_raw);
  381. timespec_add_ns(ts_real, nsecs_real);
  382. }
  383. EXPORT_SYMBOL(getnstime_raw_and_real);
  384. #endif /* CONFIG_NTP_PPS */
  385. /**
  386. * do_gettimeofday - Returns the time of day in a timeval
  387. * @tv: pointer to the timeval to be set
  388. *
  389. * NOTE: Users should be converted to using getnstimeofday()
  390. */
  391. void do_gettimeofday(struct timeval *tv)
  392. {
  393. struct timespec now;
  394. getnstimeofday(&now);
  395. tv->tv_sec = now.tv_sec;
  396. tv->tv_usec = now.tv_nsec/1000;
  397. }
  398. EXPORT_SYMBOL(do_gettimeofday);
  399. /**
  400. * do_settimeofday - Sets the time of day
  401. * @tv: pointer to the timespec variable containing the new time
  402. *
  403. * Sets the time of day to the new time and update NTP and notify hrtimers
  404. */
  405. int do_settimeofday(const struct timespec *tv)
  406. {
  407. struct timekeeper *tk = &timekeeper;
  408. struct timespec ts_delta, xt;
  409. unsigned long flags;
  410. if (!timespec_valid_strict(tv))
  411. return -EINVAL;
  412. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  413. write_seqcount_begin(&timekeeper_seq);
  414. timekeeping_forward_now(tk);
  415. xt = tk_xtime(tk);
  416. ts_delta.tv_sec = tv->tv_sec - xt.tv_sec;
  417. ts_delta.tv_nsec = tv->tv_nsec - xt.tv_nsec;
  418. tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, ts_delta));
  419. tk_set_xtime(tk, tv);
  420. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  421. write_seqcount_end(&timekeeper_seq);
  422. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  423. /* signal hrtimers about time change */
  424. clock_was_set();
  425. return 0;
  426. }
  427. EXPORT_SYMBOL(do_settimeofday);
  428. /**
  429. * timekeeping_inject_offset - Adds or subtracts from the current time.
  430. * @tv: pointer to the timespec variable containing the offset
  431. *
  432. * Adds or subtracts an offset value from the current time.
  433. */
  434. int timekeeping_inject_offset(struct timespec *ts)
  435. {
  436. struct timekeeper *tk = &timekeeper;
  437. unsigned long flags;
  438. struct timespec tmp;
  439. int ret = 0;
  440. if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
  441. return -EINVAL;
  442. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  443. write_seqcount_begin(&timekeeper_seq);
  444. timekeeping_forward_now(tk);
  445. /* Make sure the proposed value is valid */
  446. tmp = timespec_add(tk_xtime(tk), *ts);
  447. if (!timespec_valid_strict(&tmp)) {
  448. ret = -EINVAL;
  449. goto error;
  450. }
  451. tk_xtime_add(tk, ts);
  452. tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *ts));
  453. error: /* even if we error out, we forwarded the time, so call update */
  454. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  455. write_seqcount_end(&timekeeper_seq);
  456. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  457. /* signal hrtimers about time change */
  458. clock_was_set();
  459. return ret;
  460. }
  461. EXPORT_SYMBOL(timekeeping_inject_offset);
  462. /**
  463. * timekeeping_get_tai_offset - Returns current TAI offset from UTC
  464. *
  465. */
  466. s32 timekeeping_get_tai_offset(void)
  467. {
  468. struct timekeeper *tk = &timekeeper;
  469. unsigned int seq;
  470. s32 ret;
  471. do {
  472. seq = read_seqcount_begin(&timekeeper_seq);
  473. ret = tk->tai_offset;
  474. } while (read_seqcount_retry(&timekeeper_seq, seq));
  475. return ret;
  476. }
  477. /**
  478. * __timekeeping_set_tai_offset - Lock free worker function
  479. *
  480. */
  481. static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
  482. {
  483. tk->tai_offset = tai_offset;
  484. tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tai_offset, 0));
  485. }
  486. /**
  487. * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
  488. *
  489. */
  490. void timekeeping_set_tai_offset(s32 tai_offset)
  491. {
  492. struct timekeeper *tk = &timekeeper;
  493. unsigned long flags;
  494. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  495. write_seqcount_begin(&timekeeper_seq);
  496. __timekeeping_set_tai_offset(tk, tai_offset);
  497. write_seqcount_end(&timekeeper_seq);
  498. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  499. clock_was_set();
  500. }
  501. /**
  502. * change_clocksource - Swaps clocksources if a new one is available
  503. *
  504. * Accumulates current time interval and initializes new clocksource
  505. */
  506. static int change_clocksource(void *data)
  507. {
  508. struct timekeeper *tk = &timekeeper;
  509. struct clocksource *new, *old;
  510. unsigned long flags;
  511. new = (struct clocksource *) data;
  512. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  513. write_seqcount_begin(&timekeeper_seq);
  514. timekeeping_forward_now(tk);
  515. /*
  516. * If the cs is in module, get a module reference. Succeeds
  517. * for built-in code (owner == NULL) as well.
  518. */
  519. if (try_module_get(new->owner)) {
  520. if (!new->enable || new->enable(new) == 0) {
  521. old = tk->clock;
  522. tk_setup_internals(tk, new);
  523. if (old->disable)
  524. old->disable(old);
  525. module_put(old->owner);
  526. } else {
  527. module_put(new->owner);
  528. }
  529. }
  530. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  531. write_seqcount_end(&timekeeper_seq);
  532. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  533. return 0;
  534. }
  535. /**
  536. * timekeeping_notify - Install a new clock source
  537. * @clock: pointer to the clock source
  538. *
  539. * This function is called from clocksource.c after a new, better clock
  540. * source has been registered. The caller holds the clocksource_mutex.
  541. */
  542. int timekeeping_notify(struct clocksource *clock)
  543. {
  544. struct timekeeper *tk = &timekeeper;
  545. if (tk->clock == clock)
  546. return 0;
  547. stop_machine(change_clocksource, clock, NULL);
  548. tick_clock_notify();
  549. return tk->clock == clock ? 0 : -1;
  550. }
  551. /**
  552. * ktime_get_real - get the real (wall-) time in ktime_t format
  553. *
  554. * returns the time in ktime_t format
  555. */
  556. ktime_t ktime_get_real(void)
  557. {
  558. struct timespec now;
  559. getnstimeofday(&now);
  560. return timespec_to_ktime(now);
  561. }
  562. EXPORT_SYMBOL_GPL(ktime_get_real);
  563. /**
  564. * getrawmonotonic - Returns the raw monotonic time in a timespec
  565. * @ts: pointer to the timespec to be set
  566. *
  567. * Returns the raw monotonic time (completely un-modified by ntp)
  568. */
  569. void getrawmonotonic(struct timespec *ts)
  570. {
  571. struct timekeeper *tk = &timekeeper;
  572. unsigned long seq;
  573. s64 nsecs;
  574. do {
  575. seq = read_seqcount_begin(&timekeeper_seq);
  576. nsecs = timekeeping_get_ns_raw(tk);
  577. *ts = tk->raw_time;
  578. } while (read_seqcount_retry(&timekeeper_seq, seq));
  579. timespec_add_ns(ts, nsecs);
  580. }
  581. EXPORT_SYMBOL(getrawmonotonic);
  582. /**
  583. * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
  584. */
  585. int timekeeping_valid_for_hres(void)
  586. {
  587. struct timekeeper *tk = &timekeeper;
  588. unsigned long seq;
  589. int ret;
  590. do {
  591. seq = read_seqcount_begin(&timekeeper_seq);
  592. ret = tk->clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  593. } while (read_seqcount_retry(&timekeeper_seq, seq));
  594. return ret;
  595. }
  596. /**
  597. * timekeeping_max_deferment - Returns max time the clocksource can be deferred
  598. */
  599. u64 timekeeping_max_deferment(void)
  600. {
  601. struct timekeeper *tk = &timekeeper;
  602. unsigned long seq;
  603. u64 ret;
  604. do {
  605. seq = read_seqcount_begin(&timekeeper_seq);
  606. ret = tk->clock->max_idle_ns;
  607. } while (read_seqcount_retry(&timekeeper_seq, seq));
  608. return ret;
  609. }
  610. /**
  611. * read_persistent_clock - Return time from the persistent clock.
  612. *
  613. * Weak dummy function for arches that do not yet support it.
  614. * Reads the time from the battery backed persistent clock.
  615. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  616. *
  617. * XXX - Do be sure to remove it once all arches implement it.
  618. */
  619. void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
  620. {
  621. ts->tv_sec = 0;
  622. ts->tv_nsec = 0;
  623. }
  624. /**
  625. * read_boot_clock - Return time of the system start.
  626. *
  627. * Weak dummy function for arches that do not yet support it.
  628. * Function to read the exact time the system has been started.
  629. * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
  630. *
  631. * XXX - Do be sure to remove it once all arches implement it.
  632. */
  633. void __attribute__((weak)) read_boot_clock(struct timespec *ts)
  634. {
  635. ts->tv_sec = 0;
  636. ts->tv_nsec = 0;
  637. }
  638. /*
  639. * timekeeping_init - Initializes the clocksource and common timekeeping values
  640. */
  641. void __init timekeeping_init(void)
  642. {
  643. struct timekeeper *tk = &timekeeper;
  644. struct clocksource *clock;
  645. unsigned long flags;
  646. struct timespec now, boot, tmp;
  647. read_persistent_clock(&now);
  648. if (!timespec_valid_strict(&now)) {
  649. pr_warn("WARNING: Persistent clock returned invalid value!\n"
  650. " Check your CMOS/BIOS settings.\n");
  651. now.tv_sec = 0;
  652. now.tv_nsec = 0;
  653. } else if (now.tv_sec || now.tv_nsec)
  654. persistent_clock_exist = true;
  655. read_boot_clock(&boot);
  656. if (!timespec_valid_strict(&boot)) {
  657. pr_warn("WARNING: Boot clock returned invalid value!\n"
  658. " Check your CMOS/BIOS settings.\n");
  659. boot.tv_sec = 0;
  660. boot.tv_nsec = 0;
  661. }
  662. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  663. write_seqcount_begin(&timekeeper_seq);
  664. ntp_init();
  665. clock = clocksource_default_clock();
  666. if (clock->enable)
  667. clock->enable(clock);
  668. tk_setup_internals(tk, clock);
  669. tk_set_xtime(tk, &now);
  670. tk->raw_time.tv_sec = 0;
  671. tk->raw_time.tv_nsec = 0;
  672. if (boot.tv_sec == 0 && boot.tv_nsec == 0)
  673. boot = tk_xtime(tk);
  674. set_normalized_timespec(&tmp, -boot.tv_sec, -boot.tv_nsec);
  675. tk_set_wall_to_mono(tk, tmp);
  676. tmp.tv_sec = 0;
  677. tmp.tv_nsec = 0;
  678. tk_set_sleep_time(tk, tmp);
  679. memcpy(&shadow_timekeeper, &timekeeper, sizeof(timekeeper));
  680. write_seqcount_end(&timekeeper_seq);
  681. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  682. }
  683. /* time in seconds when suspend began */
  684. static struct timespec timekeeping_suspend_time;
  685. /**
  686. * __timekeeping_inject_sleeptime - Internal function to add sleep interval
  687. * @delta: pointer to a timespec delta value
  688. *
  689. * Takes a timespec offset measuring a suspend interval and properly
  690. * adds the sleep offset to the timekeeping variables.
  691. */
  692. static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
  693. struct timespec *delta)
  694. {
  695. if (!timespec_valid_strict(delta)) {
  696. printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
  697. "sleep delta value!\n");
  698. return;
  699. }
  700. tk_xtime_add(tk, delta);
  701. tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *delta));
  702. tk_set_sleep_time(tk, timespec_add(tk->total_sleep_time, *delta));
  703. tk_debug_account_sleep_time(delta);
  704. }
  705. /**
  706. * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
  707. * @delta: pointer to a timespec delta value
  708. *
  709. * This hook is for architectures that cannot support read_persistent_clock
  710. * because their RTC/persistent clock is only accessible when irqs are enabled.
  711. *
  712. * This function should only be called by rtc_resume(), and allows
  713. * a suspend offset to be injected into the timekeeping values.
  714. */
  715. void timekeeping_inject_sleeptime(struct timespec *delta)
  716. {
  717. struct timekeeper *tk = &timekeeper;
  718. unsigned long flags;
  719. /*
  720. * Make sure we don't set the clock twice, as timekeeping_resume()
  721. * already did it
  722. */
  723. if (has_persistent_clock())
  724. return;
  725. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  726. write_seqcount_begin(&timekeeper_seq);
  727. timekeeping_forward_now(tk);
  728. __timekeeping_inject_sleeptime(tk, delta);
  729. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  730. write_seqcount_end(&timekeeper_seq);
  731. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  732. /* signal hrtimers about time change */
  733. clock_was_set();
  734. }
  735. /**
  736. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  737. *
  738. * This is for the generic clocksource timekeeping.
  739. * xtime/wall_to_monotonic/jiffies/etc are
  740. * still managed by arch specific suspend/resume code.
  741. */
  742. static void timekeeping_resume(void)
  743. {
  744. struct timekeeper *tk = &timekeeper;
  745. struct clocksource *clock = tk->clock;
  746. unsigned long flags;
  747. struct timespec ts_new, ts_delta;
  748. cycle_t cycle_now, cycle_delta;
  749. bool suspendtime_found = false;
  750. read_persistent_clock(&ts_new);
  751. clockevents_resume();
  752. clocksource_resume();
  753. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  754. write_seqcount_begin(&timekeeper_seq);
  755. /*
  756. * After system resumes, we need to calculate the suspended time and
  757. * compensate it for the OS time. There are 3 sources that could be
  758. * used: Nonstop clocksource during suspend, persistent clock and rtc
  759. * device.
  760. *
  761. * One specific platform may have 1 or 2 or all of them, and the
  762. * preference will be:
  763. * suspend-nonstop clocksource -> persistent clock -> rtc
  764. * The less preferred source will only be tried if there is no better
  765. * usable source. The rtc part is handled separately in rtc core code.
  766. */
  767. cycle_now = clock->read(clock);
  768. if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
  769. cycle_now > clock->cycle_last) {
  770. u64 num, max = ULLONG_MAX;
  771. u32 mult = clock->mult;
  772. u32 shift = clock->shift;
  773. s64 nsec = 0;
  774. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  775. /*
  776. * "cycle_delta * mutl" may cause 64 bits overflow, if the
  777. * suspended time is too long. In that case we need do the
  778. * 64 bits math carefully
  779. */
  780. do_div(max, mult);
  781. if (cycle_delta > max) {
  782. num = div64_u64(cycle_delta, max);
  783. nsec = (((u64) max * mult) >> shift) * num;
  784. cycle_delta -= num * max;
  785. }
  786. nsec += ((u64) cycle_delta * mult) >> shift;
  787. ts_delta = ns_to_timespec(nsec);
  788. suspendtime_found = true;
  789. } else if (timespec_compare(&ts_new, &timekeeping_suspend_time) > 0) {
  790. ts_delta = timespec_sub(ts_new, timekeeping_suspend_time);
  791. suspendtime_found = true;
  792. }
  793. if (suspendtime_found)
  794. __timekeeping_inject_sleeptime(tk, &ts_delta);
  795. /* Re-base the last cycle value */
  796. tk->cycle_last = clock->cycle_last = cycle_now;
  797. tk->ntp_error = 0;
  798. timekeeping_suspended = 0;
  799. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  800. write_seqcount_end(&timekeeper_seq);
  801. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  802. touch_softlockup_watchdog();
  803. clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
  804. /* Resume hrtimers */
  805. hrtimers_resume();
  806. }
  807. static int timekeeping_suspend(void)
  808. {
  809. struct timekeeper *tk = &timekeeper;
  810. unsigned long flags;
  811. struct timespec delta, delta_delta;
  812. static struct timespec old_delta;
  813. read_persistent_clock(&timekeeping_suspend_time);
  814. /*
  815. * On some systems the persistent_clock can not be detected at
  816. * timekeeping_init by its return value, so if we see a valid
  817. * value returned, update the persistent_clock_exists flag.
  818. */
  819. if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
  820. persistent_clock_exist = true;
  821. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  822. write_seqcount_begin(&timekeeper_seq);
  823. timekeeping_forward_now(tk);
  824. timekeeping_suspended = 1;
  825. /*
  826. * To avoid drift caused by repeated suspend/resumes,
  827. * which each can add ~1 second drift error,
  828. * try to compensate so the difference in system time
  829. * and persistent_clock time stays close to constant.
  830. */
  831. delta = timespec_sub(tk_xtime(tk), timekeeping_suspend_time);
  832. delta_delta = timespec_sub(delta, old_delta);
  833. if (abs(delta_delta.tv_sec) >= 2) {
  834. /*
  835. * if delta_delta is too large, assume time correction
  836. * has occured and set old_delta to the current delta.
  837. */
  838. old_delta = delta;
  839. } else {
  840. /* Otherwise try to adjust old_system to compensate */
  841. timekeeping_suspend_time =
  842. timespec_add(timekeeping_suspend_time, delta_delta);
  843. }
  844. write_seqcount_end(&timekeeper_seq);
  845. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  846. clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
  847. clocksource_suspend();
  848. clockevents_suspend();
  849. return 0;
  850. }
  851. /* sysfs resume/suspend bits for timekeeping */
  852. static struct syscore_ops timekeeping_syscore_ops = {
  853. .resume = timekeeping_resume,
  854. .suspend = timekeeping_suspend,
  855. };
  856. static int __init timekeeping_init_ops(void)
  857. {
  858. register_syscore_ops(&timekeeping_syscore_ops);
  859. return 0;
  860. }
  861. device_initcall(timekeeping_init_ops);
  862. /*
  863. * If the error is already larger, we look ahead even further
  864. * to compensate for late or lost adjustments.
  865. */
  866. static __always_inline int timekeeping_bigadjust(struct timekeeper *tk,
  867. s64 error, s64 *interval,
  868. s64 *offset)
  869. {
  870. s64 tick_error, i;
  871. u32 look_ahead, adj;
  872. s32 error2, mult;
  873. /*
  874. * Use the current error value to determine how much to look ahead.
  875. * The larger the error the slower we adjust for it to avoid problems
  876. * with losing too many ticks, otherwise we would overadjust and
  877. * produce an even larger error. The smaller the adjustment the
  878. * faster we try to adjust for it, as lost ticks can do less harm
  879. * here. This is tuned so that an error of about 1 msec is adjusted
  880. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  881. */
  882. error2 = tk->ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
  883. error2 = abs(error2);
  884. for (look_ahead = 0; error2 > 0; look_ahead++)
  885. error2 >>= 2;
  886. /*
  887. * Now calculate the error in (1 << look_ahead) ticks, but first
  888. * remove the single look ahead already included in the error.
  889. */
  890. tick_error = ntp_tick_length() >> (tk->ntp_error_shift + 1);
  891. tick_error -= tk->xtime_interval >> 1;
  892. error = ((error - tick_error) >> look_ahead) + tick_error;
  893. /* Finally calculate the adjustment shift value. */
  894. i = *interval;
  895. mult = 1;
  896. if (error < 0) {
  897. error = -error;
  898. *interval = -*interval;
  899. *offset = -*offset;
  900. mult = -1;
  901. }
  902. for (adj = 0; error > i; adj++)
  903. error >>= 1;
  904. *interval <<= adj;
  905. *offset <<= adj;
  906. return mult << adj;
  907. }
  908. /*
  909. * Adjust the multiplier to reduce the error value,
  910. * this is optimized for the most common adjustments of -1,0,1,
  911. * for other values we can do a bit more work.
  912. */
  913. static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
  914. {
  915. s64 error, interval = tk->cycle_interval;
  916. int adj;
  917. /*
  918. * The point of this is to check if the error is greater than half
  919. * an interval.
  920. *
  921. * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
  922. *
  923. * Note we subtract one in the shift, so that error is really error*2.
  924. * This "saves" dividing(shifting) interval twice, but keeps the
  925. * (error > interval) comparison as still measuring if error is
  926. * larger than half an interval.
  927. *
  928. * Note: It does not "save" on aggravation when reading the code.
  929. */
  930. error = tk->ntp_error >> (tk->ntp_error_shift - 1);
  931. if (error > interval) {
  932. /*
  933. * We now divide error by 4(via shift), which checks if
  934. * the error is greater than twice the interval.
  935. * If it is greater, we need a bigadjust, if its smaller,
  936. * we can adjust by 1.
  937. */
  938. error >>= 2;
  939. /*
  940. * XXX - In update_wall_time, we round up to the next
  941. * nanosecond, and store the amount rounded up into
  942. * the error. This causes the likely below to be unlikely.
  943. *
  944. * The proper fix is to avoid rounding up by using
  945. * the high precision tk->xtime_nsec instead of
  946. * xtime.tv_nsec everywhere. Fixing this will take some
  947. * time.
  948. */
  949. if (likely(error <= interval))
  950. adj = 1;
  951. else
  952. adj = timekeeping_bigadjust(tk, error, &interval, &offset);
  953. } else {
  954. if (error < -interval) {
  955. /* See comment above, this is just switched for the negative */
  956. error >>= 2;
  957. if (likely(error >= -interval)) {
  958. adj = -1;
  959. interval = -interval;
  960. offset = -offset;
  961. } else {
  962. adj = timekeeping_bigadjust(tk, error, &interval, &offset);
  963. }
  964. } else {
  965. goto out_adjust;
  966. }
  967. }
  968. if (unlikely(tk->clock->maxadj &&
  969. (tk->mult + adj > tk->clock->mult + tk->clock->maxadj))) {
  970. printk_once(KERN_WARNING
  971. "Adjusting %s more than 11%% (%ld vs %ld)\n",
  972. tk->clock->name, (long)tk->mult + adj,
  973. (long)tk->clock->mult + tk->clock->maxadj);
  974. }
  975. /*
  976. * So the following can be confusing.
  977. *
  978. * To keep things simple, lets assume adj == 1 for now.
  979. *
  980. * When adj != 1, remember that the interval and offset values
  981. * have been appropriately scaled so the math is the same.
  982. *
  983. * The basic idea here is that we're increasing the multiplier
  984. * by one, this causes the xtime_interval to be incremented by
  985. * one cycle_interval. This is because:
  986. * xtime_interval = cycle_interval * mult
  987. * So if mult is being incremented by one:
  988. * xtime_interval = cycle_interval * (mult + 1)
  989. * Its the same as:
  990. * xtime_interval = (cycle_interval * mult) + cycle_interval
  991. * Which can be shortened to:
  992. * xtime_interval += cycle_interval
  993. *
  994. * So offset stores the non-accumulated cycles. Thus the current
  995. * time (in shifted nanoseconds) is:
  996. * now = (offset * adj) + xtime_nsec
  997. * Now, even though we're adjusting the clock frequency, we have
  998. * to keep time consistent. In other words, we can't jump back
  999. * in time, and we also want to avoid jumping forward in time.
  1000. *
  1001. * So given the same offset value, we need the time to be the same
  1002. * both before and after the freq adjustment.
  1003. * now = (offset * adj_1) + xtime_nsec_1
  1004. * now = (offset * adj_2) + xtime_nsec_2
  1005. * So:
  1006. * (offset * adj_1) + xtime_nsec_1 =
  1007. * (offset * adj_2) + xtime_nsec_2
  1008. * And we know:
  1009. * adj_2 = adj_1 + 1
  1010. * So:
  1011. * (offset * adj_1) + xtime_nsec_1 =
  1012. * (offset * (adj_1+1)) + xtime_nsec_2
  1013. * (offset * adj_1) + xtime_nsec_1 =
  1014. * (offset * adj_1) + offset + xtime_nsec_2
  1015. * Canceling the sides:
  1016. * xtime_nsec_1 = offset + xtime_nsec_2
  1017. * Which gives us:
  1018. * xtime_nsec_2 = xtime_nsec_1 - offset
  1019. * Which simplfies to:
  1020. * xtime_nsec -= offset
  1021. *
  1022. * XXX - TODO: Doc ntp_error calculation.
  1023. */
  1024. tk->mult += adj;
  1025. tk->xtime_interval += interval;
  1026. tk->xtime_nsec -= offset;
  1027. tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
  1028. out_adjust:
  1029. /*
  1030. * It may be possible that when we entered this function, xtime_nsec
  1031. * was very small. Further, if we're slightly speeding the clocksource
  1032. * in the code above, its possible the required corrective factor to
  1033. * xtime_nsec could cause it to underflow.
  1034. *
  1035. * Now, since we already accumulated the second, cannot simply roll
  1036. * the accumulated second back, since the NTP subsystem has been
  1037. * notified via second_overflow. So instead we push xtime_nsec forward
  1038. * by the amount we underflowed, and add that amount into the error.
  1039. *
  1040. * We'll correct this error next time through this function, when
  1041. * xtime_nsec is not as small.
  1042. */
  1043. if (unlikely((s64)tk->xtime_nsec < 0)) {
  1044. s64 neg = -(s64)tk->xtime_nsec;
  1045. tk->xtime_nsec = 0;
  1046. tk->ntp_error += neg << tk->ntp_error_shift;
  1047. }
  1048. }
  1049. /**
  1050. * accumulate_nsecs_to_secs - Accumulates nsecs into secs
  1051. *
  1052. * Helper function that accumulates a the nsecs greater then a second
  1053. * from the xtime_nsec field to the xtime_secs field.
  1054. * It also calls into the NTP code to handle leapsecond processing.
  1055. *
  1056. */
  1057. static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
  1058. {
  1059. u64 nsecps = (u64)NSEC_PER_SEC << tk->shift;
  1060. unsigned int action = 0;
  1061. while (tk->xtime_nsec >= nsecps) {
  1062. int leap;
  1063. tk->xtime_nsec -= nsecps;
  1064. tk->xtime_sec++;
  1065. /* Figure out if its a leap sec and apply if needed */
  1066. leap = second_overflow(tk->xtime_sec);
  1067. if (unlikely(leap)) {
  1068. struct timespec ts;
  1069. tk->xtime_sec += leap;
  1070. ts.tv_sec = leap;
  1071. ts.tv_nsec = 0;
  1072. tk_set_wall_to_mono(tk,
  1073. timespec_sub(tk->wall_to_monotonic, ts));
  1074. __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
  1075. clock_was_set_delayed();
  1076. action = TK_CLOCK_WAS_SET;
  1077. }
  1078. }
  1079. return action;
  1080. }
  1081. /**
  1082. * logarithmic_accumulation - shifted accumulation of cycles
  1083. *
  1084. * This functions accumulates a shifted interval of cycles into
  1085. * into a shifted interval nanoseconds. Allows for O(log) accumulation
  1086. * loop.
  1087. *
  1088. * Returns the unconsumed cycles.
  1089. */
  1090. static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
  1091. u32 shift)
  1092. {
  1093. cycle_t interval = tk->cycle_interval << shift;
  1094. u64 raw_nsecs;
  1095. /* If the offset is smaller then a shifted interval, do nothing */
  1096. if (offset < interval)
  1097. return offset;
  1098. /* Accumulate one shifted interval */
  1099. offset -= interval;
  1100. tk->cycle_last += interval;
  1101. tk->xtime_nsec += tk->xtime_interval << shift;
  1102. accumulate_nsecs_to_secs(tk);
  1103. /* Accumulate raw time */
  1104. raw_nsecs = (u64)tk->raw_interval << shift;
  1105. raw_nsecs += tk->raw_time.tv_nsec;
  1106. if (raw_nsecs >= NSEC_PER_SEC) {
  1107. u64 raw_secs = raw_nsecs;
  1108. raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
  1109. tk->raw_time.tv_sec += raw_secs;
  1110. }
  1111. tk->raw_time.tv_nsec = raw_nsecs;
  1112. /* Accumulate error between NTP and clock interval */
  1113. tk->ntp_error += ntp_tick_length() << shift;
  1114. tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
  1115. (tk->ntp_error_shift + shift);
  1116. return offset;
  1117. }
  1118. #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
  1119. static inline void old_vsyscall_fixup(struct timekeeper *tk)
  1120. {
  1121. s64 remainder;
  1122. /*
  1123. * Store only full nanoseconds into xtime_nsec after rounding
  1124. * it up and add the remainder to the error difference.
  1125. * XXX - This is necessary to avoid small 1ns inconsistnecies caused
  1126. * by truncating the remainder in vsyscalls. However, it causes
  1127. * additional work to be done in timekeeping_adjust(). Once
  1128. * the vsyscall implementations are converted to use xtime_nsec
  1129. * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
  1130. * users are removed, this can be killed.
  1131. */
  1132. remainder = tk->xtime_nsec & ((1ULL << tk->shift) - 1);
  1133. tk->xtime_nsec -= remainder;
  1134. tk->xtime_nsec += 1ULL << tk->shift;
  1135. tk->ntp_error += remainder << tk->ntp_error_shift;
  1136. }
  1137. #else
  1138. #define old_vsyscall_fixup(tk)
  1139. #endif
  1140. /**
  1141. * update_wall_time - Uses the current clocksource to increment the wall time
  1142. *
  1143. */
  1144. static void update_wall_time(void)
  1145. {
  1146. struct clocksource *clock;
  1147. struct timekeeper *real_tk = &timekeeper;
  1148. struct timekeeper *tk = &shadow_timekeeper;
  1149. cycle_t offset;
  1150. int shift = 0, maxshift;
  1151. unsigned int action;
  1152. unsigned long flags;
  1153. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1154. /* Make sure we're fully resumed: */
  1155. if (unlikely(timekeeping_suspended))
  1156. goto out;
  1157. clock = real_tk->clock;
  1158. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  1159. offset = real_tk->cycle_interval;
  1160. #else
  1161. offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
  1162. #endif
  1163. /* Check if there's really nothing to do */
  1164. if (offset < real_tk->cycle_interval)
  1165. goto out;
  1166. /*
  1167. * With NO_HZ we may have to accumulate many cycle_intervals
  1168. * (think "ticks") worth of time at once. To do this efficiently,
  1169. * we calculate the largest doubling multiple of cycle_intervals
  1170. * that is smaller than the offset. We then accumulate that
  1171. * chunk in one go, and then try to consume the next smaller
  1172. * doubled multiple.
  1173. */
  1174. shift = ilog2(offset) - ilog2(tk->cycle_interval);
  1175. shift = max(0, shift);
  1176. /* Bound shift to one less than what overflows tick_length */
  1177. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  1178. shift = min(shift, maxshift);
  1179. while (offset >= tk->cycle_interval) {
  1180. offset = logarithmic_accumulation(tk, offset, shift);
  1181. if (offset < tk->cycle_interval<<shift)
  1182. shift--;
  1183. }
  1184. /* correct the clock when NTP error is too big */
  1185. timekeeping_adjust(tk, offset);
  1186. /*
  1187. * XXX This can be killed once everyone converts
  1188. * to the new update_vsyscall.
  1189. */
  1190. old_vsyscall_fixup(tk);
  1191. /*
  1192. * Finally, make sure that after the rounding
  1193. * xtime_nsec isn't larger than NSEC_PER_SEC
  1194. */
  1195. action = accumulate_nsecs_to_secs(tk);
  1196. write_seqcount_begin(&timekeeper_seq);
  1197. /* Update clock->cycle_last with the new value */
  1198. clock->cycle_last = tk->cycle_last;
  1199. /*
  1200. * Update the real timekeeper.
  1201. *
  1202. * We could avoid this memcpy by switching pointers, but that
  1203. * requires changes to all other timekeeper usage sites as
  1204. * well, i.e. move the timekeeper pointer getter into the
  1205. * spinlocked/seqcount protected sections. And we trade this
  1206. * memcpy under the timekeeper_seq against one before we start
  1207. * updating.
  1208. */
  1209. memcpy(real_tk, tk, sizeof(*tk));
  1210. timekeeping_update(real_tk, action);
  1211. write_seqcount_end(&timekeeper_seq);
  1212. out:
  1213. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1214. }
  1215. /**
  1216. * getboottime - Return the real time of system boot.
  1217. * @ts: pointer to the timespec to be set
  1218. *
  1219. * Returns the wall-time of boot in a timespec.
  1220. *
  1221. * This is based on the wall_to_monotonic offset and the total suspend
  1222. * time. Calls to settimeofday will affect the value returned (which
  1223. * basically means that however wrong your real time clock is at boot time,
  1224. * you get the right time here).
  1225. */
  1226. void getboottime(struct timespec *ts)
  1227. {
  1228. struct timekeeper *tk = &timekeeper;
  1229. struct timespec boottime = {
  1230. .tv_sec = tk->wall_to_monotonic.tv_sec +
  1231. tk->total_sleep_time.tv_sec,
  1232. .tv_nsec = tk->wall_to_monotonic.tv_nsec +
  1233. tk->total_sleep_time.tv_nsec
  1234. };
  1235. set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
  1236. }
  1237. EXPORT_SYMBOL_GPL(getboottime);
  1238. /**
  1239. * get_monotonic_boottime - Returns monotonic time since boot
  1240. * @ts: pointer to the timespec to be set
  1241. *
  1242. * Returns the monotonic time since boot in a timespec.
  1243. *
  1244. * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
  1245. * includes the time spent in suspend.
  1246. */
  1247. void get_monotonic_boottime(struct timespec *ts)
  1248. {
  1249. struct timekeeper *tk = &timekeeper;
  1250. struct timespec tomono, sleep;
  1251. s64 nsec;
  1252. unsigned int seq;
  1253. WARN_ON(timekeeping_suspended);
  1254. do {
  1255. seq = read_seqcount_begin(&timekeeper_seq);
  1256. ts->tv_sec = tk->xtime_sec;
  1257. nsec = timekeeping_get_ns(tk);
  1258. tomono = tk->wall_to_monotonic;
  1259. sleep = tk->total_sleep_time;
  1260. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1261. ts->tv_sec += tomono.tv_sec + sleep.tv_sec;
  1262. ts->tv_nsec = 0;
  1263. timespec_add_ns(ts, nsec + tomono.tv_nsec + sleep.tv_nsec);
  1264. }
  1265. EXPORT_SYMBOL_GPL(get_monotonic_boottime);
  1266. /**
  1267. * ktime_get_boottime - Returns monotonic time since boot in a ktime
  1268. *
  1269. * Returns the monotonic time since boot in a ktime
  1270. *
  1271. * This is similar to CLOCK_MONTONIC/ktime_get, but also
  1272. * includes the time spent in suspend.
  1273. */
  1274. ktime_t ktime_get_boottime(void)
  1275. {
  1276. struct timespec ts;
  1277. get_monotonic_boottime(&ts);
  1278. return timespec_to_ktime(ts);
  1279. }
  1280. EXPORT_SYMBOL_GPL(ktime_get_boottime);
  1281. /**
  1282. * monotonic_to_bootbased - Convert the monotonic time to boot based.
  1283. * @ts: pointer to the timespec to be converted
  1284. */
  1285. void monotonic_to_bootbased(struct timespec *ts)
  1286. {
  1287. struct timekeeper *tk = &timekeeper;
  1288. *ts = timespec_add(*ts, tk->total_sleep_time);
  1289. }
  1290. EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
  1291. unsigned long get_seconds(void)
  1292. {
  1293. struct timekeeper *tk = &timekeeper;
  1294. return tk->xtime_sec;
  1295. }
  1296. EXPORT_SYMBOL(get_seconds);
  1297. struct timespec __current_kernel_time(void)
  1298. {
  1299. struct timekeeper *tk = &timekeeper;
  1300. return tk_xtime(tk);
  1301. }
  1302. struct timespec current_kernel_time(void)
  1303. {
  1304. struct timekeeper *tk = &timekeeper;
  1305. struct timespec now;
  1306. unsigned long seq;
  1307. do {
  1308. seq = read_seqcount_begin(&timekeeper_seq);
  1309. now = tk_xtime(tk);
  1310. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1311. return now;
  1312. }
  1313. EXPORT_SYMBOL(current_kernel_time);
  1314. struct timespec get_monotonic_coarse(void)
  1315. {
  1316. struct timekeeper *tk = &timekeeper;
  1317. struct timespec now, mono;
  1318. unsigned long seq;
  1319. do {
  1320. seq = read_seqcount_begin(&timekeeper_seq);
  1321. now = tk_xtime(tk);
  1322. mono = tk->wall_to_monotonic;
  1323. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1324. set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
  1325. now.tv_nsec + mono.tv_nsec);
  1326. return now;
  1327. }
  1328. /*
  1329. * Must hold jiffies_lock
  1330. */
  1331. void do_timer(unsigned long ticks)
  1332. {
  1333. jiffies_64 += ticks;
  1334. update_wall_time();
  1335. calc_global_load(ticks);
  1336. }
  1337. /**
  1338. * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
  1339. * and sleep offsets.
  1340. * @xtim: pointer to timespec to be set with xtime
  1341. * @wtom: pointer to timespec to be set with wall_to_monotonic
  1342. * @sleep: pointer to timespec to be set with time in suspend
  1343. */
  1344. void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
  1345. struct timespec *wtom, struct timespec *sleep)
  1346. {
  1347. struct timekeeper *tk = &timekeeper;
  1348. unsigned long seq;
  1349. do {
  1350. seq = read_seqcount_begin(&timekeeper_seq);
  1351. *xtim = tk_xtime(tk);
  1352. *wtom = tk->wall_to_monotonic;
  1353. *sleep = tk->total_sleep_time;
  1354. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1355. }
  1356. #ifdef CONFIG_HIGH_RES_TIMERS
  1357. /**
  1358. * ktime_get_update_offsets - hrtimer helper
  1359. * @offs_real: pointer to storage for monotonic -> realtime offset
  1360. * @offs_boot: pointer to storage for monotonic -> boottime offset
  1361. *
  1362. * Returns current monotonic time and updates the offsets
  1363. * Called from hrtimer_interupt() or retrigger_next_event()
  1364. */
  1365. ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot,
  1366. ktime_t *offs_tai)
  1367. {
  1368. struct timekeeper *tk = &timekeeper;
  1369. ktime_t now;
  1370. unsigned int seq;
  1371. u64 secs, nsecs;
  1372. do {
  1373. seq = read_seqcount_begin(&timekeeper_seq);
  1374. secs = tk->xtime_sec;
  1375. nsecs = timekeeping_get_ns(tk);
  1376. *offs_real = tk->offs_real;
  1377. *offs_boot = tk->offs_boot;
  1378. *offs_tai = tk->offs_tai;
  1379. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1380. now = ktime_add_ns(ktime_set(secs, 0), nsecs);
  1381. now = ktime_sub(now, *offs_real);
  1382. return now;
  1383. }
  1384. #endif
  1385. /**
  1386. * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
  1387. */
  1388. ktime_t ktime_get_monotonic_offset(void)
  1389. {
  1390. struct timekeeper *tk = &timekeeper;
  1391. unsigned long seq;
  1392. struct timespec wtom;
  1393. do {
  1394. seq = read_seqcount_begin(&timekeeper_seq);
  1395. wtom = tk->wall_to_monotonic;
  1396. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1397. return timespec_to_ktime(wtom);
  1398. }
  1399. EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
  1400. /**
  1401. * do_adjtimex() - Accessor function to NTP __do_adjtimex function
  1402. */
  1403. int do_adjtimex(struct timex *txc)
  1404. {
  1405. struct timekeeper *tk = &timekeeper;
  1406. unsigned long flags;
  1407. struct timespec ts;
  1408. s32 orig_tai, tai;
  1409. int ret;
  1410. /* Validate the data before disabling interrupts */
  1411. ret = ntp_validate_timex(txc);
  1412. if (ret)
  1413. return ret;
  1414. if (txc->modes & ADJ_SETOFFSET) {
  1415. struct timespec delta;
  1416. delta.tv_sec = txc->time.tv_sec;
  1417. delta.tv_nsec = txc->time.tv_usec;
  1418. if (!(txc->modes & ADJ_NANO))
  1419. delta.tv_nsec *= 1000;
  1420. ret = timekeeping_inject_offset(&delta);
  1421. if (ret)
  1422. return ret;
  1423. }
  1424. getnstimeofday(&ts);
  1425. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1426. write_seqcount_begin(&timekeeper_seq);
  1427. orig_tai = tai = tk->tai_offset;
  1428. ret = __do_adjtimex(txc, &ts, &tai);
  1429. if (tai != orig_tai) {
  1430. __timekeeping_set_tai_offset(tk, tai);
  1431. update_pvclock_gtod(tk, true);
  1432. clock_was_set_delayed();
  1433. }
  1434. write_seqcount_end(&timekeeper_seq);
  1435. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1436. ntp_notify_cmos_timer();
  1437. return ret;
  1438. }
  1439. #ifdef CONFIG_NTP_PPS
  1440. /**
  1441. * hardpps() - Accessor function to NTP __hardpps function
  1442. */
  1443. void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
  1444. {
  1445. unsigned long flags;
  1446. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1447. write_seqcount_begin(&timekeeper_seq);
  1448. __hardpps(phase_ts, raw_ts);
  1449. write_seqcount_end(&timekeeper_seq);
  1450. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1451. }
  1452. EXPORT_SYMBOL(hardpps);
  1453. #endif
  1454. /**
  1455. * xtime_update() - advances the timekeeping infrastructure
  1456. * @ticks: number of ticks, that have elapsed since the last call.
  1457. *
  1458. * Must be called with interrupts disabled.
  1459. */
  1460. void xtime_update(unsigned long ticks)
  1461. {
  1462. write_seqlock(&jiffies_lock);
  1463. do_timer(ticks);
  1464. write_sequnlock(&jiffies_lock);
  1465. }