timekeeping.c 44 KB

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