time.c 31 KB

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