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