timekeeping.c 44 KB

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