timekeeping.c 46 KB

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