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