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