timekeeping.c 45 KB

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