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