time.c 32 KB

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