time.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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 (acct->steal_time)
  359. account_steal_time(cputime_to_nsecs(acct->steal_time));
  360. if (acct->idle_time)
  361. account_idle_time(cputime_to_nsecs(acct->idle_time));
  362. if (acct->stime)
  363. account_system_index_time(tsk, cputime_to_nsecs(acct->stime),
  364. CPUTIME_SYSTEM);
  365. if (acct->hardirq_time)
  366. account_system_index_time(tsk, cputime_to_nsecs(acct->hardirq_time),
  367. CPUTIME_IRQ);
  368. if (acct->softirq_time)
  369. account_system_index_time(tsk, cputime_to_nsecs(acct->softirq_time),
  370. CPUTIME_SOFTIRQ);
  371. vtime_flush_scaled(tsk, acct);
  372. acct->utime = 0;
  373. acct->gtime = 0;
  374. acct->steal_time = 0;
  375. acct->idle_time = 0;
  376. acct->stime = 0;
  377. acct->hardirq_time = 0;
  378. acct->softirq_time = 0;
  379. }
  380. #else /* ! CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
  381. #define calc_cputime_factors()
  382. #endif
  383. void __delay(unsigned long loops)
  384. {
  385. unsigned long start;
  386. int diff;
  387. spin_begin();
  388. if (__USE_RTC()) {
  389. start = get_rtcl();
  390. do {
  391. /* the RTCL register wraps at 1000000000 */
  392. diff = get_rtcl() - start;
  393. if (diff < 0)
  394. diff += 1000000000;
  395. spin_cpu_relax();
  396. } while (diff < loops);
  397. } else {
  398. start = get_tbl();
  399. while (get_tbl() - start < loops)
  400. spin_cpu_relax();
  401. }
  402. spin_end();
  403. }
  404. EXPORT_SYMBOL(__delay);
  405. void udelay(unsigned long usecs)
  406. {
  407. __delay(tb_ticks_per_usec * usecs);
  408. }
  409. EXPORT_SYMBOL(udelay);
  410. #ifdef CONFIG_SMP
  411. unsigned long profile_pc(struct pt_regs *regs)
  412. {
  413. unsigned long pc = instruction_pointer(regs);
  414. if (in_lock_functions(pc))
  415. return regs->link;
  416. return pc;
  417. }
  418. EXPORT_SYMBOL(profile_pc);
  419. #endif
  420. #ifdef CONFIG_IRQ_WORK
  421. /*
  422. * 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
  423. */
  424. #ifdef CONFIG_PPC64
  425. static inline unsigned long test_irq_work_pending(void)
  426. {
  427. unsigned long x;
  428. asm volatile("lbz %0,%1(13)"
  429. : "=r" (x)
  430. : "i" (offsetof(struct paca_struct, irq_work_pending)));
  431. return x;
  432. }
  433. static inline void set_irq_work_pending_flag(void)
  434. {
  435. asm volatile("stb %0,%1(13)" : :
  436. "r" (1),
  437. "i" (offsetof(struct paca_struct, irq_work_pending)));
  438. }
  439. static inline void clear_irq_work_pending(void)
  440. {
  441. asm volatile("stb %0,%1(13)" : :
  442. "r" (0),
  443. "i" (offsetof(struct paca_struct, irq_work_pending)));
  444. }
  445. void arch_irq_work_raise(void)
  446. {
  447. preempt_disable();
  448. set_irq_work_pending_flag();
  449. /*
  450. * Non-nmi code running with interrupts disabled will replay
  451. * irq_happened before it re-enables interrupts, so setthe
  452. * decrementer there instead of causing a hardware exception
  453. * which would immediately hit the masked interrupt handler
  454. * and have the net effect of setting the decrementer in
  455. * irq_happened.
  456. *
  457. * NMI interrupts can not check this when they return, so the
  458. * decrementer hardware exception is raised, which will fire
  459. * when interrupts are next enabled.
  460. *
  461. * BookE does not support this yet, it must audit all NMI
  462. * interrupt handlers to ensure they call nmi_enter() so this
  463. * check would be correct.
  464. */
  465. if (IS_ENABLED(CONFIG_BOOKE) || !irqs_disabled() || in_nmi()) {
  466. set_dec(1);
  467. } else {
  468. hard_irq_disable();
  469. local_paca->irq_happened |= PACA_IRQ_DEC;
  470. }
  471. preempt_enable();
  472. }
  473. #else /* 32-bit */
  474. DEFINE_PER_CPU(u8, irq_work_pending);
  475. #define set_irq_work_pending_flag() __this_cpu_write(irq_work_pending, 1)
  476. #define test_irq_work_pending() __this_cpu_read(irq_work_pending)
  477. #define clear_irq_work_pending() __this_cpu_write(irq_work_pending, 0)
  478. void arch_irq_work_raise(void)
  479. {
  480. preempt_disable();
  481. set_irq_work_pending_flag();
  482. set_dec(1);
  483. preempt_enable();
  484. }
  485. #endif /* 32 vs 64 bit */
  486. #else /* CONFIG_IRQ_WORK */
  487. #define test_irq_work_pending() 0
  488. #define clear_irq_work_pending()
  489. #endif /* CONFIG_IRQ_WORK */
  490. /*
  491. * timer_interrupt - gets called when the decrementer overflows,
  492. * with interrupts disabled.
  493. */
  494. void timer_interrupt(struct pt_regs *regs)
  495. {
  496. struct clock_event_device *evt = this_cpu_ptr(&decrementers);
  497. u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
  498. struct pt_regs *old_regs;
  499. u64 now;
  500. /* Some implementations of hotplug will get timer interrupts while
  501. * offline, just ignore these and we also need to set
  502. * decrementers_next_tb as MAX to make sure __check_irq_replay
  503. * don't replay timer interrupt when return, otherwise we'll trap
  504. * here infinitely :(
  505. */
  506. if (unlikely(!cpu_online(smp_processor_id()))) {
  507. *next_tb = ~(u64)0;
  508. set_dec(decrementer_max);
  509. return;
  510. }
  511. /* Ensure a positive value is written to the decrementer, or else
  512. * some CPUs will continue to take decrementer exceptions. When the
  513. * PPC_WATCHDOG (decrementer based) is configured, keep this at most
  514. * 31 bits, which is about 4 seconds on most systems, which gives
  515. * the watchdog a chance of catching timer interrupt hard lockups.
  516. */
  517. if (IS_ENABLED(CONFIG_PPC_WATCHDOG))
  518. set_dec(0x7fffffff);
  519. else
  520. set_dec(decrementer_max);
  521. /* Conditionally hard-enable interrupts now that the DEC has been
  522. * bumped to its maximum value
  523. */
  524. may_hard_irq_enable();
  525. #if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
  526. if (atomic_read(&ppc_n_lost_interrupts) != 0)
  527. do_IRQ(regs);
  528. #endif
  529. old_regs = set_irq_regs(regs);
  530. irq_enter();
  531. trace_timer_interrupt_entry(regs);
  532. if (test_irq_work_pending()) {
  533. clear_irq_work_pending();
  534. irq_work_run();
  535. }
  536. now = get_tb_or_rtc();
  537. if (now >= *next_tb) {
  538. *next_tb = ~(u64)0;
  539. if (evt->event_handler)
  540. evt->event_handler(evt);
  541. __this_cpu_inc(irq_stat.timer_irqs_event);
  542. } else {
  543. now = *next_tb - now;
  544. if (now <= decrementer_max)
  545. set_dec(now);
  546. /* We may have raced with new irq work */
  547. if (test_irq_work_pending())
  548. set_dec(1);
  549. __this_cpu_inc(irq_stat.timer_irqs_others);
  550. }
  551. trace_timer_interrupt_exit(regs);
  552. irq_exit();
  553. set_irq_regs(old_regs);
  554. }
  555. EXPORT_SYMBOL(timer_interrupt);
  556. #ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
  557. void timer_broadcast_interrupt(void)
  558. {
  559. u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
  560. *next_tb = ~(u64)0;
  561. tick_receive_broadcast();
  562. __this_cpu_inc(irq_stat.broadcast_irqs_event);
  563. }
  564. #endif
  565. /*
  566. * Hypervisor decrementer interrupts shouldn't occur but are sometimes
  567. * left pending on exit from a KVM guest. We don't need to do anything
  568. * to clear them, as they are edge-triggered.
  569. */
  570. void hdec_interrupt(struct pt_regs *regs)
  571. {
  572. }
  573. #ifdef CONFIG_SUSPEND
  574. static void generic_suspend_disable_irqs(void)
  575. {
  576. /* Disable the decrementer, so that it doesn't interfere
  577. * with suspending.
  578. */
  579. set_dec(decrementer_max);
  580. local_irq_disable();
  581. set_dec(decrementer_max);
  582. }
  583. static void generic_suspend_enable_irqs(void)
  584. {
  585. local_irq_enable();
  586. }
  587. /* Overrides the weak version in kernel/power/main.c */
  588. void arch_suspend_disable_irqs(void)
  589. {
  590. if (ppc_md.suspend_disable_irqs)
  591. ppc_md.suspend_disable_irqs();
  592. generic_suspend_disable_irqs();
  593. }
  594. /* Overrides the weak version in kernel/power/main.c */
  595. void arch_suspend_enable_irqs(void)
  596. {
  597. generic_suspend_enable_irqs();
  598. if (ppc_md.suspend_enable_irqs)
  599. ppc_md.suspend_enable_irqs();
  600. }
  601. #endif
  602. unsigned long long tb_to_ns(unsigned long long ticks)
  603. {
  604. return mulhdu(ticks, tb_to_ns_scale) << tb_to_ns_shift;
  605. }
  606. EXPORT_SYMBOL_GPL(tb_to_ns);
  607. /*
  608. * Scheduler clock - returns current time in nanosec units.
  609. *
  610. * Note: mulhdu(a, b) (multiply high double unsigned) returns
  611. * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
  612. * are 64-bit unsigned numbers.
  613. */
  614. notrace unsigned long long sched_clock(void)
  615. {
  616. if (__USE_RTC())
  617. return get_rtc();
  618. return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  619. }
  620. #ifdef CONFIG_PPC_PSERIES
  621. /*
  622. * Running clock - attempts to give a view of time passing for a virtualised
  623. * kernels.
  624. * Uses the VTB register if available otherwise a next best guess.
  625. */
  626. unsigned long long running_clock(void)
  627. {
  628. /*
  629. * Don't read the VTB as a host since KVM does not switch in host
  630. * timebase into the VTB when it takes a guest off the CPU, reading the
  631. * VTB would result in reading 'last switched out' guest VTB.
  632. *
  633. * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
  634. * would be unsafe to rely only on the #ifdef above.
  635. */
  636. if (firmware_has_feature(FW_FEATURE_LPAR) &&
  637. cpu_has_feature(CPU_FTR_ARCH_207S))
  638. return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  639. /*
  640. * This is a next best approximation without a VTB.
  641. * On a host which is running bare metal there should never be any stolen
  642. * time and on a host which doesn't do any virtualisation TB *should* equal
  643. * VTB so it makes no difference anyway.
  644. */
  645. return local_clock() - kcpustat_this_cpu->cpustat[CPUTIME_STEAL];
  646. }
  647. #endif
  648. static int __init get_freq(char *name, int cells, unsigned long *val)
  649. {
  650. struct device_node *cpu;
  651. const __be32 *fp;
  652. int found = 0;
  653. /* The cpu node should have timebase and clock frequency properties */
  654. cpu = of_find_node_by_type(NULL, "cpu");
  655. if (cpu) {
  656. fp = of_get_property(cpu, name, NULL);
  657. if (fp) {
  658. found = 1;
  659. *val = of_read_ulong(fp, cells);
  660. }
  661. of_node_put(cpu);
  662. }
  663. return found;
  664. }
  665. static void start_cpu_decrementer(void)
  666. {
  667. #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
  668. unsigned int tcr;
  669. /* Clear any pending timer interrupts */
  670. mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
  671. tcr = mfspr(SPRN_TCR);
  672. /*
  673. * The watchdog may have already been enabled by u-boot. So leave
  674. * TRC[WP] (Watchdog Period) alone.
  675. */
  676. tcr &= TCR_WP_MASK; /* Clear all bits except for TCR[WP] */
  677. tcr |= TCR_DIE; /* Enable decrementer */
  678. mtspr(SPRN_TCR, tcr);
  679. #endif
  680. }
  681. void __init generic_calibrate_decr(void)
  682. {
  683. ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
  684. if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
  685. !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
  686. printk(KERN_ERR "WARNING: Estimating decrementer frequency "
  687. "(not found)\n");
  688. }
  689. ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
  690. if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
  691. !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
  692. printk(KERN_ERR "WARNING: Estimating processor frequency "
  693. "(not found)\n");
  694. }
  695. }
  696. int update_persistent_clock64(struct timespec64 now)
  697. {
  698. struct rtc_time tm;
  699. if (!ppc_md.set_rtc_time)
  700. return -ENODEV;
  701. rtc_time64_to_tm(now.tv_sec + 1 + timezone_offset, &tm);
  702. return ppc_md.set_rtc_time(&tm);
  703. }
  704. static void __read_persistent_clock(struct timespec64 *ts)
  705. {
  706. struct rtc_time tm;
  707. static int first = 1;
  708. ts->tv_nsec = 0;
  709. /* XXX this is a litle fragile but will work okay in the short term */
  710. if (first) {
  711. first = 0;
  712. if (ppc_md.time_init)
  713. timezone_offset = ppc_md.time_init();
  714. /* get_boot_time() isn't guaranteed to be safe to call late */
  715. if (ppc_md.get_boot_time) {
  716. ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
  717. return;
  718. }
  719. }
  720. if (!ppc_md.get_rtc_time) {
  721. ts->tv_sec = 0;
  722. return;
  723. }
  724. ppc_md.get_rtc_time(&tm);
  725. ts->tv_sec = rtc_tm_to_time64(&tm);
  726. }
  727. void read_persistent_clock64(struct timespec64 *ts)
  728. {
  729. __read_persistent_clock(ts);
  730. /* Sanitize it in case real time clock is set below EPOCH */
  731. if (ts->tv_sec < 0) {
  732. ts->tv_sec = 0;
  733. ts->tv_nsec = 0;
  734. }
  735. }
  736. /* clocksource code */
  737. static notrace u64 rtc_read(struct clocksource *cs)
  738. {
  739. return (u64)get_rtc();
  740. }
  741. static notrace u64 timebase_read(struct clocksource *cs)
  742. {
  743. return (u64)get_tb();
  744. }
  745. void update_vsyscall(struct timekeeper *tk)
  746. {
  747. struct timespec xt;
  748. struct clocksource *clock = tk->tkr_mono.clock;
  749. u32 mult = tk->tkr_mono.mult;
  750. u32 shift = tk->tkr_mono.shift;
  751. u64 cycle_last = tk->tkr_mono.cycle_last;
  752. u64 new_tb_to_xs, new_stamp_xsec;
  753. u64 frac_sec;
  754. if (clock != &clocksource_timebase)
  755. return;
  756. xt.tv_sec = tk->xtime_sec;
  757. xt.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
  758. /* Make userspace gettimeofday spin until we're done. */
  759. ++vdso_data->tb_update_count;
  760. smp_mb();
  761. /*
  762. * This computes ((2^20 / 1e9) * mult) >> shift as a
  763. * 0.64 fixed-point fraction.
  764. * The computation in the else clause below won't overflow
  765. * (as long as the timebase frequency is >= 1.049 MHz)
  766. * but loses precision because we lose the low bits of the constant
  767. * in the shift. Note that 19342813113834067 ~= 2^(20+64) / 1e9.
  768. * For a shift of 24 the error is about 0.5e-9, or about 0.5ns
  769. * over a second. (Shift values are usually 22, 23 or 24.)
  770. * For high frequency clocks such as the 512MHz timebase clock
  771. * on POWER[6789], the mult value is small (e.g. 32768000)
  772. * and so we can shift the constant by 16 initially
  773. * (295147905179 ~= 2^(20+64-16) / 1e9) and then do the
  774. * remaining shifts after the multiplication, which gives a
  775. * more accurate result (e.g. with mult = 32768000, shift = 24,
  776. * the error is only about 1.2e-12, or 0.7ns over 10 minutes).
  777. */
  778. if (mult <= 62500000 && clock->shift >= 16)
  779. new_tb_to_xs = ((u64) mult * 295147905179ULL) >> (clock->shift - 16);
  780. else
  781. new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
  782. /*
  783. * Compute the fractional second in units of 2^-32 seconds.
  784. * The fractional second is tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift
  785. * in nanoseconds, so multiplying that by 2^32 / 1e9 gives
  786. * it in units of 2^-32 seconds.
  787. * We assume shift <= 32 because clocks_calc_mult_shift()
  788. * generates shift values in the range 0 - 32.
  789. */
  790. frac_sec = tk->tkr_mono.xtime_nsec << (32 - shift);
  791. do_div(frac_sec, NSEC_PER_SEC);
  792. /*
  793. * Work out new stamp_xsec value for any legacy users of systemcfg.
  794. * stamp_xsec is in units of 2^-20 seconds.
  795. */
  796. new_stamp_xsec = frac_sec >> 12;
  797. new_stamp_xsec += tk->xtime_sec * XSEC_PER_SEC;
  798. /*
  799. * tb_update_count is used to allow the userspace gettimeofday code
  800. * to assure itself that it sees a consistent view of the tb_to_xs and
  801. * stamp_xsec variables. It reads the tb_update_count, then reads
  802. * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
  803. * the two values of tb_update_count match and are even then the
  804. * tb_to_xs and stamp_xsec values are consistent. If not, then it
  805. * loops back and reads them again until this criteria is met.
  806. */
  807. vdso_data->tb_orig_stamp = cycle_last;
  808. vdso_data->stamp_xsec = new_stamp_xsec;
  809. vdso_data->tb_to_xs = new_tb_to_xs;
  810. vdso_data->wtom_clock_sec = tk->wall_to_monotonic.tv_sec;
  811. vdso_data->wtom_clock_nsec = tk->wall_to_monotonic.tv_nsec;
  812. vdso_data->stamp_xtime = xt;
  813. vdso_data->stamp_sec_fraction = frac_sec;
  814. smp_wmb();
  815. ++(vdso_data->tb_update_count);
  816. }
  817. void update_vsyscall_tz(void)
  818. {
  819. vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
  820. vdso_data->tz_dsttime = sys_tz.tz_dsttime;
  821. }
  822. static void __init clocksource_init(void)
  823. {
  824. struct clocksource *clock;
  825. if (__USE_RTC())
  826. clock = &clocksource_rtc;
  827. else
  828. clock = &clocksource_timebase;
  829. if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
  830. printk(KERN_ERR "clocksource: %s is already registered\n",
  831. clock->name);
  832. return;
  833. }
  834. printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
  835. clock->name, clock->mult, clock->shift);
  836. }
  837. static int decrementer_set_next_event(unsigned long evt,
  838. struct clock_event_device *dev)
  839. {
  840. __this_cpu_write(decrementers_next_tb, get_tb_or_rtc() + evt);
  841. set_dec(evt);
  842. /* We may have raced with new irq work */
  843. if (test_irq_work_pending())
  844. set_dec(1);
  845. return 0;
  846. }
  847. static int decrementer_shutdown(struct clock_event_device *dev)
  848. {
  849. decrementer_set_next_event(decrementer_max, dev);
  850. return 0;
  851. }
  852. static void register_decrementer_clockevent(int cpu)
  853. {
  854. struct clock_event_device *dec = &per_cpu(decrementers, cpu);
  855. *dec = decrementer_clockevent;
  856. dec->cpumask = cpumask_of(cpu);
  857. clockevents_config_and_register(dec, ppc_tb_freq, 2, decrementer_max);
  858. printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
  859. dec->name, dec->mult, dec->shift, cpu);
  860. /* Set values for KVM, see kvm_emulate_dec() */
  861. decrementer_clockevent.mult = dec->mult;
  862. decrementer_clockevent.shift = dec->shift;
  863. }
  864. static void enable_large_decrementer(void)
  865. {
  866. if (!cpu_has_feature(CPU_FTR_ARCH_300))
  867. return;
  868. if (decrementer_max <= DECREMENTER_DEFAULT_MAX)
  869. return;
  870. /*
  871. * If we're running as the hypervisor we need to enable the LD manually
  872. * otherwise firmware should have done it for us.
  873. */
  874. if (cpu_has_feature(CPU_FTR_HVMODE))
  875. mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) | LPCR_LD);
  876. }
  877. static void __init set_decrementer_max(void)
  878. {
  879. struct device_node *cpu;
  880. u32 bits = 32;
  881. /* Prior to ISAv3 the decrementer is always 32 bit */
  882. if (!cpu_has_feature(CPU_FTR_ARCH_300))
  883. return;
  884. cpu = of_find_node_by_type(NULL, "cpu");
  885. if (of_property_read_u32(cpu, "ibm,dec-bits", &bits) == 0) {
  886. if (bits > 64 || bits < 32) {
  887. pr_warn("time_init: firmware supplied invalid ibm,dec-bits");
  888. bits = 32;
  889. }
  890. /* calculate the signed maximum given this many bits */
  891. decrementer_max = (1ul << (bits - 1)) - 1;
  892. }
  893. of_node_put(cpu);
  894. pr_info("time_init: %u bit decrementer (max: %llx)\n",
  895. bits, decrementer_max);
  896. }
  897. static void __init init_decrementer_clockevent(void)
  898. {
  899. register_decrementer_clockevent(smp_processor_id());
  900. }
  901. void secondary_cpu_time_init(void)
  902. {
  903. /* Enable and test the large decrementer for this cpu */
  904. enable_large_decrementer();
  905. /* Start the decrementer on CPUs that have manual control
  906. * such as BookE
  907. */
  908. start_cpu_decrementer();
  909. /* FIME: Should make unrelatred change to move snapshot_timebase
  910. * call here ! */
  911. register_decrementer_clockevent(smp_processor_id());
  912. }
  913. /* This function is only called on the boot processor */
  914. void __init time_init(void)
  915. {
  916. struct div_result res;
  917. u64 scale;
  918. unsigned shift;
  919. if (__USE_RTC()) {
  920. /* 601 processor: dec counts down by 128 every 128ns */
  921. ppc_tb_freq = 1000000000;
  922. } else {
  923. /* Normal PowerPC with timebase register */
  924. ppc_md.calibrate_decr();
  925. printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
  926. ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
  927. printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
  928. ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
  929. }
  930. tb_ticks_per_jiffy = ppc_tb_freq / HZ;
  931. tb_ticks_per_sec = ppc_tb_freq;
  932. tb_ticks_per_usec = ppc_tb_freq / 1000000;
  933. calc_cputime_factors();
  934. /*
  935. * Compute scale factor for sched_clock.
  936. * The calibrate_decr() function has set tb_ticks_per_sec,
  937. * which is the timebase frequency.
  938. * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
  939. * the 128-bit result as a 64.64 fixed-point number.
  940. * We then shift that number right until it is less than 1.0,
  941. * giving us the scale factor and shift count to use in
  942. * sched_clock().
  943. */
  944. div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
  945. scale = res.result_low;
  946. for (shift = 0; res.result_high != 0; ++shift) {
  947. scale = (scale >> 1) | (res.result_high << 63);
  948. res.result_high >>= 1;
  949. }
  950. tb_to_ns_scale = scale;
  951. tb_to_ns_shift = shift;
  952. /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
  953. boot_tb = get_tb_or_rtc();
  954. /* If platform provided a timezone (pmac), we correct the time */
  955. if (timezone_offset) {
  956. sys_tz.tz_minuteswest = -timezone_offset / 60;
  957. sys_tz.tz_dsttime = 0;
  958. }
  959. vdso_data->tb_update_count = 0;
  960. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  961. /* initialise and enable the large decrementer (if we have one) */
  962. set_decrementer_max();
  963. enable_large_decrementer();
  964. /* Start the decrementer on CPUs that have manual control
  965. * such as BookE
  966. */
  967. start_cpu_decrementer();
  968. /* Register the clocksource */
  969. clocksource_init();
  970. init_decrementer_clockevent();
  971. tick_setup_hrtimer_broadcast();
  972. #ifdef CONFIG_COMMON_CLK
  973. of_clk_init(NULL);
  974. #endif
  975. }
  976. /*
  977. * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
  978. * result.
  979. */
  980. void div128_by_32(u64 dividend_high, u64 dividend_low,
  981. unsigned divisor, struct div_result *dr)
  982. {
  983. unsigned long a, b, c, d;
  984. unsigned long w, x, y, z;
  985. u64 ra, rb, rc;
  986. a = dividend_high >> 32;
  987. b = dividend_high & 0xffffffff;
  988. c = dividend_low >> 32;
  989. d = dividend_low & 0xffffffff;
  990. w = a / divisor;
  991. ra = ((u64)(a - (w * divisor)) << 32) + b;
  992. rb = ((u64) do_div(ra, divisor) << 32) + c;
  993. x = ra;
  994. rc = ((u64) do_div(rb, divisor) << 32) + d;
  995. y = rb;
  996. do_div(rc, divisor);
  997. z = rc;
  998. dr->result_high = ((u64)w << 32) + x;
  999. dr->result_low = ((u64)y << 32) + z;
  1000. }
  1001. /* We don't need to calibrate delay, we use the CPU timebase for that */
  1002. void calibrate_delay(void)
  1003. {
  1004. /* Some generic code (such as spinlock debug) use loops_per_jiffy
  1005. * as the number of __delay(1) in a jiffy, so make it so
  1006. */
  1007. loops_per_jiffy = tb_ticks_per_jiffy;
  1008. }
  1009. #if IS_ENABLED(CONFIG_RTC_DRV_GENERIC)
  1010. static int rtc_generic_get_time(struct device *dev, struct rtc_time *tm)
  1011. {
  1012. ppc_md.get_rtc_time(tm);
  1013. return 0;
  1014. }
  1015. static int rtc_generic_set_time(struct device *dev, struct rtc_time *tm)
  1016. {
  1017. if (!ppc_md.set_rtc_time)
  1018. return -EOPNOTSUPP;
  1019. if (ppc_md.set_rtc_time(tm) < 0)
  1020. return -EOPNOTSUPP;
  1021. return 0;
  1022. }
  1023. static const struct rtc_class_ops rtc_generic_ops = {
  1024. .read_time = rtc_generic_get_time,
  1025. .set_time = rtc_generic_set_time,
  1026. };
  1027. static int __init rtc_init(void)
  1028. {
  1029. struct platform_device *pdev;
  1030. if (!ppc_md.get_rtc_time)
  1031. return -ENODEV;
  1032. pdev = platform_device_register_data(NULL, "rtc-generic", -1,
  1033. &rtc_generic_ops,
  1034. sizeof(rtc_generic_ops));
  1035. return PTR_ERR_OR_ZERO(pdev);
  1036. }
  1037. device_initcall(rtc_init);
  1038. #endif