time.c 30 KB

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