time.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  1. /*
  2. * Common time routines among all ppc machines.
  3. *
  4. * Written by Cort Dougan (cort@cs.nmt.edu) to merge
  5. * Paul Mackerras' version and mine for PReP and Pmac.
  6. * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
  7. * Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
  8. *
  9. * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
  10. * to make clock more stable (2.4.0-test5). The only thing
  11. * that this code assumes is that the timebases have been synchronized
  12. * by firmware on SMP and are never stopped (never do sleep
  13. * on SMP then, nap and doze are OK).
  14. *
  15. * Speeded up do_gettimeofday by getting rid of references to
  16. * xtime (which required locks for consistency). (mikejc@us.ibm.com)
  17. *
  18. * TODO (not necessarily in this file):
  19. * - improve precision and reproducibility of timebase frequency
  20. * measurement at boot time.
  21. * - for astronomical applications: add a new function to get
  22. * non ambiguous timestamps even around leap seconds. This needs
  23. * a new timestamp format and a good name.
  24. *
  25. * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
  26. * "A Kernel Model for Precision Timekeeping" by Dave Mills
  27. *
  28. * This program is free software; you can redistribute it and/or
  29. * modify it under the terms of the GNU General Public License
  30. * as published by the Free Software Foundation; either version
  31. * 2 of the License, or (at your option) any later version.
  32. */
  33. #include <linux/errno.h>
  34. #include <linux/export.h>
  35. #include <linux/sched.h>
  36. #include <linux/sched/clock.h>
  37. #include <linux/kernel.h>
  38. #include <linux/param.h>
  39. #include <linux/string.h>
  40. #include <linux/mm.h>
  41. #include <linux/interrupt.h>
  42. #include <linux/timex.h>
  43. #include <linux/kernel_stat.h>
  44. #include <linux/time.h>
  45. #include <linux/clockchips.h>
  46. #include <linux/init.h>
  47. #include <linux/profile.h>
  48. #include <linux/cpu.h>
  49. #include <linux/security.h>
  50. #include <linux/percpu.h>
  51. #include <linux/rtc.h>
  52. #include <linux/jiffies.h>
  53. #include <linux/posix-timers.h>
  54. #include <linux/irq.h>
  55. #include <linux/delay.h>
  56. #include <linux/irq_work.h>
  57. #include <linux/clk-provider.h>
  58. #include <linux/suspend.h>
  59. #include <linux/rtc.h>
  60. #include <linux/sched/cputime.h>
  61. #include <linux/processor.h>
  62. #include <asm/trace.h>
  63. #include <asm/io.h>
  64. #include <asm/nvram.h>
  65. #include <asm/cache.h>
  66. #include <asm/machdep.h>
  67. #include <linux/uaccess.h>
  68. #include <asm/time.h>
  69. #include <asm/prom.h>
  70. #include <asm/irq.h>
  71. #include <asm/div64.h>
  72. #include <asm/smp.h>
  73. #include <asm/vdso_datapage.h>
  74. #include <asm/firmware.h>
  75. #include <asm/asm-prototypes.h>
  76. /* powerpc clocksource/clockevent code */
  77. #include <linux/clockchips.h>
  78. #include <linux/timekeeper_internal.h>
  79. static u64 rtc_read(struct clocksource *);
  80. static struct clocksource clocksource_rtc = {
  81. .name = "rtc",
  82. .rating = 400,
  83. .flags = CLOCK_SOURCE_IS_CONTINUOUS,
  84. .mask = CLOCKSOURCE_MASK(64),
  85. .read = rtc_read,
  86. };
  87. static u64 timebase_read(struct clocksource *);
  88. static struct clocksource clocksource_timebase = {
  89. .name = "timebase",
  90. .rating = 400,
  91. .flags = CLOCK_SOURCE_IS_CONTINUOUS,
  92. .mask = CLOCKSOURCE_MASK(64),
  93. .read = timebase_read,
  94. };
  95. #define DECREMENTER_DEFAULT_MAX 0x7FFFFFFF
  96. u64 decrementer_max = DECREMENTER_DEFAULT_MAX;
  97. static int decrementer_set_next_event(unsigned long evt,
  98. struct clock_event_device *dev);
  99. static int decrementer_shutdown(struct clock_event_device *evt);
  100. struct clock_event_device decrementer_clockevent = {
  101. .name = "decrementer",
  102. .rating = 200,
  103. .irq = 0,
  104. .set_next_event = decrementer_set_next_event,
  105. .set_state_oneshot_stopped = decrementer_shutdown,
  106. .set_state_shutdown = decrementer_shutdown,
  107. .tick_resume = decrementer_shutdown,
  108. .features = CLOCK_EVT_FEAT_ONESHOT |
  109. CLOCK_EVT_FEAT_C3STOP,
  110. };
  111. EXPORT_SYMBOL(decrementer_clockevent);
  112. DEFINE_PER_CPU(u64, decrementers_next_tb);
  113. static DEFINE_PER_CPU(struct clock_event_device, decrementers);
  114. #define XSEC_PER_SEC (1024*1024)
  115. #ifdef CONFIG_PPC64
  116. #define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
  117. #else
  118. /* compute ((xsec << 12) * max) >> 32 */
  119. #define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
  120. #endif
  121. unsigned long tb_ticks_per_jiffy;
  122. unsigned long tb_ticks_per_usec = 100; /* sane default */
  123. EXPORT_SYMBOL(tb_ticks_per_usec);
  124. unsigned long tb_ticks_per_sec;
  125. EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
  126. DEFINE_SPINLOCK(rtc_lock);
  127. EXPORT_SYMBOL_GPL(rtc_lock);
  128. static u64 tb_to_ns_scale __read_mostly;
  129. static unsigned tb_to_ns_shift __read_mostly;
  130. static u64 boot_tb __read_mostly;
  131. extern struct timezone sys_tz;
  132. static long timezone_offset;
  133. unsigned long ppc_proc_freq;
  134. EXPORT_SYMBOL_GPL(ppc_proc_freq);
  135. unsigned long ppc_tb_freq;
  136. EXPORT_SYMBOL_GPL(ppc_tb_freq);
  137. #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
  138. /*
  139. * Factor for converting from cputime_t (timebase ticks) to
  140. * microseconds. This is stored as 0.64 fixed-point binary fraction.
  141. */
  142. u64 __cputime_usec_factor;
  143. EXPORT_SYMBOL(__cputime_usec_factor);
  144. #ifdef CONFIG_PPC_SPLPAR
  145. void (*dtl_consumer)(struct dtl_entry *, u64);
  146. #endif
  147. static void calc_cputime_factors(void)
  148. {
  149. struct div_result res;
  150. div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
  151. __cputime_usec_factor = res.result_low;
  152. }
  153. /*
  154. * Read the SPURR on systems that have it, otherwise the PURR,
  155. * or if that doesn't exist return the timebase value passed in.
  156. */
  157. static inline unsigned long read_spurr(unsigned long tb)
  158. {
  159. if (cpu_has_feature(CPU_FTR_SPURR))
  160. return mfspr(SPRN_SPURR);
  161. if (cpu_has_feature(CPU_FTR_PURR))
  162. return mfspr(SPRN_PURR);
  163. return tb;
  164. }
  165. #ifdef CONFIG_PPC_SPLPAR
  166. /*
  167. * Scan the dispatch trace log and count up the stolen time.
  168. * Should be called with interrupts disabled.
  169. */
  170. static u64 scan_dispatch_log(u64 stop_tb)
  171. {
  172. u64 i = local_paca->dtl_ridx;
  173. struct dtl_entry *dtl = local_paca->dtl_curr;
  174. struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
  175. struct lppaca *vpa = local_paca->lppaca_ptr;
  176. u64 tb_delta;
  177. u64 stolen = 0;
  178. u64 dtb;
  179. if (!dtl)
  180. return 0;
  181. if (i == be64_to_cpu(vpa->dtl_idx))
  182. return 0;
  183. while (i < be64_to_cpu(vpa->dtl_idx)) {
  184. dtb = be64_to_cpu(dtl->timebase);
  185. tb_delta = be32_to_cpu(dtl->enqueue_to_dispatch_time) +
  186. be32_to_cpu(dtl->ready_to_enqueue_time);
  187. barrier();
  188. if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
  189. /* buffer has overflowed */
  190. i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
  191. dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
  192. continue;
  193. }
  194. if (dtb > stop_tb)
  195. break;
  196. if (dtl_consumer)
  197. dtl_consumer(dtl, i);
  198. stolen += tb_delta;
  199. ++i;
  200. ++dtl;
  201. if (dtl == dtl_end)
  202. dtl = local_paca->dispatch_log;
  203. }
  204. local_paca->dtl_ridx = i;
  205. local_paca->dtl_curr = dtl;
  206. return stolen;
  207. }
  208. /*
  209. * Accumulate stolen time by scanning the dispatch trace log.
  210. * Called on entry from user mode.
  211. */
  212. void accumulate_stolen_time(void)
  213. {
  214. u64 sst, ust;
  215. unsigned long save_irq_soft_mask = irq_soft_mask_return();
  216. struct cpu_accounting_data *acct = &local_paca->accounting;
  217. /* We are called early in the exception entry, before
  218. * soft/hard_enabled are sync'ed to the expected state
  219. * for the exception. We are hard disabled but the PACA
  220. * needs to reflect that so various debug stuff doesn't
  221. * complain
  222. */
  223. irq_soft_mask_set(IRQS_DISABLED);
  224. sst = scan_dispatch_log(acct->starttime_user);
  225. ust = scan_dispatch_log(acct->starttime);
  226. acct->stime -= sst;
  227. acct->utime -= ust;
  228. acct->steal_time += ust + sst;
  229. irq_soft_mask_set(save_irq_soft_mask);
  230. }
  231. static inline u64 calculate_stolen_time(u64 stop_tb)
  232. {
  233. if (!firmware_has_feature(FW_FEATURE_SPLPAR))
  234. return 0;
  235. if (get_paca()->dtl_ridx != be64_to_cpu(get_lppaca()->dtl_idx))
  236. return scan_dispatch_log(stop_tb);
  237. return 0;
  238. }
  239. #else /* CONFIG_PPC_SPLPAR */
  240. static inline u64 calculate_stolen_time(u64 stop_tb)
  241. {
  242. return 0;
  243. }
  244. #endif /* CONFIG_PPC_SPLPAR */
  245. /*
  246. * Account time for a transition between system, hard irq
  247. * or soft irq state.
  248. */
  249. static unsigned long vtime_delta_scaled(struct cpu_accounting_data *acct,
  250. unsigned long now, unsigned long stime)
  251. {
  252. unsigned long stime_scaled = 0;
  253. #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
  254. unsigned long nowscaled, deltascaled;
  255. unsigned long utime, utime_scaled;
  256. nowscaled = read_spurr(now);
  257. deltascaled = nowscaled - acct->startspurr;
  258. acct->startspurr = nowscaled;
  259. utime = acct->utime - acct->utime_sspurr;
  260. acct->utime_sspurr = acct->utime;
  261. /*
  262. * Because we don't read the SPURR on every kernel entry/exit,
  263. * deltascaled includes both user and system SPURR ticks.
  264. * Apportion these ticks to system SPURR ticks and user
  265. * SPURR ticks in the same ratio as the system time (delta)
  266. * and user time (udelta) values obtained from the timebase
  267. * over the same interval. The system ticks get accounted here;
  268. * the user ticks get saved up in paca->user_time_scaled to be
  269. * used by account_process_tick.
  270. */
  271. stime_scaled = stime;
  272. utime_scaled = utime;
  273. if (deltascaled != stime + utime) {
  274. if (utime) {
  275. stime_scaled = deltascaled * stime / (stime + utime);
  276. utime_scaled = deltascaled - stime_scaled;
  277. } else {
  278. stime_scaled = deltascaled;
  279. }
  280. }
  281. acct->utime_scaled += utime_scaled;
  282. #endif
  283. return stime_scaled;
  284. }
  285. static unsigned long vtime_delta(struct task_struct *tsk,
  286. unsigned long *stime_scaled,
  287. unsigned long *steal_time)
  288. {
  289. unsigned long now, stime;
  290. struct cpu_accounting_data *acct = get_accounting(tsk);
  291. WARN_ON_ONCE(!irqs_disabled());
  292. now = mftb();
  293. stime = now - acct->starttime;
  294. acct->starttime = now;
  295. *stime_scaled = vtime_delta_scaled(acct, now, stime);
  296. *steal_time = calculate_stolen_time(now);
  297. return stime;
  298. }
  299. void vtime_account_system(struct task_struct *tsk)
  300. {
  301. unsigned long stime, stime_scaled, steal_time;
  302. struct cpu_accounting_data *acct = get_accounting(tsk);
  303. stime = vtime_delta(tsk, &stime_scaled, &steal_time);
  304. stime -= min(stime, steal_time);
  305. acct->steal_time += steal_time;
  306. if ((tsk->flags & PF_VCPU) && !irq_count()) {
  307. acct->gtime += stime;
  308. #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
  309. acct->utime_scaled += stime_scaled;
  310. #endif
  311. } else {
  312. if (hardirq_count())
  313. acct->hardirq_time += stime;
  314. else if (in_serving_softirq())
  315. acct->softirq_time += stime;
  316. else
  317. acct->stime += stime;
  318. #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
  319. acct->stime_scaled += stime_scaled;
  320. #endif
  321. }
  322. }
  323. EXPORT_SYMBOL_GPL(vtime_account_system);
  324. void vtime_account_idle(struct task_struct *tsk)
  325. {
  326. unsigned long stime, stime_scaled, steal_time;
  327. struct cpu_accounting_data *acct = get_accounting(tsk);
  328. stime = vtime_delta(tsk, &stime_scaled, &steal_time);
  329. acct->idle_time += stime + steal_time;
  330. }
  331. static void vtime_flush_scaled(struct task_struct *tsk,
  332. struct cpu_accounting_data *acct)
  333. {
  334. #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
  335. if (acct->utime_scaled)
  336. tsk->utimescaled += cputime_to_nsecs(acct->utime_scaled);
  337. if (acct->stime_scaled)
  338. tsk->stimescaled += cputime_to_nsecs(acct->stime_scaled);
  339. acct->utime_scaled = 0;
  340. acct->utime_sspurr = 0;
  341. acct->stime_scaled = 0;
  342. #endif
  343. }
  344. /*
  345. * Account the whole cputime accumulated in the paca
  346. * Must be called with interrupts disabled.
  347. * Assumes that vtime_account_system/idle() has been called
  348. * recently (i.e. since the last entry from usermode) so that
  349. * get_paca()->user_time_scaled is up to date.
  350. */
  351. void vtime_flush(struct task_struct *tsk)
  352. {
  353. struct cpu_accounting_data *acct = get_accounting(tsk);
  354. if (acct->utime)
  355. account_user_time(tsk, cputime_to_nsecs(acct->utime));
  356. if (acct->gtime)
  357. account_guest_time(tsk, cputime_to_nsecs(acct->gtime));
  358. if (IS_ENABLED(CONFIG_PPC_SPLPAR) && acct->steal_time) {
  359. account_steal_time(cputime_to_nsecs(acct->steal_time));
  360. acct->steal_time = 0;
  361. }
  362. if (acct->idle_time)
  363. account_idle_time(cputime_to_nsecs(acct->idle_time));
  364. if (acct->stime)
  365. account_system_index_time(tsk, cputime_to_nsecs(acct->stime),
  366. CPUTIME_SYSTEM);
  367. if (acct->hardirq_time)
  368. account_system_index_time(tsk, cputime_to_nsecs(acct->hardirq_time),
  369. CPUTIME_IRQ);
  370. if (acct->softirq_time)
  371. account_system_index_time(tsk, cputime_to_nsecs(acct->softirq_time),
  372. CPUTIME_SOFTIRQ);
  373. vtime_flush_scaled(tsk, acct);
  374. acct->utime = 0;
  375. acct->gtime = 0;
  376. acct->idle_time = 0;
  377. acct->stime = 0;
  378. acct->hardirq_time = 0;
  379. acct->softirq_time = 0;
  380. }
  381. #else /* ! CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
  382. #define calc_cputime_factors()
  383. #endif
  384. void __delay(unsigned long loops)
  385. {
  386. unsigned long start;
  387. int diff;
  388. spin_begin();
  389. if (__USE_RTC()) {
  390. start = get_rtcl();
  391. do {
  392. /* the RTCL register wraps at 1000000000 */
  393. diff = get_rtcl() - start;
  394. if (diff < 0)
  395. diff += 1000000000;
  396. spin_cpu_relax();
  397. } while (diff < loops);
  398. } else {
  399. start = get_tbl();
  400. while (get_tbl() - start < loops)
  401. spin_cpu_relax();
  402. }
  403. spin_end();
  404. }
  405. EXPORT_SYMBOL(__delay);
  406. void udelay(unsigned long usecs)
  407. {
  408. __delay(tb_ticks_per_usec * usecs);
  409. }
  410. EXPORT_SYMBOL(udelay);
  411. #ifdef CONFIG_SMP
  412. unsigned long profile_pc(struct pt_regs *regs)
  413. {
  414. unsigned long pc = instruction_pointer(regs);
  415. if (in_lock_functions(pc))
  416. return regs->link;
  417. return pc;
  418. }
  419. EXPORT_SYMBOL(profile_pc);
  420. #endif
  421. #ifdef CONFIG_IRQ_WORK
  422. /*
  423. * 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
  424. */
  425. #ifdef CONFIG_PPC64
  426. static inline unsigned long test_irq_work_pending(void)
  427. {
  428. unsigned long x;
  429. asm volatile("lbz %0,%1(13)"
  430. : "=r" (x)
  431. : "i" (offsetof(struct paca_struct, irq_work_pending)));
  432. return x;
  433. }
  434. static inline void set_irq_work_pending_flag(void)
  435. {
  436. asm volatile("stb %0,%1(13)" : :
  437. "r" (1),
  438. "i" (offsetof(struct paca_struct, irq_work_pending)));
  439. }
  440. static inline void clear_irq_work_pending(void)
  441. {
  442. asm volatile("stb %0,%1(13)" : :
  443. "r" (0),
  444. "i" (offsetof(struct paca_struct, irq_work_pending)));
  445. }
  446. void arch_irq_work_raise(void)
  447. {
  448. preempt_disable();
  449. set_irq_work_pending_flag();
  450. /*
  451. * Non-nmi code running with interrupts disabled will replay
  452. * irq_happened before it re-enables interrupts, so setthe
  453. * decrementer there instead of causing a hardware exception
  454. * which would immediately hit the masked interrupt handler
  455. * and have the net effect of setting the decrementer in
  456. * irq_happened.
  457. *
  458. * NMI interrupts can not check this when they return, so the
  459. * decrementer hardware exception is raised, which will fire
  460. * when interrupts are next enabled.
  461. *
  462. * BookE does not support this yet, it must audit all NMI
  463. * interrupt handlers to ensure they call nmi_enter() so this
  464. * check would be correct.
  465. */
  466. if (IS_ENABLED(CONFIG_BOOKE) || !irqs_disabled() || in_nmi()) {
  467. set_dec(1);
  468. } else {
  469. hard_irq_disable();
  470. local_paca->irq_happened |= PACA_IRQ_DEC;
  471. }
  472. preempt_enable();
  473. }
  474. #else /* 32-bit */
  475. DEFINE_PER_CPU(u8, irq_work_pending);
  476. #define set_irq_work_pending_flag() __this_cpu_write(irq_work_pending, 1)
  477. #define test_irq_work_pending() __this_cpu_read(irq_work_pending)
  478. #define clear_irq_work_pending() __this_cpu_write(irq_work_pending, 0)
  479. void arch_irq_work_raise(void)
  480. {
  481. preempt_disable();
  482. set_irq_work_pending_flag();
  483. set_dec(1);
  484. preempt_enable();
  485. }
  486. #endif /* 32 vs 64 bit */
  487. #else /* CONFIG_IRQ_WORK */
  488. #define test_irq_work_pending() 0
  489. #define clear_irq_work_pending()
  490. #endif /* CONFIG_IRQ_WORK */
  491. /*
  492. * timer_interrupt - gets called when the decrementer overflows,
  493. * with interrupts disabled.
  494. */
  495. void timer_interrupt(struct pt_regs *regs)
  496. {
  497. struct clock_event_device *evt = this_cpu_ptr(&decrementers);
  498. u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
  499. struct pt_regs *old_regs;
  500. u64 now;
  501. /* Some implementations of hotplug will get timer interrupts while
  502. * offline, just ignore these and we also need to set
  503. * decrementers_next_tb as MAX to make sure __check_irq_replay
  504. * don't replay timer interrupt when return, otherwise we'll trap
  505. * here infinitely :(
  506. */
  507. if (unlikely(!cpu_online(smp_processor_id()))) {
  508. *next_tb = ~(u64)0;
  509. set_dec(decrementer_max);
  510. return;
  511. }
  512. /* Ensure a positive value is written to the decrementer, or else
  513. * some CPUs will continue to take decrementer exceptions. When the
  514. * PPC_WATCHDOG (decrementer based) is configured, keep this at most
  515. * 31 bits, which is about 4 seconds on most systems, which gives
  516. * the watchdog a chance of catching timer interrupt hard lockups.
  517. */
  518. if (IS_ENABLED(CONFIG_PPC_WATCHDOG))
  519. set_dec(0x7fffffff);
  520. else
  521. set_dec(decrementer_max);
  522. /* Conditionally hard-enable interrupts now that the DEC has been
  523. * bumped to its maximum value
  524. */
  525. may_hard_irq_enable();
  526. #if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
  527. if (atomic_read(&ppc_n_lost_interrupts) != 0)
  528. do_IRQ(regs);
  529. #endif
  530. old_regs = set_irq_regs(regs);
  531. irq_enter();
  532. trace_timer_interrupt_entry(regs);
  533. if (test_irq_work_pending()) {
  534. clear_irq_work_pending();
  535. irq_work_run();
  536. }
  537. now = get_tb_or_rtc();
  538. if (now >= *next_tb) {
  539. *next_tb = ~(u64)0;
  540. if (evt->event_handler)
  541. evt->event_handler(evt);
  542. __this_cpu_inc(irq_stat.timer_irqs_event);
  543. } else {
  544. now = *next_tb - now;
  545. if (now <= decrementer_max)
  546. set_dec(now);
  547. /* We may have raced with new irq work */
  548. if (test_irq_work_pending())
  549. set_dec(1);
  550. __this_cpu_inc(irq_stat.timer_irqs_others);
  551. }
  552. trace_timer_interrupt_exit(regs);
  553. irq_exit();
  554. set_irq_regs(old_regs);
  555. }
  556. EXPORT_SYMBOL(timer_interrupt);
  557. #ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
  558. void timer_broadcast_interrupt(void)
  559. {
  560. u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
  561. *next_tb = ~(u64)0;
  562. tick_receive_broadcast();
  563. __this_cpu_inc(irq_stat.broadcast_irqs_event);
  564. }
  565. #endif
  566. /*
  567. * Hypervisor decrementer interrupts shouldn't occur but are sometimes
  568. * left pending on exit from a KVM guest. We don't need to do anything
  569. * to clear them, as they are edge-triggered.
  570. */
  571. void hdec_interrupt(struct pt_regs *regs)
  572. {
  573. }
  574. #ifdef CONFIG_SUSPEND
  575. static void generic_suspend_disable_irqs(void)
  576. {
  577. /* Disable the decrementer, so that it doesn't interfere
  578. * with suspending.
  579. */
  580. set_dec(decrementer_max);
  581. local_irq_disable();
  582. set_dec(decrementer_max);
  583. }
  584. static void generic_suspend_enable_irqs(void)
  585. {
  586. local_irq_enable();
  587. }
  588. /* Overrides the weak version in kernel/power/main.c */
  589. void arch_suspend_disable_irqs(void)
  590. {
  591. if (ppc_md.suspend_disable_irqs)
  592. ppc_md.suspend_disable_irqs();
  593. generic_suspend_disable_irqs();
  594. }
  595. /* Overrides the weak version in kernel/power/main.c */
  596. void arch_suspend_enable_irqs(void)
  597. {
  598. generic_suspend_enable_irqs();
  599. if (ppc_md.suspend_enable_irqs)
  600. ppc_md.suspend_enable_irqs();
  601. }
  602. #endif
  603. unsigned long long tb_to_ns(unsigned long long ticks)
  604. {
  605. return mulhdu(ticks, tb_to_ns_scale) << tb_to_ns_shift;
  606. }
  607. EXPORT_SYMBOL_GPL(tb_to_ns);
  608. /*
  609. * Scheduler clock - returns current time in nanosec units.
  610. *
  611. * Note: mulhdu(a, b) (multiply high double unsigned) returns
  612. * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
  613. * are 64-bit unsigned numbers.
  614. */
  615. notrace unsigned long long sched_clock(void)
  616. {
  617. if (__USE_RTC())
  618. return get_rtc();
  619. return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  620. }
  621. #ifdef CONFIG_PPC_PSERIES
  622. /*
  623. * Running clock - attempts to give a view of time passing for a virtualised
  624. * kernels.
  625. * Uses the VTB register if available otherwise a next best guess.
  626. */
  627. unsigned long long running_clock(void)
  628. {
  629. /*
  630. * Don't read the VTB as a host since KVM does not switch in host
  631. * timebase into the VTB when it takes a guest off the CPU, reading the
  632. * VTB would result in reading 'last switched out' guest VTB.
  633. *
  634. * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
  635. * would be unsafe to rely only on the #ifdef above.
  636. */
  637. if (firmware_has_feature(FW_FEATURE_LPAR) &&
  638. cpu_has_feature(CPU_FTR_ARCH_207S))
  639. return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  640. /*
  641. * This is a next best approximation without a VTB.
  642. * On a host which is running bare metal there should never be any stolen
  643. * time and on a host which doesn't do any virtualisation TB *should* equal
  644. * VTB so it makes no difference anyway.
  645. */
  646. return local_clock() - kcpustat_this_cpu->cpustat[CPUTIME_STEAL];
  647. }
  648. #endif
  649. static int __init get_freq(char *name, int cells, unsigned long *val)
  650. {
  651. struct device_node *cpu;
  652. const __be32 *fp;
  653. int found = 0;
  654. /* The cpu node should have timebase and clock frequency properties */
  655. cpu = of_find_node_by_type(NULL, "cpu");
  656. if (cpu) {
  657. fp = of_get_property(cpu, name, NULL);
  658. if (fp) {
  659. found = 1;
  660. *val = of_read_ulong(fp, cells);
  661. }
  662. of_node_put(cpu);
  663. }
  664. return found;
  665. }
  666. static void start_cpu_decrementer(void)
  667. {
  668. #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
  669. unsigned int tcr;
  670. /* Clear any pending timer interrupts */
  671. mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
  672. tcr = mfspr(SPRN_TCR);
  673. /*
  674. * The watchdog may have already been enabled by u-boot. So leave
  675. * TRC[WP] (Watchdog Period) alone.
  676. */
  677. tcr &= TCR_WP_MASK; /* Clear all bits except for TCR[WP] */
  678. tcr |= TCR_DIE; /* Enable decrementer */
  679. mtspr(SPRN_TCR, tcr);
  680. #endif
  681. }
  682. void __init generic_calibrate_decr(void)
  683. {
  684. ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
  685. if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
  686. !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
  687. printk(KERN_ERR "WARNING: Estimating decrementer frequency "
  688. "(not found)\n");
  689. }
  690. ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
  691. if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
  692. !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
  693. printk(KERN_ERR "WARNING: Estimating processor frequency "
  694. "(not found)\n");
  695. }
  696. }
  697. int update_persistent_clock64(struct timespec64 now)
  698. {
  699. struct rtc_time tm;
  700. if (!ppc_md.set_rtc_time)
  701. return -ENODEV;
  702. rtc_time64_to_tm(now.tv_sec + 1 + timezone_offset, &tm);
  703. return ppc_md.set_rtc_time(&tm);
  704. }
  705. static void __read_persistent_clock(struct timespec64 *ts)
  706. {
  707. struct rtc_time tm;
  708. static int first = 1;
  709. ts->tv_nsec = 0;
  710. /* XXX this is a litle fragile but will work okay in the short term */
  711. if (first) {
  712. first = 0;
  713. if (ppc_md.time_init)
  714. timezone_offset = ppc_md.time_init();
  715. /* get_boot_time() isn't guaranteed to be safe to call late */
  716. if (ppc_md.get_boot_time) {
  717. ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
  718. return;
  719. }
  720. }
  721. if (!ppc_md.get_rtc_time) {
  722. ts->tv_sec = 0;
  723. return;
  724. }
  725. ppc_md.get_rtc_time(&tm);
  726. ts->tv_sec = rtc_tm_to_time64(&tm);
  727. }
  728. void read_persistent_clock64(struct timespec64 *ts)
  729. {
  730. __read_persistent_clock(ts);
  731. /* Sanitize it in case real time clock is set below EPOCH */
  732. if (ts->tv_sec < 0) {
  733. ts->tv_sec = 0;
  734. ts->tv_nsec = 0;
  735. }
  736. }
  737. /* clocksource code */
  738. static notrace u64 rtc_read(struct clocksource *cs)
  739. {
  740. return (u64)get_rtc();
  741. }
  742. static notrace u64 timebase_read(struct clocksource *cs)
  743. {
  744. return (u64)get_tb();
  745. }
  746. void update_vsyscall(struct timekeeper *tk)
  747. {
  748. struct timespec xt;
  749. struct clocksource *clock = tk->tkr_mono.clock;
  750. u32 mult = tk->tkr_mono.mult;
  751. u32 shift = tk->tkr_mono.shift;
  752. u64 cycle_last = tk->tkr_mono.cycle_last;
  753. u64 new_tb_to_xs, new_stamp_xsec;
  754. u64 frac_sec;
  755. if (clock != &clocksource_timebase)
  756. return;
  757. xt.tv_sec = tk->xtime_sec;
  758. xt.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
  759. /* Make userspace gettimeofday spin until we're done. */
  760. ++vdso_data->tb_update_count;
  761. smp_mb();
  762. /*
  763. * This computes ((2^20 / 1e9) * mult) >> shift as a
  764. * 0.64 fixed-point fraction.
  765. * The computation in the else clause below won't overflow
  766. * (as long as the timebase frequency is >= 1.049 MHz)
  767. * but loses precision because we lose the low bits of the constant
  768. * in the shift. Note that 19342813113834067 ~= 2^(20+64) / 1e9.
  769. * For a shift of 24 the error is about 0.5e-9, or about 0.5ns
  770. * over a second. (Shift values are usually 22, 23 or 24.)
  771. * For high frequency clocks such as the 512MHz timebase clock
  772. * on POWER[6789], the mult value is small (e.g. 32768000)
  773. * and so we can shift the constant by 16 initially
  774. * (295147905179 ~= 2^(20+64-16) / 1e9) and then do the
  775. * remaining shifts after the multiplication, which gives a
  776. * more accurate result (e.g. with mult = 32768000, shift = 24,
  777. * the error is only about 1.2e-12, or 0.7ns over 10 minutes).
  778. */
  779. if (mult <= 62500000 && clock->shift >= 16)
  780. new_tb_to_xs = ((u64) mult * 295147905179ULL) >> (clock->shift - 16);
  781. else
  782. new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
  783. /*
  784. * Compute the fractional second in units of 2^-32 seconds.
  785. * The fractional second is tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift
  786. * in nanoseconds, so multiplying that by 2^32 / 1e9 gives
  787. * it in units of 2^-32 seconds.
  788. * We assume shift <= 32 because clocks_calc_mult_shift()
  789. * generates shift values in the range 0 - 32.
  790. */
  791. frac_sec = tk->tkr_mono.xtime_nsec << (32 - shift);
  792. do_div(frac_sec, NSEC_PER_SEC);
  793. /*
  794. * Work out new stamp_xsec value for any legacy users of systemcfg.
  795. * stamp_xsec is in units of 2^-20 seconds.
  796. */
  797. new_stamp_xsec = frac_sec >> 12;
  798. new_stamp_xsec += tk->xtime_sec * XSEC_PER_SEC;
  799. /*
  800. * tb_update_count is used to allow the userspace gettimeofday code
  801. * to assure itself that it sees a consistent view of the tb_to_xs and
  802. * stamp_xsec variables. It reads the tb_update_count, then reads
  803. * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
  804. * the two values of tb_update_count match and are even then the
  805. * tb_to_xs and stamp_xsec values are consistent. If not, then it
  806. * loops back and reads them again until this criteria is met.
  807. */
  808. vdso_data->tb_orig_stamp = cycle_last;
  809. vdso_data->stamp_xsec = new_stamp_xsec;
  810. vdso_data->tb_to_xs = new_tb_to_xs;
  811. vdso_data->wtom_clock_sec = tk->wall_to_monotonic.tv_sec;
  812. vdso_data->wtom_clock_nsec = tk->wall_to_monotonic.tv_nsec;
  813. vdso_data->stamp_xtime = xt;
  814. vdso_data->stamp_sec_fraction = frac_sec;
  815. smp_wmb();
  816. ++(vdso_data->tb_update_count);
  817. }
  818. void update_vsyscall_tz(void)
  819. {
  820. vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
  821. vdso_data->tz_dsttime = sys_tz.tz_dsttime;
  822. }
  823. static void __init clocksource_init(void)
  824. {
  825. struct clocksource *clock;
  826. if (__USE_RTC())
  827. clock = &clocksource_rtc;
  828. else
  829. clock = &clocksource_timebase;
  830. if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
  831. printk(KERN_ERR "clocksource: %s is already registered\n",
  832. clock->name);
  833. return;
  834. }
  835. printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
  836. clock->name, clock->mult, clock->shift);
  837. }
  838. static int decrementer_set_next_event(unsigned long evt,
  839. struct clock_event_device *dev)
  840. {
  841. __this_cpu_write(decrementers_next_tb, get_tb_or_rtc() + evt);
  842. set_dec(evt);
  843. /* We may have raced with new irq work */
  844. if (test_irq_work_pending())
  845. set_dec(1);
  846. return 0;
  847. }
  848. static int decrementer_shutdown(struct clock_event_device *dev)
  849. {
  850. decrementer_set_next_event(decrementer_max, dev);
  851. return 0;
  852. }
  853. static void register_decrementer_clockevent(int cpu)
  854. {
  855. struct clock_event_device *dec = &per_cpu(decrementers, cpu);
  856. *dec = decrementer_clockevent;
  857. dec->cpumask = cpumask_of(cpu);
  858. clockevents_config_and_register(dec, ppc_tb_freq, 2, decrementer_max);
  859. printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
  860. dec->name, dec->mult, dec->shift, cpu);
  861. /* Set values for KVM, see kvm_emulate_dec() */
  862. decrementer_clockevent.mult = dec->mult;
  863. decrementer_clockevent.shift = dec->shift;
  864. }
  865. static void enable_large_decrementer(void)
  866. {
  867. if (!cpu_has_feature(CPU_FTR_ARCH_300))
  868. return;
  869. if (decrementer_max <= DECREMENTER_DEFAULT_MAX)
  870. return;
  871. /*
  872. * If we're running as the hypervisor we need to enable the LD manually
  873. * otherwise firmware should have done it for us.
  874. */
  875. if (cpu_has_feature(CPU_FTR_HVMODE))
  876. mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) | LPCR_LD);
  877. }
  878. static void __init set_decrementer_max(void)
  879. {
  880. struct device_node *cpu;
  881. u32 bits = 32;
  882. /* Prior to ISAv3 the decrementer is always 32 bit */
  883. if (!cpu_has_feature(CPU_FTR_ARCH_300))
  884. return;
  885. cpu = of_find_node_by_type(NULL, "cpu");
  886. if (of_property_read_u32(cpu, "ibm,dec-bits", &bits) == 0) {
  887. if (bits > 64 || bits < 32) {
  888. pr_warn("time_init: firmware supplied invalid ibm,dec-bits");
  889. bits = 32;
  890. }
  891. /* calculate the signed maximum given this many bits */
  892. decrementer_max = (1ul << (bits - 1)) - 1;
  893. }
  894. of_node_put(cpu);
  895. pr_info("time_init: %u bit decrementer (max: %llx)\n",
  896. bits, decrementer_max);
  897. }
  898. static void __init init_decrementer_clockevent(void)
  899. {
  900. register_decrementer_clockevent(smp_processor_id());
  901. }
  902. void secondary_cpu_time_init(void)
  903. {
  904. /* Enable and test the large decrementer for this cpu */
  905. enable_large_decrementer();
  906. /* Start the decrementer on CPUs that have manual control
  907. * such as BookE
  908. */
  909. start_cpu_decrementer();
  910. /* FIME: Should make unrelatred change to move snapshot_timebase
  911. * call here ! */
  912. register_decrementer_clockevent(smp_processor_id());
  913. }
  914. /* This function is only called on the boot processor */
  915. void __init time_init(void)
  916. {
  917. struct div_result res;
  918. u64 scale;
  919. unsigned shift;
  920. if (__USE_RTC()) {
  921. /* 601 processor: dec counts down by 128 every 128ns */
  922. ppc_tb_freq = 1000000000;
  923. } else {
  924. /* Normal PowerPC with timebase register */
  925. ppc_md.calibrate_decr();
  926. printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
  927. ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
  928. printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
  929. ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
  930. }
  931. tb_ticks_per_jiffy = ppc_tb_freq / HZ;
  932. tb_ticks_per_sec = ppc_tb_freq;
  933. tb_ticks_per_usec = ppc_tb_freq / 1000000;
  934. calc_cputime_factors();
  935. /*
  936. * Compute scale factor for sched_clock.
  937. * The calibrate_decr() function has set tb_ticks_per_sec,
  938. * which is the timebase frequency.
  939. * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
  940. * the 128-bit result as a 64.64 fixed-point number.
  941. * We then shift that number right until it is less than 1.0,
  942. * giving us the scale factor and shift count to use in
  943. * sched_clock().
  944. */
  945. div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
  946. scale = res.result_low;
  947. for (shift = 0; res.result_high != 0; ++shift) {
  948. scale = (scale >> 1) | (res.result_high << 63);
  949. res.result_high >>= 1;
  950. }
  951. tb_to_ns_scale = scale;
  952. tb_to_ns_shift = shift;
  953. /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
  954. boot_tb = get_tb_or_rtc();
  955. /* If platform provided a timezone (pmac), we correct the time */
  956. if (timezone_offset) {
  957. sys_tz.tz_minuteswest = -timezone_offset / 60;
  958. sys_tz.tz_dsttime = 0;
  959. }
  960. vdso_data->tb_update_count = 0;
  961. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  962. /* initialise and enable the large decrementer (if we have one) */
  963. set_decrementer_max();
  964. enable_large_decrementer();
  965. /* Start the decrementer on CPUs that have manual control
  966. * such as BookE
  967. */
  968. start_cpu_decrementer();
  969. /* Register the clocksource */
  970. clocksource_init();
  971. init_decrementer_clockevent();
  972. tick_setup_hrtimer_broadcast();
  973. #ifdef CONFIG_COMMON_CLK
  974. of_clk_init(NULL);
  975. #endif
  976. }
  977. /*
  978. * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
  979. * result.
  980. */
  981. void div128_by_32(u64 dividend_high, u64 dividend_low,
  982. unsigned divisor, struct div_result *dr)
  983. {
  984. unsigned long a, b, c, d;
  985. unsigned long w, x, y, z;
  986. u64 ra, rb, rc;
  987. a = dividend_high >> 32;
  988. b = dividend_high & 0xffffffff;
  989. c = dividend_low >> 32;
  990. d = dividend_low & 0xffffffff;
  991. w = a / divisor;
  992. ra = ((u64)(a - (w * divisor)) << 32) + b;
  993. rb = ((u64) do_div(ra, divisor) << 32) + c;
  994. x = ra;
  995. rc = ((u64) do_div(rb, divisor) << 32) + d;
  996. y = rb;
  997. do_div(rc, divisor);
  998. z = rc;
  999. dr->result_high = ((u64)w << 32) + x;
  1000. dr->result_low = ((u64)y << 32) + z;
  1001. }
  1002. /* We don't need to calibrate delay, we use the CPU timebase for that */
  1003. void calibrate_delay(void)
  1004. {
  1005. /* Some generic code (such as spinlock debug) use loops_per_jiffy
  1006. * as the number of __delay(1) in a jiffy, so make it so
  1007. */
  1008. loops_per_jiffy = tb_ticks_per_jiffy;
  1009. }
  1010. #if IS_ENABLED(CONFIG_RTC_DRV_GENERIC)
  1011. static int rtc_generic_get_time(struct device *dev, struct rtc_time *tm)
  1012. {
  1013. ppc_md.get_rtc_time(tm);
  1014. return 0;
  1015. }
  1016. static int rtc_generic_set_time(struct device *dev, struct rtc_time *tm)
  1017. {
  1018. if (!ppc_md.set_rtc_time)
  1019. return -EOPNOTSUPP;
  1020. if (ppc_md.set_rtc_time(tm) < 0)
  1021. return -EOPNOTSUPP;
  1022. return 0;
  1023. }
  1024. static const struct rtc_class_ops rtc_generic_ops = {
  1025. .read_time = rtc_generic_get_time,
  1026. .set_time = rtc_generic_set_time,
  1027. };
  1028. static int __init rtc_init(void)
  1029. {
  1030. struct platform_device *pdev;
  1031. if (!ppc_md.get_rtc_time)
  1032. return -ENODEV;
  1033. pdev = platform_device_register_data(NULL, "rtc-generic", -1,
  1034. &rtc_generic_ops,
  1035. sizeof(rtc_generic_ops));
  1036. return PTR_ERR_OR_ZERO(pdev);
  1037. }
  1038. device_initcall(rtc_init);
  1039. #endif