xref: /openbmc/linux/arch/powerpc/kernel/time.c (revision d894fc60)
1 /*
2  * Common time routines among all ppc machines.
3  *
4  * Written by Cort Dougan (cort@cs.nmt.edu) to merge
5  * Paul Mackerras' version and mine for PReP and Pmac.
6  * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
7  * Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
8  *
9  * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
10  * to make clock more stable (2.4.0-test5). The only thing
11  * that this code assumes is that the timebases have been synchronized
12  * by firmware on SMP and are never stopped (never do sleep
13  * on SMP then, nap and doze are OK).
14  *
15  * Speeded up do_gettimeofday by getting rid of references to
16  * xtime (which required locks for consistency). (mikejc@us.ibm.com)
17  *
18  * TODO (not necessarily in this file):
19  * - improve precision and reproducibility of timebase frequency
20  * measurement at boot time.
21  * - for astronomical applications: add a new function to get
22  * non ambiguous timestamps even around leap seconds. This needs
23  * a new timestamp format and a good name.
24  *
25  * 1997-09-10  Updated NTP code according to technical memorandum Jan '96
26  *             "A Kernel Model for Precision Timekeeping" by Dave Mills
27  *
28  *      This program is free software; you can redistribute it and/or
29  *      modify it under the terms of the GNU General Public License
30  *      as published by the Free Software Foundation; either version
31  *      2 of the License, or (at your option) any later version.
32  */
33 
34 #include <linux/errno.h>
35 #include <linux/export.h>
36 #include <linux/sched.h>
37 #include <linux/kernel.h>
38 #include <linux/param.h>
39 #include <linux/string.h>
40 #include <linux/mm.h>
41 #include <linux/interrupt.h>
42 #include <linux/timex.h>
43 #include <linux/kernel_stat.h>
44 #include <linux/time.h>
45 #include <linux/clockchips.h>
46 #include <linux/init.h>
47 #include <linux/profile.h>
48 #include <linux/cpu.h>
49 #include <linux/security.h>
50 #include <linux/percpu.h>
51 #include <linux/rtc.h>
52 #include <linux/jiffies.h>
53 #include <linux/posix-timers.h>
54 #include <linux/irq.h>
55 #include <linux/delay.h>
56 #include <linux/irq_work.h>
57 #include <linux/clk-provider.h>
58 #include <asm/trace.h>
59 
60 #include <asm/io.h>
61 #include <asm/processor.h>
62 #include <asm/nvram.h>
63 #include <asm/cache.h>
64 #include <asm/machdep.h>
65 #include <asm/uaccess.h>
66 #include <asm/time.h>
67 #include <asm/prom.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/cputime.h>
74 
75 /* powerpc clocksource/clockevent code */
76 
77 #include <linux/clockchips.h>
78 #include <linux/timekeeper_internal.h>
79 
80 static cycle_t rtc_read(struct clocksource *);
81 static struct clocksource clocksource_rtc = {
82 	.name         = "rtc",
83 	.rating       = 400,
84 	.flags        = CLOCK_SOURCE_IS_CONTINUOUS,
85 	.mask         = CLOCKSOURCE_MASK(64),
86 	.read         = rtc_read,
87 };
88 
89 static cycle_t timebase_read(struct clocksource *);
90 static struct clocksource clocksource_timebase = {
91 	.name         = "timebase",
92 	.rating       = 400,
93 	.flags        = CLOCK_SOURCE_IS_CONTINUOUS,
94 	.mask         = CLOCKSOURCE_MASK(64),
95 	.read         = timebase_read,
96 };
97 
98 #define DECREMENTER_MAX	0x7fffffff
99 
100 static int decrementer_set_next_event(unsigned long evt,
101 				      struct clock_event_device *dev);
102 static void decrementer_set_mode(enum clock_event_mode mode,
103 				 struct clock_event_device *dev);
104 
105 struct clock_event_device decrementer_clockevent = {
106 	.name           = "decrementer",
107 	.rating         = 200,
108 	.irq            = 0,
109 	.set_next_event = decrementer_set_next_event,
110 	.set_mode       = decrementer_set_mode,
111 	.features       = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_C3STOP,
112 };
113 EXPORT_SYMBOL(decrementer_clockevent);
114 
115 DEFINE_PER_CPU(u64, decrementers_next_tb);
116 static DEFINE_PER_CPU(struct clock_event_device, decrementers);
117 
118 #define XSEC_PER_SEC (1024*1024)
119 
120 #ifdef CONFIG_PPC64
121 #define SCALE_XSEC(xsec, max)	(((xsec) * max) / XSEC_PER_SEC)
122 #else
123 /* compute ((xsec << 12) * max) >> 32 */
124 #define SCALE_XSEC(xsec, max)	mulhwu((xsec) << 12, max)
125 #endif
126 
127 unsigned long tb_ticks_per_jiffy;
128 unsigned long tb_ticks_per_usec = 100; /* sane default */
129 EXPORT_SYMBOL(tb_ticks_per_usec);
130 unsigned long tb_ticks_per_sec;
131 EXPORT_SYMBOL(tb_ticks_per_sec);	/* for cputime_t conversions */
132 
133 DEFINE_SPINLOCK(rtc_lock);
134 EXPORT_SYMBOL_GPL(rtc_lock);
135 
136 static u64 tb_to_ns_scale __read_mostly;
137 static unsigned tb_to_ns_shift __read_mostly;
138 static u64 boot_tb __read_mostly;
139 
140 extern struct timezone sys_tz;
141 static long timezone_offset;
142 
143 unsigned long ppc_proc_freq;
144 EXPORT_SYMBOL_GPL(ppc_proc_freq);
145 unsigned long ppc_tb_freq;
146 EXPORT_SYMBOL_GPL(ppc_tb_freq);
147 
148 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
149 /*
150  * Factors for converting from cputime_t (timebase ticks) to
151  * jiffies, microseconds, seconds, and clock_t (1/USER_HZ seconds).
152  * These are all stored as 0.64 fixed-point binary fractions.
153  */
154 u64 __cputime_jiffies_factor;
155 EXPORT_SYMBOL(__cputime_jiffies_factor);
156 u64 __cputime_usec_factor;
157 EXPORT_SYMBOL(__cputime_usec_factor);
158 u64 __cputime_sec_factor;
159 EXPORT_SYMBOL(__cputime_sec_factor);
160 u64 __cputime_clockt_factor;
161 EXPORT_SYMBOL(__cputime_clockt_factor);
162 DEFINE_PER_CPU(unsigned long, cputime_last_delta);
163 DEFINE_PER_CPU(unsigned long, cputime_scaled_last_delta);
164 
165 cputime_t cputime_one_jiffy;
166 
167 void (*dtl_consumer)(struct dtl_entry *, u64);
168 
169 static void calc_cputime_factors(void)
170 {
171 	struct div_result res;
172 
173 	div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
174 	__cputime_jiffies_factor = res.result_low;
175 	div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
176 	__cputime_usec_factor = res.result_low;
177 	div128_by_32(1, 0, tb_ticks_per_sec, &res);
178 	__cputime_sec_factor = res.result_low;
179 	div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
180 	__cputime_clockt_factor = res.result_low;
181 }
182 
183 /*
184  * Read the SPURR on systems that have it, otherwise the PURR,
185  * or if that doesn't exist return the timebase value passed in.
186  */
187 static u64 read_spurr(u64 tb)
188 {
189 	if (cpu_has_feature(CPU_FTR_SPURR))
190 		return mfspr(SPRN_SPURR);
191 	if (cpu_has_feature(CPU_FTR_PURR))
192 		return mfspr(SPRN_PURR);
193 	return tb;
194 }
195 
196 #ifdef CONFIG_PPC_SPLPAR
197 
198 /*
199  * Scan the dispatch trace log and count up the stolen time.
200  * Should be called with interrupts disabled.
201  */
202 static u64 scan_dispatch_log(u64 stop_tb)
203 {
204 	u64 i = local_paca->dtl_ridx;
205 	struct dtl_entry *dtl = local_paca->dtl_curr;
206 	struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
207 	struct lppaca *vpa = local_paca->lppaca_ptr;
208 	u64 tb_delta;
209 	u64 stolen = 0;
210 	u64 dtb;
211 
212 	if (!dtl)
213 		return 0;
214 
215 	if (i == be64_to_cpu(vpa->dtl_idx))
216 		return 0;
217 	while (i < be64_to_cpu(vpa->dtl_idx)) {
218 		dtb = be64_to_cpu(dtl->timebase);
219 		tb_delta = be32_to_cpu(dtl->enqueue_to_dispatch_time) +
220 			be32_to_cpu(dtl->ready_to_enqueue_time);
221 		barrier();
222 		if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
223 			/* buffer has overflowed */
224 			i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
225 			dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
226 			continue;
227 		}
228 		if (dtb > stop_tb)
229 			break;
230 		if (dtl_consumer)
231 			dtl_consumer(dtl, i);
232 		stolen += tb_delta;
233 		++i;
234 		++dtl;
235 		if (dtl == dtl_end)
236 			dtl = local_paca->dispatch_log;
237 	}
238 	local_paca->dtl_ridx = i;
239 	local_paca->dtl_curr = dtl;
240 	return stolen;
241 }
242 
243 /*
244  * Accumulate stolen time by scanning the dispatch trace log.
245  * Called on entry from user mode.
246  */
247 void accumulate_stolen_time(void)
248 {
249 	u64 sst, ust;
250 
251 	u8 save_soft_enabled = local_paca->soft_enabled;
252 
253 	/* We are called early in the exception entry, before
254 	 * soft/hard_enabled are sync'ed to the expected state
255 	 * for the exception. We are hard disabled but the PACA
256 	 * needs to reflect that so various debug stuff doesn't
257 	 * complain
258 	 */
259 	local_paca->soft_enabled = 0;
260 
261 	sst = scan_dispatch_log(local_paca->starttime_user);
262 	ust = scan_dispatch_log(local_paca->starttime);
263 	local_paca->system_time -= sst;
264 	local_paca->user_time -= ust;
265 	local_paca->stolen_time += ust + sst;
266 
267 	local_paca->soft_enabled = save_soft_enabled;
268 }
269 
270 static inline u64 calculate_stolen_time(u64 stop_tb)
271 {
272 	u64 stolen = 0;
273 
274 	if (get_paca()->dtl_ridx != be64_to_cpu(get_lppaca()->dtl_idx)) {
275 		stolen = scan_dispatch_log(stop_tb);
276 		get_paca()->system_time -= stolen;
277 	}
278 
279 	stolen += get_paca()->stolen_time;
280 	get_paca()->stolen_time = 0;
281 	return stolen;
282 }
283 
284 #else /* CONFIG_PPC_SPLPAR */
285 static inline u64 calculate_stolen_time(u64 stop_tb)
286 {
287 	return 0;
288 }
289 
290 #endif /* CONFIG_PPC_SPLPAR */
291 
292 /*
293  * Account time for a transition between system, hard irq
294  * or soft irq state.
295  */
296 static u64 vtime_delta(struct task_struct *tsk,
297 			u64 *sys_scaled, u64 *stolen)
298 {
299 	u64 now, nowscaled, deltascaled;
300 	u64 udelta, delta, user_scaled;
301 
302 	WARN_ON_ONCE(!irqs_disabled());
303 
304 	now = mftb();
305 	nowscaled = read_spurr(now);
306 	get_paca()->system_time += now - get_paca()->starttime;
307 	get_paca()->starttime = now;
308 	deltascaled = nowscaled - get_paca()->startspurr;
309 	get_paca()->startspurr = nowscaled;
310 
311 	*stolen = calculate_stolen_time(now);
312 
313 	delta = get_paca()->system_time;
314 	get_paca()->system_time = 0;
315 	udelta = get_paca()->user_time - get_paca()->utime_sspurr;
316 	get_paca()->utime_sspurr = get_paca()->user_time;
317 
318 	/*
319 	 * Because we don't read the SPURR on every kernel entry/exit,
320 	 * deltascaled includes both user and system SPURR ticks.
321 	 * Apportion these ticks to system SPURR ticks and user
322 	 * SPURR ticks in the same ratio as the system time (delta)
323 	 * and user time (udelta) values obtained from the timebase
324 	 * over the same interval.  The system ticks get accounted here;
325 	 * the user ticks get saved up in paca->user_time_scaled to be
326 	 * used by account_process_tick.
327 	 */
328 	*sys_scaled = delta;
329 	user_scaled = udelta;
330 	if (deltascaled != delta + udelta) {
331 		if (udelta) {
332 			*sys_scaled = deltascaled * delta / (delta + udelta);
333 			user_scaled = deltascaled - *sys_scaled;
334 		} else {
335 			*sys_scaled = deltascaled;
336 		}
337 	}
338 	get_paca()->user_time_scaled += user_scaled;
339 
340 	return delta;
341 }
342 
343 void vtime_account_system(struct task_struct *tsk)
344 {
345 	u64 delta, sys_scaled, stolen;
346 
347 	delta = vtime_delta(tsk, &sys_scaled, &stolen);
348 	account_system_time(tsk, 0, delta, sys_scaled);
349 	if (stolen)
350 		account_steal_time(stolen);
351 }
352 EXPORT_SYMBOL_GPL(vtime_account_system);
353 
354 void vtime_account_idle(struct task_struct *tsk)
355 {
356 	u64 delta, sys_scaled, stolen;
357 
358 	delta = vtime_delta(tsk, &sys_scaled, &stolen);
359 	account_idle_time(delta + stolen);
360 }
361 
362 /*
363  * Transfer the user time accumulated in the paca
364  * by the exception entry and exit code to the generic
365  * process user time records.
366  * Must be called with interrupts disabled.
367  * Assumes that vtime_account_system/idle() has been called
368  * recently (i.e. since the last entry from usermode) so that
369  * get_paca()->user_time_scaled is up to date.
370  */
371 void vtime_account_user(struct task_struct *tsk)
372 {
373 	cputime_t utime, utimescaled;
374 
375 	utime = get_paca()->user_time;
376 	utimescaled = get_paca()->user_time_scaled;
377 	get_paca()->user_time = 0;
378 	get_paca()->user_time_scaled = 0;
379 	get_paca()->utime_sspurr = 0;
380 	account_user_time(tsk, utime, utimescaled);
381 }
382 
383 #else /* ! CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
384 #define calc_cputime_factors()
385 #endif
386 
387 void __delay(unsigned long loops)
388 {
389 	unsigned long start;
390 	int diff;
391 
392 	if (__USE_RTC()) {
393 		start = get_rtcl();
394 		do {
395 			/* the RTCL register wraps at 1000000000 */
396 			diff = get_rtcl() - start;
397 			if (diff < 0)
398 				diff += 1000000000;
399 		} while (diff < loops);
400 	} else {
401 		start = get_tbl();
402 		while (get_tbl() - start < loops)
403 			HMT_low();
404 		HMT_medium();
405 	}
406 }
407 EXPORT_SYMBOL(__delay);
408 
409 void udelay(unsigned long usecs)
410 {
411 	__delay(tb_ticks_per_usec * usecs);
412 }
413 EXPORT_SYMBOL(udelay);
414 
415 #ifdef CONFIG_SMP
416 unsigned long profile_pc(struct pt_regs *regs)
417 {
418 	unsigned long pc = instruction_pointer(regs);
419 
420 	if (in_lock_functions(pc))
421 		return regs->link;
422 
423 	return pc;
424 }
425 EXPORT_SYMBOL(profile_pc);
426 #endif
427 
428 #ifdef CONFIG_IRQ_WORK
429 
430 /*
431  * 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
432  */
433 #ifdef CONFIG_PPC64
434 static inline unsigned long test_irq_work_pending(void)
435 {
436 	unsigned long x;
437 
438 	asm volatile("lbz %0,%1(13)"
439 		: "=r" (x)
440 		: "i" (offsetof(struct paca_struct, irq_work_pending)));
441 	return x;
442 }
443 
444 static inline void set_irq_work_pending_flag(void)
445 {
446 	asm volatile("stb %0,%1(13)" : :
447 		"r" (1),
448 		"i" (offsetof(struct paca_struct, irq_work_pending)));
449 }
450 
451 static inline void clear_irq_work_pending(void)
452 {
453 	asm volatile("stb %0,%1(13)" : :
454 		"r" (0),
455 		"i" (offsetof(struct paca_struct, irq_work_pending)));
456 }
457 
458 #else /* 32-bit */
459 
460 DEFINE_PER_CPU(u8, irq_work_pending);
461 
462 #define set_irq_work_pending_flag()	__this_cpu_write(irq_work_pending, 1)
463 #define test_irq_work_pending()		__this_cpu_read(irq_work_pending)
464 #define clear_irq_work_pending()	__this_cpu_write(irq_work_pending, 0)
465 
466 #endif /* 32 vs 64 bit */
467 
468 void arch_irq_work_raise(void)
469 {
470 	preempt_disable();
471 	set_irq_work_pending_flag();
472 	set_dec(1);
473 	preempt_enable();
474 }
475 
476 #else  /* CONFIG_IRQ_WORK */
477 
478 #define test_irq_work_pending()	0
479 #define clear_irq_work_pending()
480 
481 #endif /* CONFIG_IRQ_WORK */
482 
483 static void __timer_interrupt(void)
484 {
485 	struct pt_regs *regs = get_irq_regs();
486 	u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
487 	struct clock_event_device *evt = this_cpu_ptr(&decrementers);
488 	u64 now;
489 
490 	trace_timer_interrupt_entry(regs);
491 
492 	if (test_irq_work_pending()) {
493 		clear_irq_work_pending();
494 		irq_work_run();
495 	}
496 
497 	now = get_tb_or_rtc();
498 	if (now >= *next_tb) {
499 		*next_tb = ~(u64)0;
500 		if (evt->event_handler)
501 			evt->event_handler(evt);
502 		__this_cpu_inc(irq_stat.timer_irqs_event);
503 	} else {
504 		now = *next_tb - now;
505 		if (now <= DECREMENTER_MAX)
506 			set_dec((int)now);
507 		/* We may have raced with new irq work */
508 		if (test_irq_work_pending())
509 			set_dec(1);
510 		__this_cpu_inc(irq_stat.timer_irqs_others);
511 	}
512 
513 #ifdef CONFIG_PPC64
514 	/* collect purr register values often, for accurate calculations */
515 	if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
516 		struct cpu_usage *cu = this_cpu_ptr(&cpu_usage_array);
517 		cu->current_tb = mfspr(SPRN_PURR);
518 	}
519 #endif
520 
521 	trace_timer_interrupt_exit(regs);
522 }
523 
524 /*
525  * timer_interrupt - gets called when the decrementer overflows,
526  * with interrupts disabled.
527  */
528 void timer_interrupt(struct pt_regs * regs)
529 {
530 	struct pt_regs *old_regs;
531 	u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
532 
533 	/* Ensure a positive value is written to the decrementer, or else
534 	 * some CPUs will continue to take decrementer exceptions.
535 	 */
536 	set_dec(DECREMENTER_MAX);
537 
538 	/* Some implementations of hotplug will get timer interrupts while
539 	 * offline, just ignore these and we also need to set
540 	 * decrementers_next_tb as MAX to make sure __check_irq_replay
541 	 * don't replay timer interrupt when return, otherwise we'll trap
542 	 * here infinitely :(
543 	 */
544 	if (!cpu_online(smp_processor_id())) {
545 		*next_tb = ~(u64)0;
546 		return;
547 	}
548 
549 	/* Conditionally hard-enable interrupts now that the DEC has been
550 	 * bumped to its maximum value
551 	 */
552 	may_hard_irq_enable();
553 
554 
555 #if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
556 	if (atomic_read(&ppc_n_lost_interrupts) != 0)
557 		do_IRQ(regs);
558 #endif
559 
560 	old_regs = set_irq_regs(regs);
561 	irq_enter();
562 
563 	__timer_interrupt();
564 	irq_exit();
565 	set_irq_regs(old_regs);
566 }
567 
568 /*
569  * Hypervisor decrementer interrupts shouldn't occur but are sometimes
570  * left pending on exit from a KVM guest.  We don't need to do anything
571  * to clear them, as they are edge-triggered.
572  */
573 void hdec_interrupt(struct pt_regs *regs)
574 {
575 }
576 
577 #ifdef CONFIG_SUSPEND
578 static void generic_suspend_disable_irqs(void)
579 {
580 	/* Disable the decrementer, so that it doesn't interfere
581 	 * with suspending.
582 	 */
583 
584 	set_dec(DECREMENTER_MAX);
585 	local_irq_disable();
586 	set_dec(DECREMENTER_MAX);
587 }
588 
589 static void generic_suspend_enable_irqs(void)
590 {
591 	local_irq_enable();
592 }
593 
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 	generic_suspend_disable_irqs();
600 }
601 
602 /* Overrides the weak version in kernel/power/main.c */
603 void arch_suspend_enable_irqs(void)
604 {
605 	generic_suspend_enable_irqs();
606 	if (ppc_md.suspend_enable_irqs)
607 		ppc_md.suspend_enable_irqs();
608 }
609 #endif
610 
611 /*
612  * Scheduler clock - returns current time in nanosec units.
613  *
614  * Note: mulhdu(a, b) (multiply high double unsigned) returns
615  * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
616  * are 64-bit unsigned numbers.
617  */
618 unsigned long long sched_clock(void)
619 {
620 	if (__USE_RTC())
621 		return get_rtc();
622 	return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
623 }
624 
625 
626 #ifdef CONFIG_PPC_PSERIES
627 
628 /*
629  * Running clock - attempts to give a view of time passing for a virtualised
630  * kernels.
631  * Uses the VTB register if available otherwise a next best guess.
632  */
633 unsigned long long running_clock(void)
634 {
635 	/*
636 	 * Don't read the VTB as a host since KVM does not switch in host
637 	 * timebase into the VTB when it takes a guest off the CPU, reading the
638 	 * VTB would result in reading 'last switched out' guest VTB.
639 	 *
640 	 * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
641 	 * would be unsafe to rely only on the #ifdef above.
642 	 */
643 	if (firmware_has_feature(FW_FEATURE_LPAR) &&
644 	    cpu_has_feature(CPU_FTR_ARCH_207S))
645 		return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
646 
647 	/*
648 	 * This is a next best approximation without a VTB.
649 	 * On a host which is running bare metal there should never be any stolen
650 	 * time and on a host which doesn't do any virtualisation TB *should* equal
651 	 * VTB so it makes no difference anyway.
652 	 */
653 	return local_clock() - cputime_to_nsecs(kcpustat_this_cpu->cpustat[CPUTIME_STEAL]);
654 }
655 #endif
656 
657 static int __init get_freq(char *name, int cells, unsigned long *val)
658 {
659 	struct device_node *cpu;
660 	const __be32 *fp;
661 	int found = 0;
662 
663 	/* The cpu node should have timebase and clock frequency properties */
664 	cpu = of_find_node_by_type(NULL, "cpu");
665 
666 	if (cpu) {
667 		fp = of_get_property(cpu, name, NULL);
668 		if (fp) {
669 			found = 1;
670 			*val = of_read_ulong(fp, cells);
671 		}
672 
673 		of_node_put(cpu);
674 	}
675 
676 	return found;
677 }
678 
679 static void start_cpu_decrementer(void)
680 {
681 #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
682 	/* Clear any pending timer interrupts */
683 	mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
684 
685 	/* Enable decrementer interrupt */
686 	mtspr(SPRN_TCR, TCR_DIE);
687 #endif /* defined(CONFIG_BOOKE) || defined(CONFIG_40x) */
688 }
689 
690 void __init generic_calibrate_decr(void)
691 {
692 	ppc_tb_freq = DEFAULT_TB_FREQ;		/* hardcoded default */
693 
694 	if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
695 	    !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
696 
697 		printk(KERN_ERR "WARNING: Estimating decrementer frequency "
698 				"(not found)\n");
699 	}
700 
701 	ppc_proc_freq = DEFAULT_PROC_FREQ;	/* hardcoded default */
702 
703 	if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
704 	    !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
705 
706 		printk(KERN_ERR "WARNING: Estimating processor frequency "
707 				"(not found)\n");
708 	}
709 }
710 
711 int update_persistent_clock(struct timespec now)
712 {
713 	struct rtc_time tm;
714 
715 	if (!ppc_md.set_rtc_time)
716 		return -ENODEV;
717 
718 	to_tm(now.tv_sec + 1 + timezone_offset, &tm);
719 	tm.tm_year -= 1900;
720 	tm.tm_mon -= 1;
721 
722 	return ppc_md.set_rtc_time(&tm);
723 }
724 
725 static void __read_persistent_clock(struct timespec *ts)
726 {
727 	struct rtc_time tm;
728 	static int first = 1;
729 
730 	ts->tv_nsec = 0;
731 	/* XXX this is a litle fragile but will work okay in the short term */
732 	if (first) {
733 		first = 0;
734 		if (ppc_md.time_init)
735 			timezone_offset = ppc_md.time_init();
736 
737 		/* get_boot_time() isn't guaranteed to be safe to call late */
738 		if (ppc_md.get_boot_time) {
739 			ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
740 			return;
741 		}
742 	}
743 	if (!ppc_md.get_rtc_time) {
744 		ts->tv_sec = 0;
745 		return;
746 	}
747 	ppc_md.get_rtc_time(&tm);
748 
749 	ts->tv_sec = mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
750 			    tm.tm_hour, tm.tm_min, tm.tm_sec);
751 }
752 
753 void read_persistent_clock(struct timespec *ts)
754 {
755 	__read_persistent_clock(ts);
756 
757 	/* Sanitize it in case real time clock is set below EPOCH */
758 	if (ts->tv_sec < 0) {
759 		ts->tv_sec = 0;
760 		ts->tv_nsec = 0;
761 	}
762 
763 }
764 
765 /* clocksource code */
766 static cycle_t rtc_read(struct clocksource *cs)
767 {
768 	return (cycle_t)get_rtc();
769 }
770 
771 static cycle_t timebase_read(struct clocksource *cs)
772 {
773 	return (cycle_t)get_tb();
774 }
775 
776 void update_vsyscall_old(struct timespec *wall_time, struct timespec *wtm,
777 			 struct clocksource *clock, u32 mult, cycle_t cycle_last)
778 {
779 	u64 new_tb_to_xs, new_stamp_xsec;
780 	u32 frac_sec;
781 
782 	if (clock != &clocksource_timebase)
783 		return;
784 
785 	/* Make userspace gettimeofday spin until we're done. */
786 	++vdso_data->tb_update_count;
787 	smp_mb();
788 
789 	/* 19342813113834067 ~= 2^(20+64) / 1e9 */
790 	new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
791 	new_stamp_xsec = (u64) wall_time->tv_nsec * XSEC_PER_SEC;
792 	do_div(new_stamp_xsec, 1000000000);
793 	new_stamp_xsec += (u64) wall_time->tv_sec * XSEC_PER_SEC;
794 
795 	BUG_ON(wall_time->tv_nsec >= NSEC_PER_SEC);
796 	/* this is tv_nsec / 1e9 as a 0.32 fraction */
797 	frac_sec = ((u64) wall_time->tv_nsec * 18446744073ULL) >> 32;
798 
799 	/*
800 	 * tb_update_count is used to allow the userspace gettimeofday code
801 	 * to assure itself that it sees a consistent view of the tb_to_xs and
802 	 * stamp_xsec variables.  It reads the tb_update_count, then reads
803 	 * tb_to_xs and stamp_xsec and then reads tb_update_count again.  If
804 	 * the two values of tb_update_count match and are even then the
805 	 * tb_to_xs and stamp_xsec values are consistent.  If not, then it
806 	 * loops back and reads them again until this criteria is met.
807 	 * We expect the caller to have done the first increment of
808 	 * vdso_data->tb_update_count already.
809 	 */
810 	vdso_data->tb_orig_stamp = cycle_last;
811 	vdso_data->stamp_xsec = new_stamp_xsec;
812 	vdso_data->tb_to_xs = new_tb_to_xs;
813 	vdso_data->wtom_clock_sec = wtm->tv_sec;
814 	vdso_data->wtom_clock_nsec = wtm->tv_nsec;
815 	vdso_data->stamp_xtime = *wall_time;
816 	vdso_data->stamp_sec_fraction = frac_sec;
817 	smp_wmb();
818 	++(vdso_data->tb_update_count);
819 }
820 
821 void update_vsyscall_tz(void)
822 {
823 	vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
824 	vdso_data->tz_dsttime = sys_tz.tz_dsttime;
825 }
826 
827 static void __init clocksource_init(void)
828 {
829 	struct clocksource *clock;
830 
831 	if (__USE_RTC())
832 		clock = &clocksource_rtc;
833 	else
834 		clock = &clocksource_timebase;
835 
836 	if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
837 		printk(KERN_ERR "clocksource: %s is already registered\n",
838 		       clock->name);
839 		return;
840 	}
841 
842 	printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
843 	       clock->name, clock->mult, clock->shift);
844 }
845 
846 static int decrementer_set_next_event(unsigned long evt,
847 				      struct clock_event_device *dev)
848 {
849 	__this_cpu_write(decrementers_next_tb, get_tb_or_rtc() + evt);
850 	set_dec(evt);
851 
852 	/* We may have raced with new irq work */
853 	if (test_irq_work_pending())
854 		set_dec(1);
855 
856 	return 0;
857 }
858 
859 static void decrementer_set_mode(enum clock_event_mode mode,
860 				 struct clock_event_device *dev)
861 {
862 	if (mode != CLOCK_EVT_MODE_ONESHOT)
863 		decrementer_set_next_event(DECREMENTER_MAX, dev);
864 }
865 
866 /* Interrupt handler for the timer broadcast IPI */
867 void tick_broadcast_ipi_handler(void)
868 {
869 	u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
870 
871 	*next_tb = get_tb_or_rtc();
872 	__timer_interrupt();
873 }
874 
875 static void register_decrementer_clockevent(int cpu)
876 {
877 	struct clock_event_device *dec = &per_cpu(decrementers, cpu);
878 
879 	*dec = decrementer_clockevent;
880 	dec->cpumask = cpumask_of(cpu);
881 
882 	printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
883 		    dec->name, dec->mult, dec->shift, cpu);
884 
885 	clockevents_register_device(dec);
886 }
887 
888 static void __init init_decrementer_clockevent(void)
889 {
890 	int cpu = smp_processor_id();
891 
892 	clockevents_calc_mult_shift(&decrementer_clockevent, ppc_tb_freq, 4);
893 
894 	decrementer_clockevent.max_delta_ns =
895 		clockevent_delta2ns(DECREMENTER_MAX, &decrementer_clockevent);
896 	decrementer_clockevent.min_delta_ns =
897 		clockevent_delta2ns(2, &decrementer_clockevent);
898 
899 	register_decrementer_clockevent(cpu);
900 }
901 
902 void secondary_cpu_time_init(void)
903 {
904 	/* Start the decrementer on CPUs that have manual control
905 	 * such as BookE
906 	 */
907 	start_cpu_decrementer();
908 
909 	/* FIME: Should make unrelatred change to move snapshot_timebase
910 	 * call here ! */
911 	register_decrementer_clockevent(smp_processor_id());
912 }
913 
914 /* This function is only called on the boot processor */
915 void __init time_init(void)
916 {
917 	struct div_result res;
918 	u64 scale;
919 	unsigned shift;
920 
921 	if (__USE_RTC()) {
922 		/* 601 processor: dec counts down by 128 every 128ns */
923 		ppc_tb_freq = 1000000000;
924 	} else {
925 		/* Normal PowerPC with timebase register */
926 		ppc_md.calibrate_decr();
927 		printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
928 		       ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
929 		printk(KERN_DEBUG "time_init: processor frequency   = %lu.%.6lu MHz\n",
930 		       ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
931 	}
932 
933 	tb_ticks_per_jiffy = ppc_tb_freq / HZ;
934 	tb_ticks_per_sec = ppc_tb_freq;
935 	tb_ticks_per_usec = ppc_tb_freq / 1000000;
936 	calc_cputime_factors();
937 	setup_cputime_one_jiffy();
938 
939 	/*
940 	 * Compute scale factor for sched_clock.
941 	 * The calibrate_decr() function has set tb_ticks_per_sec,
942 	 * which is the timebase frequency.
943 	 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
944 	 * the 128-bit result as a 64.64 fixed-point number.
945 	 * We then shift that number right until it is less than 1.0,
946 	 * giving us the scale factor and shift count to use in
947 	 * sched_clock().
948 	 */
949 	div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
950 	scale = res.result_low;
951 	for (shift = 0; res.result_high != 0; ++shift) {
952 		scale = (scale >> 1) | (res.result_high << 63);
953 		res.result_high >>= 1;
954 	}
955 	tb_to_ns_scale = scale;
956 	tb_to_ns_shift = shift;
957 	/* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
958 	boot_tb = get_tb_or_rtc();
959 
960 	/* If platform provided a timezone (pmac), we correct the time */
961 	if (timezone_offset) {
962 		sys_tz.tz_minuteswest = -timezone_offset / 60;
963 		sys_tz.tz_dsttime = 0;
964 	}
965 
966 	vdso_data->tb_update_count = 0;
967 	vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
968 
969 	/* Start the decrementer on CPUs that have manual control
970 	 * such as BookE
971 	 */
972 	start_cpu_decrementer();
973 
974 	/* Register the clocksource */
975 	clocksource_init();
976 
977 	init_decrementer_clockevent();
978 	tick_setup_hrtimer_broadcast();
979 
980 #ifdef CONFIG_COMMON_CLK
981 	of_clk_init(NULL);
982 #endif
983 }
984 
985 
986 #define FEBRUARY	2
987 #define	STARTOFTIME	1970
988 #define SECDAY		86400L
989 #define SECYR		(SECDAY * 365)
990 #define	leapyear(year)		((year) % 4 == 0 && \
991 				 ((year) % 100 != 0 || (year) % 400 == 0))
992 #define	days_in_year(a) 	(leapyear(a) ? 366 : 365)
993 #define	days_in_month(a) 	(month_days[(a) - 1])
994 
995 static int month_days[12] = {
996 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
997 };
998 
999 /*
1000  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
1001  */
1002 void GregorianDay(struct rtc_time * tm)
1003 {
1004 	int leapsToDate;
1005 	int lastYear;
1006 	int day;
1007 	int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
1008 
1009 	lastYear = tm->tm_year - 1;
1010 
1011 	/*
1012 	 * Number of leap corrections to apply up to end of last year
1013 	 */
1014 	leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
1015 
1016 	/*
1017 	 * This year is a leap year if it is divisible by 4 except when it is
1018 	 * divisible by 100 unless it is divisible by 400
1019 	 *
1020 	 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
1021 	 */
1022 	day = tm->tm_mon > 2 && leapyear(tm->tm_year);
1023 
1024 	day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
1025 		   tm->tm_mday;
1026 
1027 	tm->tm_wday = day % 7;
1028 }
1029 EXPORT_SYMBOL_GPL(GregorianDay);
1030 
1031 void to_tm(int tim, struct rtc_time * tm)
1032 {
1033 	register int    i;
1034 	register long   hms, day;
1035 
1036 	day = tim / SECDAY;
1037 	hms = tim % SECDAY;
1038 
1039 	/* Hours, minutes, seconds are easy */
1040 	tm->tm_hour = hms / 3600;
1041 	tm->tm_min = (hms % 3600) / 60;
1042 	tm->tm_sec = (hms % 3600) % 60;
1043 
1044 	/* Number of years in days */
1045 	for (i = STARTOFTIME; day >= days_in_year(i); i++)
1046 		day -= days_in_year(i);
1047 	tm->tm_year = i;
1048 
1049 	/* Number of months in days left */
1050 	if (leapyear(tm->tm_year))
1051 		days_in_month(FEBRUARY) = 29;
1052 	for (i = 1; day >= days_in_month(i); i++)
1053 		day -= days_in_month(i);
1054 	days_in_month(FEBRUARY) = 28;
1055 	tm->tm_mon = i;
1056 
1057 	/* Days are what is left over (+1) from all that. */
1058 	tm->tm_mday = day + 1;
1059 
1060 	/*
1061 	 * Determine the day of week
1062 	 */
1063 	GregorianDay(tm);
1064 }
1065 EXPORT_SYMBOL(to_tm);
1066 
1067 /*
1068  * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1069  * result.
1070  */
1071 void div128_by_32(u64 dividend_high, u64 dividend_low,
1072 		  unsigned divisor, struct div_result *dr)
1073 {
1074 	unsigned long a, b, c, d;
1075 	unsigned long w, x, y, z;
1076 	u64 ra, rb, rc;
1077 
1078 	a = dividend_high >> 32;
1079 	b = dividend_high & 0xffffffff;
1080 	c = dividend_low >> 32;
1081 	d = dividend_low & 0xffffffff;
1082 
1083 	w = a / divisor;
1084 	ra = ((u64)(a - (w * divisor)) << 32) + b;
1085 
1086 	rb = ((u64) do_div(ra, divisor) << 32) + c;
1087 	x = ra;
1088 
1089 	rc = ((u64) do_div(rb, divisor) << 32) + d;
1090 	y = rb;
1091 
1092 	do_div(rc, divisor);
1093 	z = rc;
1094 
1095 	dr->result_high = ((u64)w << 32) + x;
1096 	dr->result_low  = ((u64)y << 32) + z;
1097 
1098 }
1099 
1100 /* We don't need to calibrate delay, we use the CPU timebase for that */
1101 void calibrate_delay(void)
1102 {
1103 	/* Some generic code (such as spinlock debug) use loops_per_jiffy
1104 	 * as the number of __delay(1) in a jiffy, so make it so
1105 	 */
1106 	loops_per_jiffy = tb_ticks_per_jiffy;
1107 }
1108 
1109 static int __init rtc_init(void)
1110 {
1111 	struct platform_device *pdev;
1112 
1113 	if (!ppc_md.get_rtc_time)
1114 		return -ENODEV;
1115 
1116 	pdev = platform_device_register_simple("rtc-generic", -1, NULL, 0);
1117 
1118 	return PTR_ERR_OR_ZERO(pdev);
1119 }
1120 
1121 module_init(rtc_init);
1122