xref: /openbmc/linux/arch/powerpc/kernel/time.c (revision e606a2f4)
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 
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  */
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  */
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  */
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 
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 */
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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  */
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 
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 
474 void udelay(unsigned long usecs)
475 {
476 	__delay(tb_ticks_per_usec * usecs);
477 }
478 EXPORT_SYMBOL(udelay);
479 
480 #ifdef CONFIG_SMP
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
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 
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 
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  */
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
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
634 /* Overrides the weak version in kernel/power/main.c */
635 void arch_suspend_disable_irqs(void)
636 {
637 	if (ppc_md.suspend_disable_irqs)
638 		ppc_md.suspend_disable_irqs();
639 
640 	/* Disable the decrementer, so that it doesn't interfere
641 	 * with suspending.
642 	 */
643 
644 	set_dec(decrementer_max);
645 	local_irq_disable();
646 	set_dec(decrementer_max);
647 }
648 
649 /* Overrides the weak version in kernel/power/main.c */
650 void arch_suspend_enable_irqs(void)
651 {
652 	local_irq_enable();
653 
654 	if (ppc_md.suspend_enable_irqs)
655 		ppc_md.suspend_enable_irqs();
656 }
657 #endif
658 
659 unsigned long long tb_to_ns(unsigned long long ticks)
660 {
661 	return mulhdu(ticks, tb_to_ns_scale) << tb_to_ns_shift;
662 }
663 EXPORT_SYMBOL_GPL(tb_to_ns);
664 
665 /*
666  * Scheduler clock - returns current time in nanosec units.
667  *
668  * Note: mulhdu(a, b) (multiply high double unsigned) returns
669  * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
670  * are 64-bit unsigned numbers.
671  */
672 notrace unsigned long long sched_clock(void)
673 {
674 	return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
675 }
676 
677 
678 #ifdef CONFIG_PPC_PSERIES
679 
680 /*
681  * Running clock - attempts to give a view of time passing for a virtualised
682  * kernels.
683  * Uses the VTB register if available otherwise a next best guess.
684  */
685 unsigned long long running_clock(void)
686 {
687 	/*
688 	 * Don't read the VTB as a host since KVM does not switch in host
689 	 * timebase into the VTB when it takes a guest off the CPU, reading the
690 	 * VTB would result in reading 'last switched out' guest VTB.
691 	 *
692 	 * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
693 	 * would be unsafe to rely only on the #ifdef above.
694 	 */
695 	if (firmware_has_feature(FW_FEATURE_LPAR) &&
696 	    cpu_has_feature(CPU_FTR_ARCH_207S))
697 		return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
698 
699 	/*
700 	 * This is a next best approximation without a VTB.
701 	 * On a host which is running bare metal there should never be any stolen
702 	 * time and on a host which doesn't do any virtualisation TB *should* equal
703 	 * VTB so it makes no difference anyway.
704 	 */
705 	return local_clock() - kcpustat_this_cpu->cpustat[CPUTIME_STEAL];
706 }
707 #endif
708 
709 static int __init get_freq(char *name, int cells, unsigned long *val)
710 {
711 	struct device_node *cpu;
712 	const __be32 *fp;
713 	int found = 0;
714 
715 	/* The cpu node should have timebase and clock frequency properties */
716 	cpu = of_find_node_by_type(NULL, "cpu");
717 
718 	if (cpu) {
719 		fp = of_get_property(cpu, name, NULL);
720 		if (fp) {
721 			found = 1;
722 			*val = of_read_ulong(fp, cells);
723 		}
724 
725 		of_node_put(cpu);
726 	}
727 
728 	return found;
729 }
730 
731 static void start_cpu_decrementer(void)
732 {
733 #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
734 	unsigned int tcr;
735 
736 	/* Clear any pending timer interrupts */
737 	mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
738 
739 	tcr = mfspr(SPRN_TCR);
740 	/*
741 	 * The watchdog may have already been enabled by u-boot. So leave
742 	 * TRC[WP] (Watchdog Period) alone.
743 	 */
744 	tcr &= TCR_WP_MASK;	/* Clear all bits except for TCR[WP] */
745 	tcr |= TCR_DIE;		/* Enable decrementer */
746 	mtspr(SPRN_TCR, tcr);
747 #endif
748 }
749 
750 void __init generic_calibrate_decr(void)
751 {
752 	ppc_tb_freq = DEFAULT_TB_FREQ;		/* hardcoded default */
753 
754 	if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
755 	    !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
756 
757 		printk(KERN_ERR "WARNING: Estimating decrementer frequency "
758 				"(not found)\n");
759 	}
760 
761 	ppc_proc_freq = DEFAULT_PROC_FREQ;	/* hardcoded default */
762 
763 	if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
764 	    !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
765 
766 		printk(KERN_ERR "WARNING: Estimating processor frequency "
767 				"(not found)\n");
768 	}
769 }
770 
771 int update_persistent_clock64(struct timespec64 now)
772 {
773 	struct rtc_time tm;
774 
775 	if (!ppc_md.set_rtc_time)
776 		return -ENODEV;
777 
778 	rtc_time64_to_tm(now.tv_sec + 1 + timezone_offset, &tm);
779 
780 	return ppc_md.set_rtc_time(&tm);
781 }
782 
783 static void __read_persistent_clock(struct timespec64 *ts)
784 {
785 	struct rtc_time tm;
786 	static int first = 1;
787 
788 	ts->tv_nsec = 0;
789 	/* XXX this is a litle fragile but will work okay in the short term */
790 	if (first) {
791 		first = 0;
792 		if (ppc_md.time_init)
793 			timezone_offset = ppc_md.time_init();
794 
795 		/* get_boot_time() isn't guaranteed to be safe to call late */
796 		if (ppc_md.get_boot_time) {
797 			ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
798 			return;
799 		}
800 	}
801 	if (!ppc_md.get_rtc_time) {
802 		ts->tv_sec = 0;
803 		return;
804 	}
805 	ppc_md.get_rtc_time(&tm);
806 
807 	ts->tv_sec = rtc_tm_to_time64(&tm);
808 }
809 
810 void read_persistent_clock64(struct timespec64 *ts)
811 {
812 	__read_persistent_clock(ts);
813 
814 	/* Sanitize it in case real time clock is set below EPOCH */
815 	if (ts->tv_sec < 0) {
816 		ts->tv_sec = 0;
817 		ts->tv_nsec = 0;
818 	}
819 
820 }
821 
822 /* clocksource code */
823 static notrace u64 timebase_read(struct clocksource *cs)
824 {
825 	return (u64)get_tb();
826 }
827 
828 static void __init clocksource_init(void)
829 {
830 	struct clocksource *clock = &clocksource_timebase;
831 
832 	if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
833 		printk(KERN_ERR "clocksource: %s is already registered\n",
834 		       clock->name);
835 		return;
836 	}
837 
838 	printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
839 	       clock->name, clock->mult, clock->shift);
840 }
841 
842 static int decrementer_set_next_event(unsigned long evt,
843 				      struct clock_event_device *dev)
844 {
845 	__this_cpu_write(decrementers_next_tb, get_tb() + evt);
846 	set_dec(evt);
847 
848 	/* We may have raced with new irq work */
849 	if (test_irq_work_pending())
850 		set_dec(1);
851 
852 	return 0;
853 }
854 
855 static int decrementer_shutdown(struct clock_event_device *dev)
856 {
857 	decrementer_set_next_event(decrementer_max, dev);
858 	return 0;
859 }
860 
861 static void register_decrementer_clockevent(int cpu)
862 {
863 	struct clock_event_device *dec = &per_cpu(decrementers, cpu);
864 
865 	*dec = decrementer_clockevent;
866 	dec->cpumask = cpumask_of(cpu);
867 
868 	clockevents_config_and_register(dec, ppc_tb_freq, 2, decrementer_max);
869 
870 	printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
871 		    dec->name, dec->mult, dec->shift, cpu);
872 
873 	/* Set values for KVM, see kvm_emulate_dec() */
874 	decrementer_clockevent.mult = dec->mult;
875 	decrementer_clockevent.shift = dec->shift;
876 }
877 
878 static void enable_large_decrementer(void)
879 {
880 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
881 		return;
882 
883 	if (decrementer_max <= DECREMENTER_DEFAULT_MAX)
884 		return;
885 
886 	/*
887 	 * If we're running as the hypervisor we need to enable the LD manually
888 	 * otherwise firmware should have done it for us.
889 	 */
890 	if (cpu_has_feature(CPU_FTR_HVMODE))
891 		mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) | LPCR_LD);
892 }
893 
894 static void __init set_decrementer_max(void)
895 {
896 	struct device_node *cpu;
897 	u32 bits = 32;
898 
899 	/* Prior to ISAv3 the decrementer is always 32 bit */
900 	if (!cpu_has_feature(CPU_FTR_ARCH_300))
901 		return;
902 
903 	cpu = of_find_node_by_type(NULL, "cpu");
904 
905 	if (of_property_read_u32(cpu, "ibm,dec-bits", &bits) == 0) {
906 		if (bits > 64 || bits < 32) {
907 			pr_warn("time_init: firmware supplied invalid ibm,dec-bits");
908 			bits = 32;
909 		}
910 
911 		/* calculate the signed maximum given this many bits */
912 		decrementer_max = (1ul << (bits - 1)) - 1;
913 	}
914 
915 	of_node_put(cpu);
916 
917 	pr_info("time_init: %u bit decrementer (max: %llx)\n",
918 		bits, decrementer_max);
919 }
920 
921 static void __init init_decrementer_clockevent(void)
922 {
923 	register_decrementer_clockevent(smp_processor_id());
924 }
925 
926 void secondary_cpu_time_init(void)
927 {
928 	/* Enable and test the large decrementer for this cpu */
929 	enable_large_decrementer();
930 
931 	/* Start the decrementer on CPUs that have manual control
932 	 * such as BookE
933 	 */
934 	start_cpu_decrementer();
935 
936 	/* FIME: Should make unrelatred change to move snapshot_timebase
937 	 * call here ! */
938 	register_decrementer_clockevent(smp_processor_id());
939 }
940 
941 /* This function is only called on the boot processor */
942 void __init time_init(void)
943 {
944 	struct div_result res;
945 	u64 scale;
946 	unsigned shift;
947 
948 	/* Normal PowerPC with timebase register */
949 	ppc_md.calibrate_decr();
950 	printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
951 	       ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
952 	printk(KERN_DEBUG "time_init: processor frequency   = %lu.%.6lu MHz\n",
953 	       ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
954 
955 	tb_ticks_per_jiffy = ppc_tb_freq / HZ;
956 	tb_ticks_per_sec = ppc_tb_freq;
957 	tb_ticks_per_usec = ppc_tb_freq / 1000000;
958 	calc_cputime_factors();
959 
960 	/*
961 	 * Compute scale factor for sched_clock.
962 	 * The calibrate_decr() function has set tb_ticks_per_sec,
963 	 * which is the timebase frequency.
964 	 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
965 	 * the 128-bit result as a 64.64 fixed-point number.
966 	 * We then shift that number right until it is less than 1.0,
967 	 * giving us the scale factor and shift count to use in
968 	 * sched_clock().
969 	 */
970 	div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
971 	scale = res.result_low;
972 	for (shift = 0; res.result_high != 0; ++shift) {
973 		scale = (scale >> 1) | (res.result_high << 63);
974 		res.result_high >>= 1;
975 	}
976 	tb_to_ns_scale = scale;
977 	tb_to_ns_shift = shift;
978 	/* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
979 	boot_tb = get_tb();
980 
981 	/* If platform provided a timezone (pmac), we correct the time */
982 	if (timezone_offset) {
983 		sys_tz.tz_minuteswest = -timezone_offset / 60;
984 		sys_tz.tz_dsttime = 0;
985 	}
986 
987 	vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
988 
989 	/* initialise and enable the large decrementer (if we have one) */
990 	set_decrementer_max();
991 	enable_large_decrementer();
992 
993 	/* Start the decrementer on CPUs that have manual control
994 	 * such as BookE
995 	 */
996 	start_cpu_decrementer();
997 
998 	/* Register the clocksource */
999 	clocksource_init();
1000 
1001 	init_decrementer_clockevent();
1002 	tick_setup_hrtimer_broadcast();
1003 
1004 	of_clk_init(NULL);
1005 	enable_sched_clock_irqtime();
1006 }
1007 
1008 /*
1009  * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1010  * result.
1011  */
1012 void div128_by_32(u64 dividend_high, u64 dividend_low,
1013 		  unsigned divisor, struct div_result *dr)
1014 {
1015 	unsigned long a, b, c, d;
1016 	unsigned long w, x, y, z;
1017 	u64 ra, rb, rc;
1018 
1019 	a = dividend_high >> 32;
1020 	b = dividend_high & 0xffffffff;
1021 	c = dividend_low >> 32;
1022 	d = dividend_low & 0xffffffff;
1023 
1024 	w = a / divisor;
1025 	ra = ((u64)(a - (w * divisor)) << 32) + b;
1026 
1027 	rb = ((u64) do_div(ra, divisor) << 32) + c;
1028 	x = ra;
1029 
1030 	rc = ((u64) do_div(rb, divisor) << 32) + d;
1031 	y = rb;
1032 
1033 	do_div(rc, divisor);
1034 	z = rc;
1035 
1036 	dr->result_high = ((u64)w << 32) + x;
1037 	dr->result_low  = ((u64)y << 32) + z;
1038 
1039 }
1040 
1041 /* We don't need to calibrate delay, we use the CPU timebase for that */
1042 void calibrate_delay(void)
1043 {
1044 	/* Some generic code (such as spinlock debug) use loops_per_jiffy
1045 	 * as the number of __delay(1) in a jiffy, so make it so
1046 	 */
1047 	loops_per_jiffy = tb_ticks_per_jiffy;
1048 }
1049 
1050 #if IS_ENABLED(CONFIG_RTC_DRV_GENERIC)
1051 static int rtc_generic_get_time(struct device *dev, struct rtc_time *tm)
1052 {
1053 	ppc_md.get_rtc_time(tm);
1054 	return 0;
1055 }
1056 
1057 static int rtc_generic_set_time(struct device *dev, struct rtc_time *tm)
1058 {
1059 	if (!ppc_md.set_rtc_time)
1060 		return -EOPNOTSUPP;
1061 
1062 	if (ppc_md.set_rtc_time(tm) < 0)
1063 		return -EOPNOTSUPP;
1064 
1065 	return 0;
1066 }
1067 
1068 static const struct rtc_class_ops rtc_generic_ops = {
1069 	.read_time = rtc_generic_get_time,
1070 	.set_time = rtc_generic_set_time,
1071 };
1072 
1073 static int __init rtc_init(void)
1074 {
1075 	struct platform_device *pdev;
1076 
1077 	if (!ppc_md.get_rtc_time)
1078 		return -ENODEV;
1079 
1080 	pdev = platform_device_register_data(NULL, "rtc-generic", -1,
1081 					     &rtc_generic_ops,
1082 					     sizeof(rtc_generic_ops));
1083 
1084 	return PTR_ERR_OR_ZERO(pdev);
1085 }
1086 
1087 device_initcall(rtc_init);
1088 #endif
1089