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