timekeeping.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  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(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
  700. "sleep delta value!\n");
  701. return;
  702. }
  703. tk_xtime_add(tk, delta);
  704. tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *delta));
  705. tk_set_sleep_time(tk, timespec_add(tk->total_sleep_time, *delta));
  706. tk_debug_account_sleep_time(delta);
  707. }
  708. /**
  709. * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
  710. * @delta: pointer to a timespec delta value
  711. *
  712. * This hook is for architectures that cannot support read_persistent_clock
  713. * because their RTC/persistent clock is only accessible when irqs are enabled.
  714. *
  715. * This function should only be called by rtc_resume(), and allows
  716. * a suspend offset to be injected into the timekeeping values.
  717. */
  718. void timekeeping_inject_sleeptime(struct timespec *delta)
  719. {
  720. struct timekeeper *tk = &timekeeper;
  721. unsigned long flags;
  722. /*
  723. * Make sure we don't set the clock twice, as timekeeping_resume()
  724. * already did it
  725. */
  726. if (has_persistent_clock())
  727. return;
  728. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  729. write_seqcount_begin(&timekeeper_seq);
  730. timekeeping_forward_now(tk);
  731. __timekeeping_inject_sleeptime(tk, delta);
  732. timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
  733. write_seqcount_end(&timekeeper_seq);
  734. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  735. /* signal hrtimers about time change */
  736. clock_was_set();
  737. }
  738. /**
  739. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  740. *
  741. * This is for the generic clocksource timekeeping.
  742. * xtime/wall_to_monotonic/jiffies/etc are
  743. * still managed by arch specific suspend/resume code.
  744. */
  745. static void timekeeping_resume(void)
  746. {
  747. struct timekeeper *tk = &timekeeper;
  748. struct clocksource *clock = tk->clock;
  749. unsigned long flags;
  750. struct timespec ts_new, ts_delta;
  751. cycle_t cycle_now, cycle_delta;
  752. bool suspendtime_found = false;
  753. read_persistent_clock(&ts_new);
  754. clockevents_resume();
  755. clocksource_resume();
  756. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  757. write_seqcount_begin(&timekeeper_seq);
  758. /*
  759. * After system resumes, we need to calculate the suspended time and
  760. * compensate it for the OS time. There are 3 sources that could be
  761. * used: Nonstop clocksource during suspend, persistent clock and rtc
  762. * device.
  763. *
  764. * One specific platform may have 1 or 2 or all of them, and the
  765. * preference will be:
  766. * suspend-nonstop clocksource -> persistent clock -> rtc
  767. * The less preferred source will only be tried if there is no better
  768. * usable source. The rtc part is handled separately in rtc core code.
  769. */
  770. cycle_now = clock->read(clock);
  771. if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
  772. cycle_now > clock->cycle_last) {
  773. u64 num, max = ULLONG_MAX;
  774. u32 mult = clock->mult;
  775. u32 shift = clock->shift;
  776. s64 nsec = 0;
  777. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  778. /*
  779. * "cycle_delta * mutl" may cause 64 bits overflow, if the
  780. * suspended time is too long. In that case we need do the
  781. * 64 bits math carefully
  782. */
  783. do_div(max, mult);
  784. if (cycle_delta > max) {
  785. num = div64_u64(cycle_delta, max);
  786. nsec = (((u64) max * mult) >> shift) * num;
  787. cycle_delta -= num * max;
  788. }
  789. nsec += ((u64) cycle_delta * mult) >> shift;
  790. ts_delta = ns_to_timespec(nsec);
  791. suspendtime_found = true;
  792. } else if (timespec_compare(&ts_new, &timekeeping_suspend_time) > 0) {
  793. ts_delta = timespec_sub(ts_new, timekeeping_suspend_time);
  794. suspendtime_found = true;
  795. }
  796. if (suspendtime_found)
  797. __timekeeping_inject_sleeptime(tk, &ts_delta);
  798. /* Re-base the last cycle value */
  799. tk->cycle_last = clock->cycle_last = cycle_now;
  800. tk->ntp_error = 0;
  801. timekeeping_suspended = 0;
  802. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  803. write_seqcount_end(&timekeeper_seq);
  804. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  805. touch_softlockup_watchdog();
  806. clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
  807. /* Resume hrtimers */
  808. hrtimers_resume();
  809. }
  810. static int timekeeping_suspend(void)
  811. {
  812. struct timekeeper *tk = &timekeeper;
  813. unsigned long flags;
  814. struct timespec delta, delta_delta;
  815. static struct timespec old_delta;
  816. read_persistent_clock(&timekeeping_suspend_time);
  817. /*
  818. * On some systems the persistent_clock can not be detected at
  819. * timekeeping_init by its return value, so if we see a valid
  820. * value returned, update the persistent_clock_exists flag.
  821. */
  822. if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
  823. persistent_clock_exist = true;
  824. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  825. write_seqcount_begin(&timekeeper_seq);
  826. timekeeping_forward_now(tk);
  827. timekeeping_suspended = 1;
  828. /*
  829. * To avoid drift caused by repeated suspend/resumes,
  830. * which each can add ~1 second drift error,
  831. * try to compensate so the difference in system time
  832. * and persistent_clock time stays close to constant.
  833. */
  834. delta = timespec_sub(tk_xtime(tk), timekeeping_suspend_time);
  835. delta_delta = timespec_sub(delta, old_delta);
  836. if (abs(delta_delta.tv_sec) >= 2) {
  837. /*
  838. * if delta_delta is too large, assume time correction
  839. * has occured and set old_delta to the current delta.
  840. */
  841. old_delta = delta;
  842. } else {
  843. /* Otherwise try to adjust old_system to compensate */
  844. timekeeping_suspend_time =
  845. timespec_add(timekeeping_suspend_time, delta_delta);
  846. }
  847. timekeeping_update(tk, TK_MIRROR);
  848. write_seqcount_end(&timekeeper_seq);
  849. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  850. clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
  851. clocksource_suspend();
  852. clockevents_suspend();
  853. return 0;
  854. }
  855. /* sysfs resume/suspend bits for timekeeping */
  856. static struct syscore_ops timekeeping_syscore_ops = {
  857. .resume = timekeeping_resume,
  858. .suspend = timekeeping_suspend,
  859. };
  860. static int __init timekeeping_init_ops(void)
  861. {
  862. register_syscore_ops(&timekeeping_syscore_ops);
  863. return 0;
  864. }
  865. device_initcall(timekeeping_init_ops);
  866. /*
  867. * If the error is already larger, we look ahead even further
  868. * to compensate for late or lost adjustments.
  869. */
  870. static __always_inline int timekeeping_bigadjust(struct timekeeper *tk,
  871. s64 error, s64 *interval,
  872. s64 *offset)
  873. {
  874. s64 tick_error, i;
  875. u32 look_ahead, adj;
  876. s32 error2, mult;
  877. /*
  878. * Use the current error value to determine how much to look ahead.
  879. * The larger the error the slower we adjust for it to avoid problems
  880. * with losing too many ticks, otherwise we would overadjust and
  881. * produce an even larger error. The smaller the adjustment the
  882. * faster we try to adjust for it, as lost ticks can do less harm
  883. * here. This is tuned so that an error of about 1 msec is adjusted
  884. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  885. */
  886. error2 = tk->ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
  887. error2 = abs(error2);
  888. for (look_ahead = 0; error2 > 0; look_ahead++)
  889. error2 >>= 2;
  890. /*
  891. * Now calculate the error in (1 << look_ahead) ticks, but first
  892. * remove the single look ahead already included in the error.
  893. */
  894. tick_error = ntp_tick_length() >> (tk->ntp_error_shift + 1);
  895. tick_error -= tk->xtime_interval >> 1;
  896. error = ((error - tick_error) >> look_ahead) + tick_error;
  897. /* Finally calculate the adjustment shift value. */
  898. i = *interval;
  899. mult = 1;
  900. if (error < 0) {
  901. error = -error;
  902. *interval = -*interval;
  903. *offset = -*offset;
  904. mult = -1;
  905. }
  906. for (adj = 0; error > i; adj++)
  907. error >>= 1;
  908. *interval <<= adj;
  909. *offset <<= adj;
  910. return mult << adj;
  911. }
  912. /*
  913. * Adjust the multiplier to reduce the error value,
  914. * this is optimized for the most common adjustments of -1,0,1,
  915. * for other values we can do a bit more work.
  916. */
  917. static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
  918. {
  919. s64 error, interval = tk->cycle_interval;
  920. int adj;
  921. /*
  922. * The point of this is to check if the error is greater than half
  923. * an interval.
  924. *
  925. * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
  926. *
  927. * Note we subtract one in the shift, so that error is really error*2.
  928. * This "saves" dividing(shifting) interval twice, but keeps the
  929. * (error > interval) comparison as still measuring if error is
  930. * larger than half an interval.
  931. *
  932. * Note: It does not "save" on aggravation when reading the code.
  933. */
  934. error = tk->ntp_error >> (tk->ntp_error_shift - 1);
  935. if (error > interval) {
  936. /*
  937. * We now divide error by 4(via shift), which checks if
  938. * the error is greater than twice the interval.
  939. * If it is greater, we need a bigadjust, if its smaller,
  940. * we can adjust by 1.
  941. */
  942. error >>= 2;
  943. if (likely(error <= interval))
  944. adj = 1;
  945. else
  946. adj = timekeeping_bigadjust(tk, error, &interval, &offset);
  947. } else {
  948. if (error < -interval) {
  949. /* See comment above, this is just switched for the negative */
  950. error >>= 2;
  951. if (likely(error >= -interval)) {
  952. adj = -1;
  953. interval = -interval;
  954. offset = -offset;
  955. } else {
  956. adj = timekeeping_bigadjust(tk, error, &interval, &offset);
  957. }
  958. } else {
  959. goto out_adjust;
  960. }
  961. }
  962. if (unlikely(tk->clock->maxadj &&
  963. (tk->mult + adj > tk->clock->mult + tk->clock->maxadj))) {
  964. printk_once(KERN_WARNING
  965. "Adjusting %s more than 11%% (%ld vs %ld)\n",
  966. tk->clock->name, (long)tk->mult + adj,
  967. (long)tk->clock->mult + tk->clock->maxadj);
  968. }
  969. /*
  970. * So the following can be confusing.
  971. *
  972. * To keep things simple, lets assume adj == 1 for now.
  973. *
  974. * When adj != 1, remember that the interval and offset values
  975. * have been appropriately scaled so the math is the same.
  976. *
  977. * The basic idea here is that we're increasing the multiplier
  978. * by one, this causes the xtime_interval to be incremented by
  979. * one cycle_interval. This is because:
  980. * xtime_interval = cycle_interval * mult
  981. * So if mult is being incremented by one:
  982. * xtime_interval = cycle_interval * (mult + 1)
  983. * Its the same as:
  984. * xtime_interval = (cycle_interval * mult) + cycle_interval
  985. * Which can be shortened to:
  986. * xtime_interval += cycle_interval
  987. *
  988. * So offset stores the non-accumulated cycles. Thus the current
  989. * time (in shifted nanoseconds) is:
  990. * now = (offset * adj) + xtime_nsec
  991. * Now, even though we're adjusting the clock frequency, we have
  992. * to keep time consistent. In other words, we can't jump back
  993. * in time, and we also want to avoid jumping forward in time.
  994. *
  995. * So given the same offset value, we need the time to be the same
  996. * both before and after the freq adjustment.
  997. * now = (offset * adj_1) + xtime_nsec_1
  998. * now = (offset * adj_2) + xtime_nsec_2
  999. * So:
  1000. * (offset * adj_1) + xtime_nsec_1 =
  1001. * (offset * adj_2) + xtime_nsec_2
  1002. * And we know:
  1003. * adj_2 = adj_1 + 1
  1004. * So:
  1005. * (offset * adj_1) + xtime_nsec_1 =
  1006. * (offset * (adj_1+1)) + xtime_nsec_2
  1007. * (offset * adj_1) + xtime_nsec_1 =
  1008. * (offset * adj_1) + offset + xtime_nsec_2
  1009. * Canceling the sides:
  1010. * xtime_nsec_1 = offset + xtime_nsec_2
  1011. * Which gives us:
  1012. * xtime_nsec_2 = xtime_nsec_1 - offset
  1013. * Which simplfies to:
  1014. * xtime_nsec -= offset
  1015. *
  1016. * XXX - TODO: Doc ntp_error calculation.
  1017. */
  1018. tk->mult += adj;
  1019. tk->xtime_interval += interval;
  1020. tk->xtime_nsec -= offset;
  1021. tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
  1022. out_adjust:
  1023. /*
  1024. * It may be possible that when we entered this function, xtime_nsec
  1025. * was very small. Further, if we're slightly speeding the clocksource
  1026. * in the code above, its possible the required corrective factor to
  1027. * xtime_nsec could cause it to underflow.
  1028. *
  1029. * Now, since we already accumulated the second, cannot simply roll
  1030. * the accumulated second back, since the NTP subsystem has been
  1031. * notified via second_overflow. So instead we push xtime_nsec forward
  1032. * by the amount we underflowed, and add that amount into the error.
  1033. *
  1034. * We'll correct this error next time through this function, when
  1035. * xtime_nsec is not as small.
  1036. */
  1037. if (unlikely((s64)tk->xtime_nsec < 0)) {
  1038. s64 neg = -(s64)tk->xtime_nsec;
  1039. tk->xtime_nsec = 0;
  1040. tk->ntp_error += neg << tk->ntp_error_shift;
  1041. }
  1042. }
  1043. /**
  1044. * accumulate_nsecs_to_secs - Accumulates nsecs into secs
  1045. *
  1046. * Helper function that accumulates a the nsecs greater then a second
  1047. * from the xtime_nsec field to the xtime_secs field.
  1048. * It also calls into the NTP code to handle leapsecond processing.
  1049. *
  1050. */
  1051. static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
  1052. {
  1053. u64 nsecps = (u64)NSEC_PER_SEC << tk->shift;
  1054. unsigned int clock_set = 0;
  1055. while (tk->xtime_nsec >= nsecps) {
  1056. int leap;
  1057. tk->xtime_nsec -= nsecps;
  1058. tk->xtime_sec++;
  1059. /* Figure out if its a leap sec and apply if needed */
  1060. leap = second_overflow(tk->xtime_sec);
  1061. if (unlikely(leap)) {
  1062. struct timespec ts;
  1063. tk->xtime_sec += leap;
  1064. ts.tv_sec = leap;
  1065. ts.tv_nsec = 0;
  1066. tk_set_wall_to_mono(tk,
  1067. timespec_sub(tk->wall_to_monotonic, ts));
  1068. __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
  1069. clock_set = TK_CLOCK_WAS_SET;
  1070. }
  1071. }
  1072. return clock_set;
  1073. }
  1074. /**
  1075. * logarithmic_accumulation - shifted accumulation of cycles
  1076. *
  1077. * This functions accumulates a shifted interval of cycles into
  1078. * into a shifted interval nanoseconds. Allows for O(log) accumulation
  1079. * loop.
  1080. *
  1081. * Returns the unconsumed cycles.
  1082. */
  1083. static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
  1084. u32 shift,
  1085. unsigned int *clock_set)
  1086. {
  1087. cycle_t interval = tk->cycle_interval << shift;
  1088. u64 raw_nsecs;
  1089. /* If the offset is smaller then a shifted interval, do nothing */
  1090. if (offset < interval)
  1091. return offset;
  1092. /* Accumulate one shifted interval */
  1093. offset -= interval;
  1094. tk->cycle_last += interval;
  1095. tk->xtime_nsec += tk->xtime_interval << shift;
  1096. *clock_set |= accumulate_nsecs_to_secs(tk);
  1097. /* Accumulate raw time */
  1098. raw_nsecs = (u64)tk->raw_interval << shift;
  1099. raw_nsecs += tk->raw_time.tv_nsec;
  1100. if (raw_nsecs >= NSEC_PER_SEC) {
  1101. u64 raw_secs = raw_nsecs;
  1102. raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
  1103. tk->raw_time.tv_sec += raw_secs;
  1104. }
  1105. tk->raw_time.tv_nsec = raw_nsecs;
  1106. /* Accumulate error between NTP and clock interval */
  1107. tk->ntp_error += ntp_tick_length() << shift;
  1108. tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
  1109. (tk->ntp_error_shift + shift);
  1110. return offset;
  1111. }
  1112. #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
  1113. static inline void old_vsyscall_fixup(struct timekeeper *tk)
  1114. {
  1115. s64 remainder;
  1116. /*
  1117. * Store only full nanoseconds into xtime_nsec after rounding
  1118. * it up and add the remainder to the error difference.
  1119. * XXX - This is necessary to avoid small 1ns inconsistnecies caused
  1120. * by truncating the remainder in vsyscalls. However, it causes
  1121. * additional work to be done in timekeeping_adjust(). Once
  1122. * the vsyscall implementations are converted to use xtime_nsec
  1123. * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
  1124. * users are removed, this can be killed.
  1125. */
  1126. remainder = tk->xtime_nsec & ((1ULL << tk->shift) - 1);
  1127. tk->xtime_nsec -= remainder;
  1128. tk->xtime_nsec += 1ULL << tk->shift;
  1129. tk->ntp_error += remainder << tk->ntp_error_shift;
  1130. tk->ntp_error -= (1ULL << tk->shift) << tk->ntp_error_shift;
  1131. }
  1132. #else
  1133. #define old_vsyscall_fixup(tk)
  1134. #endif
  1135. /**
  1136. * update_wall_time - Uses the current clocksource to increment the wall time
  1137. *
  1138. */
  1139. void update_wall_time(void)
  1140. {
  1141. struct clocksource *clock;
  1142. struct timekeeper *real_tk = &timekeeper;
  1143. struct timekeeper *tk = &shadow_timekeeper;
  1144. cycle_t offset;
  1145. int shift = 0, maxshift;
  1146. unsigned int clock_set = 0;
  1147. unsigned long flags;
  1148. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1149. /* Make sure we're fully resumed: */
  1150. if (unlikely(timekeeping_suspended))
  1151. goto out;
  1152. clock = real_tk->clock;
  1153. #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
  1154. offset = real_tk->cycle_interval;
  1155. #else
  1156. offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
  1157. #endif
  1158. /* Check if there's really nothing to do */
  1159. if (offset < real_tk->cycle_interval)
  1160. goto out;
  1161. /*
  1162. * With NO_HZ we may have to accumulate many cycle_intervals
  1163. * (think "ticks") worth of time at once. To do this efficiently,
  1164. * we calculate the largest doubling multiple of cycle_intervals
  1165. * that is smaller than the offset. We then accumulate that
  1166. * chunk in one go, and then try to consume the next smaller
  1167. * doubled multiple.
  1168. */
  1169. shift = ilog2(offset) - ilog2(tk->cycle_interval);
  1170. shift = max(0, shift);
  1171. /* Bound shift to one less than what overflows tick_length */
  1172. maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
  1173. shift = min(shift, maxshift);
  1174. while (offset >= tk->cycle_interval) {
  1175. offset = logarithmic_accumulation(tk, offset, shift,
  1176. &clock_set);
  1177. if (offset < tk->cycle_interval<<shift)
  1178. shift--;
  1179. }
  1180. /* correct the clock when NTP error is too big */
  1181. timekeeping_adjust(tk, offset);
  1182. /*
  1183. * XXX This can be killed once everyone converts
  1184. * to the new update_vsyscall.
  1185. */
  1186. old_vsyscall_fixup(tk);
  1187. /*
  1188. * Finally, make sure that after the rounding
  1189. * xtime_nsec isn't larger than NSEC_PER_SEC
  1190. */
  1191. clock_set |= accumulate_nsecs_to_secs(tk);
  1192. write_seqcount_begin(&timekeeper_seq);
  1193. /* Update clock->cycle_last with the new value */
  1194. clock->cycle_last = tk->cycle_last;
  1195. /*
  1196. * Update the real timekeeper.
  1197. *
  1198. * We could avoid this memcpy by switching pointers, but that
  1199. * requires changes to all other timekeeper usage sites as
  1200. * well, i.e. move the timekeeper pointer getter into the
  1201. * spinlocked/seqcount protected sections. And we trade this
  1202. * memcpy under the timekeeper_seq against one before we start
  1203. * updating.
  1204. */
  1205. memcpy(real_tk, tk, sizeof(*tk));
  1206. timekeeping_update(real_tk, clock_set);
  1207. write_seqcount_end(&timekeeper_seq);
  1208. out:
  1209. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1210. if (clock_set)
  1211. /* Have to call _delayed version, since in irq context*/
  1212. clock_was_set_delayed();
  1213. }
  1214. /**
  1215. * getboottime - Return the real time of system boot.
  1216. * @ts: pointer to the timespec to be set
  1217. *
  1218. * Returns the wall-time of boot in a timespec.
  1219. *
  1220. * This is based on the wall_to_monotonic offset and the total suspend
  1221. * time. Calls to settimeofday will affect the value returned (which
  1222. * basically means that however wrong your real time clock is at boot time,
  1223. * you get the right time here).
  1224. */
  1225. void getboottime(struct timespec *ts)
  1226. {
  1227. struct timekeeper *tk = &timekeeper;
  1228. struct timespec boottime = {
  1229. .tv_sec = tk->wall_to_monotonic.tv_sec +
  1230. tk->total_sleep_time.tv_sec,
  1231. .tv_nsec = tk->wall_to_monotonic.tv_nsec +
  1232. tk->total_sleep_time.tv_nsec
  1233. };
  1234. set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
  1235. }
  1236. EXPORT_SYMBOL_GPL(getboottime);
  1237. /**
  1238. * get_monotonic_boottime - Returns monotonic time since boot
  1239. * @ts: pointer to the timespec to be set
  1240. *
  1241. * Returns the monotonic time since boot in a timespec.
  1242. *
  1243. * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
  1244. * includes the time spent in suspend.
  1245. */
  1246. void get_monotonic_boottime(struct timespec *ts)
  1247. {
  1248. struct timekeeper *tk = &timekeeper;
  1249. struct timespec tomono, sleep;
  1250. s64 nsec;
  1251. unsigned int seq;
  1252. WARN_ON(timekeeping_suspended);
  1253. do {
  1254. seq = read_seqcount_begin(&timekeeper_seq);
  1255. ts->tv_sec = tk->xtime_sec;
  1256. nsec = timekeeping_get_ns(tk);
  1257. tomono = tk->wall_to_monotonic;
  1258. sleep = tk->total_sleep_time;
  1259. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1260. ts->tv_sec += tomono.tv_sec + sleep.tv_sec;
  1261. ts->tv_nsec = 0;
  1262. timespec_add_ns(ts, nsec + tomono.tv_nsec + sleep.tv_nsec);
  1263. }
  1264. EXPORT_SYMBOL_GPL(get_monotonic_boottime);
  1265. /**
  1266. * ktime_get_boottime - Returns monotonic time since boot in a ktime
  1267. *
  1268. * Returns the monotonic time since boot in a ktime
  1269. *
  1270. * This is similar to CLOCK_MONTONIC/ktime_get, but also
  1271. * includes the time spent in suspend.
  1272. */
  1273. ktime_t ktime_get_boottime(void)
  1274. {
  1275. struct timespec ts;
  1276. get_monotonic_boottime(&ts);
  1277. return timespec_to_ktime(ts);
  1278. }
  1279. EXPORT_SYMBOL_GPL(ktime_get_boottime);
  1280. /**
  1281. * monotonic_to_bootbased - Convert the monotonic time to boot based.
  1282. * @ts: pointer to the timespec to be converted
  1283. */
  1284. void monotonic_to_bootbased(struct timespec *ts)
  1285. {
  1286. struct timekeeper *tk = &timekeeper;
  1287. *ts = timespec_add(*ts, tk->total_sleep_time);
  1288. }
  1289. EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
  1290. unsigned long get_seconds(void)
  1291. {
  1292. struct timekeeper *tk = &timekeeper;
  1293. return tk->xtime_sec;
  1294. }
  1295. EXPORT_SYMBOL(get_seconds);
  1296. struct timespec __current_kernel_time(void)
  1297. {
  1298. struct timekeeper *tk = &timekeeper;
  1299. return tk_xtime(tk);
  1300. }
  1301. struct timespec current_kernel_time(void)
  1302. {
  1303. struct timekeeper *tk = &timekeeper;
  1304. struct timespec now;
  1305. unsigned long seq;
  1306. do {
  1307. seq = read_seqcount_begin(&timekeeper_seq);
  1308. now = tk_xtime(tk);
  1309. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1310. return now;
  1311. }
  1312. EXPORT_SYMBOL(current_kernel_time);
  1313. struct timespec get_monotonic_coarse(void)
  1314. {
  1315. struct timekeeper *tk = &timekeeper;
  1316. struct timespec now, mono;
  1317. unsigned long seq;
  1318. do {
  1319. seq = read_seqcount_begin(&timekeeper_seq);
  1320. now = tk_xtime(tk);
  1321. mono = tk->wall_to_monotonic;
  1322. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1323. set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
  1324. now.tv_nsec + mono.tv_nsec);
  1325. return now;
  1326. }
  1327. /*
  1328. * Must hold jiffies_lock
  1329. */
  1330. void do_timer(unsigned long ticks)
  1331. {
  1332. jiffies_64 += ticks;
  1333. calc_global_load(ticks);
  1334. }
  1335. /**
  1336. * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
  1337. * and sleep offsets.
  1338. * @xtim: pointer to timespec to be set with xtime
  1339. * @wtom: pointer to timespec to be set with wall_to_monotonic
  1340. * @sleep: pointer to timespec to be set with time in suspend
  1341. */
  1342. void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
  1343. struct timespec *wtom, struct timespec *sleep)
  1344. {
  1345. struct timekeeper *tk = &timekeeper;
  1346. unsigned long seq;
  1347. do {
  1348. seq = read_seqcount_begin(&timekeeper_seq);
  1349. *xtim = tk_xtime(tk);
  1350. *wtom = tk->wall_to_monotonic;
  1351. *sleep = tk->total_sleep_time;
  1352. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1353. }
  1354. #ifdef CONFIG_HIGH_RES_TIMERS
  1355. /**
  1356. * ktime_get_update_offsets - hrtimer helper
  1357. * @offs_real: pointer to storage for monotonic -> realtime offset
  1358. * @offs_boot: pointer to storage for monotonic -> boottime offset
  1359. * @offs_tai: pointer to storage for monotonic -> clock tai offset
  1360. *
  1361. * Returns current monotonic time and updates the offsets
  1362. * Called from hrtimer_interrupt() or retrigger_next_event()
  1363. */
  1364. ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot,
  1365. ktime_t *offs_tai)
  1366. {
  1367. struct timekeeper *tk = &timekeeper;
  1368. ktime_t now;
  1369. unsigned int seq;
  1370. u64 secs, nsecs;
  1371. do {
  1372. seq = read_seqcount_begin(&timekeeper_seq);
  1373. secs = tk->xtime_sec;
  1374. nsecs = timekeeping_get_ns(tk);
  1375. *offs_real = tk->offs_real;
  1376. *offs_boot = tk->offs_boot;
  1377. *offs_tai = tk->offs_tai;
  1378. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1379. now = ktime_add_ns(ktime_set(secs, 0), nsecs);
  1380. now = ktime_sub(now, *offs_real);
  1381. return now;
  1382. }
  1383. #endif
  1384. /**
  1385. * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
  1386. */
  1387. ktime_t ktime_get_monotonic_offset(void)
  1388. {
  1389. struct timekeeper *tk = &timekeeper;
  1390. unsigned long seq;
  1391. struct timespec wtom;
  1392. do {
  1393. seq = read_seqcount_begin(&timekeeper_seq);
  1394. wtom = tk->wall_to_monotonic;
  1395. } while (read_seqcount_retry(&timekeeper_seq, seq));
  1396. return timespec_to_ktime(wtom);
  1397. }
  1398. EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
  1399. /**
  1400. * do_adjtimex() - Accessor function to NTP __do_adjtimex function
  1401. */
  1402. int do_adjtimex(struct timex *txc)
  1403. {
  1404. struct timekeeper *tk = &timekeeper;
  1405. unsigned long flags;
  1406. struct timespec ts;
  1407. s32 orig_tai, tai;
  1408. int ret;
  1409. /* Validate the data before disabling interrupts */
  1410. ret = ntp_validate_timex(txc);
  1411. if (ret)
  1412. return ret;
  1413. if (txc->modes & ADJ_SETOFFSET) {
  1414. struct timespec delta;
  1415. delta.tv_sec = txc->time.tv_sec;
  1416. delta.tv_nsec = txc->time.tv_usec;
  1417. if (!(txc->modes & ADJ_NANO))
  1418. delta.tv_nsec *= 1000;
  1419. ret = timekeeping_inject_offset(&delta);
  1420. if (ret)
  1421. return ret;
  1422. }
  1423. getnstimeofday(&ts);
  1424. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1425. write_seqcount_begin(&timekeeper_seq);
  1426. orig_tai = tai = tk->tai_offset;
  1427. ret = __do_adjtimex(txc, &ts, &tai);
  1428. if (tai != orig_tai) {
  1429. __timekeeping_set_tai_offset(tk, tai);
  1430. timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
  1431. }
  1432. write_seqcount_end(&timekeeper_seq);
  1433. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1434. if (tai != orig_tai)
  1435. clock_was_set();
  1436. ntp_notify_cmos_timer();
  1437. return ret;
  1438. }
  1439. #ifdef CONFIG_NTP_PPS
  1440. /**
  1441. * hardpps() - Accessor function to NTP __hardpps function
  1442. */
  1443. void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
  1444. {
  1445. unsigned long flags;
  1446. raw_spin_lock_irqsave(&timekeeper_lock, flags);
  1447. write_seqcount_begin(&timekeeper_seq);
  1448. __hardpps(phase_ts, raw_ts);
  1449. write_seqcount_end(&timekeeper_seq);
  1450. raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
  1451. }
  1452. EXPORT_SYMBOL(hardpps);
  1453. #endif
  1454. /**
  1455. * xtime_update() - advances the timekeeping infrastructure
  1456. * @ticks: number of ticks, that have elapsed since the last call.
  1457. *
  1458. * Must be called with interrupts disabled.
  1459. */
  1460. void xtime_update(unsigned long ticks)
  1461. {
  1462. write_seqlock(&jiffies_lock);
  1463. do_timer(ticks);
  1464. write_sequnlock(&jiffies_lock);
  1465. update_wall_time();
  1466. }