2 * Common time routines among all ppc machines.
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)
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).
15 * Speeded up do_gettimeofday by getting rid of references to
16 * xtime (which required locks for consistency). (mikejc@us.ibm.com)
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.
25 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
26 * "A Kernel Model for Precision Timekeeping" by Dave Mills
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.
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>
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 <linux/rtc.h>
60 #include <linux/cputime.h>
61 #include <asm/trace.h>
64 #include <asm/processor.h>
65 #include <asm/nvram.h>
66 #include <asm/cache.h>
67 #include <asm/machdep.h>
68 #include <linux/uaccess.h>
72 #include <asm/div64.h>
74 #include <asm/vdso_datapage.h>
75 #include <asm/firmware.h>
76 #include <asm/asm-prototypes.h>
78 /* powerpc clocksource/clockevent code */
80 #include <linux/clockchips.h>
81 #include <linux/timekeeper_internal.h>
83 static u64 rtc_read(struct clocksource *);
84 static struct clocksource clocksource_rtc = {
87 .flags = CLOCK_SOURCE_IS_CONTINUOUS,
88 .mask = CLOCKSOURCE_MASK(64),
92 static u64 timebase_read(struct clocksource *);
93 static struct clocksource clocksource_timebase = {
96 .flags = CLOCK_SOURCE_IS_CONTINUOUS,
97 .mask = CLOCKSOURCE_MASK(64),
98 .read = timebase_read,
101 #define DECREMENTER_DEFAULT_MAX 0x7FFFFFFF
102 u64 decrementer_max = DECREMENTER_DEFAULT_MAX;
104 static int decrementer_set_next_event(unsigned long evt,
105 struct clock_event_device *dev);
106 static int decrementer_shutdown(struct clock_event_device *evt);
108 struct clock_event_device decrementer_clockevent = {
109 .name = "decrementer",
112 .set_next_event = decrementer_set_next_event,
113 .set_state_shutdown = decrementer_shutdown,
114 .tick_resume = decrementer_shutdown,
115 .features = CLOCK_EVT_FEAT_ONESHOT |
116 CLOCK_EVT_FEAT_C3STOP,
118 EXPORT_SYMBOL(decrementer_clockevent);
120 DEFINE_PER_CPU(u64, decrementers_next_tb);
121 static DEFINE_PER_CPU(struct clock_event_device, decrementers);
123 #define XSEC_PER_SEC (1024*1024)
126 #define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
128 /* compute ((xsec << 12) * max) >> 32 */
129 #define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
132 unsigned long tb_ticks_per_jiffy;
133 unsigned long tb_ticks_per_usec = 100; /* sane default */
134 EXPORT_SYMBOL(tb_ticks_per_usec);
135 unsigned long tb_ticks_per_sec;
136 EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
138 DEFINE_SPINLOCK(rtc_lock);
139 EXPORT_SYMBOL_GPL(rtc_lock);
141 static u64 tb_to_ns_scale __read_mostly;
142 static unsigned tb_to_ns_shift __read_mostly;
143 static u64 boot_tb __read_mostly;
145 extern struct timezone sys_tz;
146 static long timezone_offset;
148 unsigned long ppc_proc_freq;
149 EXPORT_SYMBOL_GPL(ppc_proc_freq);
150 unsigned long ppc_tb_freq;
151 EXPORT_SYMBOL_GPL(ppc_tb_freq);
153 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
155 * Factor for converting from cputime_t (timebase ticks) to
156 * microseconds. This is stored as 0.64 fixed-point binary fraction.
158 u64 __cputime_usec_factor;
159 EXPORT_SYMBOL(__cputime_usec_factor);
161 #ifdef CONFIG_PPC_SPLPAR
162 void (*dtl_consumer)(struct dtl_entry *, u64);
166 #define get_accounting(tsk) (&get_paca()->accounting)
168 #define get_accounting(tsk) (&task_thread_info(tsk)->accounting)
171 static void calc_cputime_factors(void)
173 struct div_result res;
175 div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
176 __cputime_usec_factor = res.result_low;
180 * Read the SPURR on systems that have it, otherwise the PURR,
181 * or if that doesn't exist return the timebase value passed in.
183 static unsigned long read_spurr(unsigned long tb)
185 if (cpu_has_feature(CPU_FTR_SPURR))
186 return mfspr(SPRN_SPURR);
187 if (cpu_has_feature(CPU_FTR_PURR))
188 return mfspr(SPRN_PURR);
192 #ifdef CONFIG_PPC_SPLPAR
195 * Scan the dispatch trace log and count up the stolen time.
196 * Should be called with interrupts disabled.
198 static u64 scan_dispatch_log(u64 stop_tb)
200 u64 i = local_paca->dtl_ridx;
201 struct dtl_entry *dtl = local_paca->dtl_curr;
202 struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
203 struct lppaca *vpa = local_paca->lppaca_ptr;
211 if (i == be64_to_cpu(vpa->dtl_idx))
213 while (i < be64_to_cpu(vpa->dtl_idx)) {
214 dtb = be64_to_cpu(dtl->timebase);
215 tb_delta = be32_to_cpu(dtl->enqueue_to_dispatch_time) +
216 be32_to_cpu(dtl->ready_to_enqueue_time);
218 if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
219 /* buffer has overflowed */
220 i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
221 dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
227 dtl_consumer(dtl, i);
232 dtl = local_paca->dispatch_log;
234 local_paca->dtl_ridx = i;
235 local_paca->dtl_curr = dtl;
240 * Accumulate stolen time by scanning the dispatch trace log.
241 * Called on entry from user mode.
243 void accumulate_stolen_time(void)
246 u8 save_soft_enabled = local_paca->soft_enabled;
247 struct cpu_accounting_data *acct = &local_paca->accounting;
249 /* We are called early in the exception entry, before
250 * soft/hard_enabled are sync'ed to the expected state
251 * for the exception. We are hard disabled but the PACA
252 * needs to reflect that so various debug stuff doesn't
255 local_paca->soft_enabled = 0;
257 sst = scan_dispatch_log(acct->starttime_user);
258 ust = scan_dispatch_log(acct->starttime);
261 acct->steal_time += ust + sst;
263 local_paca->soft_enabled = save_soft_enabled;
266 static inline u64 calculate_stolen_time(u64 stop_tb)
268 if (get_paca()->dtl_ridx != be64_to_cpu(get_lppaca()->dtl_idx))
269 return scan_dispatch_log(stop_tb);
274 #else /* CONFIG_PPC_SPLPAR */
275 static inline u64 calculate_stolen_time(u64 stop_tb)
280 #endif /* CONFIG_PPC_SPLPAR */
283 * Account time for a transition between system, hard irq
286 static unsigned long vtime_delta(struct task_struct *tsk,
287 unsigned long *stime_scaled,
288 unsigned long *steal_time)
290 unsigned long now, nowscaled, deltascaled;
292 unsigned long utime, utime_scaled;
293 struct cpu_accounting_data *acct = get_accounting(tsk);
295 WARN_ON_ONCE(!irqs_disabled());
298 nowscaled = read_spurr(now);
299 stime = now - acct->starttime;
300 acct->starttime = now;
301 deltascaled = nowscaled - acct->startspurr;
302 acct->startspurr = nowscaled;
304 *steal_time = calculate_stolen_time(now);
306 utime = acct->utime - acct->utime_sspurr;
307 acct->utime_sspurr = acct->utime;
310 * Because we don't read the SPURR on every kernel entry/exit,
311 * deltascaled includes both user and system SPURR ticks.
312 * Apportion these ticks to system SPURR ticks and user
313 * SPURR ticks in the same ratio as the system time (delta)
314 * and user time (udelta) values obtained from the timebase
315 * over the same interval. The system ticks get accounted here;
316 * the user ticks get saved up in paca->user_time_scaled to be
317 * used by account_process_tick.
319 *stime_scaled = stime;
320 utime_scaled = utime;
321 if (deltascaled != stime + utime) {
323 *stime_scaled = deltascaled * stime / (stime + utime);
324 utime_scaled = deltascaled - *stime_scaled;
326 *stime_scaled = deltascaled;
329 acct->utime_scaled += utime_scaled;
334 void vtime_account_system(struct task_struct *tsk)
336 unsigned long stime, stime_scaled, steal_time;
337 struct cpu_accounting_data *acct = get_accounting(tsk);
339 stime = vtime_delta(tsk, &stime_scaled, &steal_time);
341 stime -= min(stime, steal_time);
342 acct->steal_time += steal_time;
344 if ((tsk->flags & PF_VCPU) && !irq_count()) {
345 acct->gtime += stime;
346 acct->utime_scaled += stime_scaled;
349 acct->hardirq_time += stime;
350 else if (in_serving_softirq())
351 acct->softirq_time += stime;
353 acct->stime += stime;
355 acct->stime_scaled += stime_scaled;
358 EXPORT_SYMBOL_GPL(vtime_account_system);
360 void vtime_account_idle(struct task_struct *tsk)
362 unsigned long stime, stime_scaled, steal_time;
363 struct cpu_accounting_data *acct = get_accounting(tsk);
365 stime = vtime_delta(tsk, &stime_scaled, &steal_time);
366 acct->idle_time += stime + steal_time;
370 * Account the whole cputime accumulated in the paca
371 * Must be called with interrupts disabled.
372 * Assumes that vtime_account_system/idle() has been called
373 * recently (i.e. since the last entry from usermode) so that
374 * get_paca()->user_time_scaled is up to date.
376 void vtime_flush(struct task_struct *tsk)
378 struct cpu_accounting_data *acct = get_accounting(tsk);
381 account_user_time(tsk, cputime_to_nsecs(acct->utime));
383 if (acct->utime_scaled)
384 tsk->utimescaled += cputime_to_nsecs(acct->utime_scaled);
387 account_guest_time(tsk, cputime_to_nsecs(acct->gtime));
389 if (acct->steal_time)
390 account_steal_time(cputime_to_nsecs(acct->steal_time));
393 account_idle_time(cputime_to_nsecs(acct->idle_time));
396 account_system_index_time(tsk, cputime_to_nsecs(acct->stime),
398 if (acct->stime_scaled)
399 tsk->stimescaled += cputime_to_nsecs(acct->stime_scaled);
401 if (acct->hardirq_time)
402 account_system_index_time(tsk, cputime_to_nsecs(acct->hardirq_time),
404 if (acct->softirq_time)
405 account_system_index_time(tsk, cputime_to_nsecs(acct->softirq_time),
409 acct->utime_scaled = 0;
410 acct->utime_sspurr = 0;
412 acct->steal_time = 0;
415 acct->stime_scaled = 0;
416 acct->hardirq_time = 0;
417 acct->softirq_time = 0;
422 * Called from the context switch with interrupts disabled, to charge all
423 * accumulated times to the current process, and to prepare accounting on
426 void arch_vtime_task_switch(struct task_struct *prev)
428 struct cpu_accounting_data *acct = get_accounting(current);
430 acct->starttime = get_accounting(prev)->starttime;
431 acct->startspurr = get_accounting(prev)->startspurr;
433 #endif /* CONFIG_PPC32 */
435 #else /* ! CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
436 #define calc_cputime_factors()
439 void __delay(unsigned long loops)
447 /* the RTCL register wraps at 1000000000 */
448 diff = get_rtcl() - start;
451 } while (diff < loops);
454 while (get_tbl() - start < loops)
459 EXPORT_SYMBOL(__delay);
461 void udelay(unsigned long usecs)
463 __delay(tb_ticks_per_usec * usecs);
465 EXPORT_SYMBOL(udelay);
468 unsigned long profile_pc(struct pt_regs *regs)
470 unsigned long pc = instruction_pointer(regs);
472 if (in_lock_functions(pc))
477 EXPORT_SYMBOL(profile_pc);
480 #ifdef CONFIG_IRQ_WORK
483 * 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
486 static inline unsigned long test_irq_work_pending(void)
490 asm volatile("lbz %0,%1(13)"
492 : "i" (offsetof(struct paca_struct, irq_work_pending)));
496 static inline void set_irq_work_pending_flag(void)
498 asm volatile("stb %0,%1(13)" : :
500 "i" (offsetof(struct paca_struct, irq_work_pending)));
503 static inline void clear_irq_work_pending(void)
505 asm volatile("stb %0,%1(13)" : :
507 "i" (offsetof(struct paca_struct, irq_work_pending)));
512 DEFINE_PER_CPU(u8, irq_work_pending);
514 #define set_irq_work_pending_flag() __this_cpu_write(irq_work_pending, 1)
515 #define test_irq_work_pending() __this_cpu_read(irq_work_pending)
516 #define clear_irq_work_pending() __this_cpu_write(irq_work_pending, 0)
518 #endif /* 32 vs 64 bit */
520 void arch_irq_work_raise(void)
523 set_irq_work_pending_flag();
528 #else /* CONFIG_IRQ_WORK */
530 #define test_irq_work_pending() 0
531 #define clear_irq_work_pending()
533 #endif /* CONFIG_IRQ_WORK */
535 static void __timer_interrupt(void)
537 struct pt_regs *regs = get_irq_regs();
538 u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
539 struct clock_event_device *evt = this_cpu_ptr(&decrementers);
542 trace_timer_interrupt_entry(regs);
544 if (test_irq_work_pending()) {
545 clear_irq_work_pending();
549 now = get_tb_or_rtc();
550 if (now >= *next_tb) {
552 if (evt->event_handler)
553 evt->event_handler(evt);
554 __this_cpu_inc(irq_stat.timer_irqs_event);
556 now = *next_tb - now;
557 if (now <= decrementer_max)
559 /* We may have raced with new irq work */
560 if (test_irq_work_pending())
562 __this_cpu_inc(irq_stat.timer_irqs_others);
566 /* collect purr register values often, for accurate calculations */
567 if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
568 struct cpu_usage *cu = this_cpu_ptr(&cpu_usage_array);
569 cu->current_tb = mfspr(SPRN_PURR);
573 trace_timer_interrupt_exit(regs);
577 * timer_interrupt - gets called when the decrementer overflows,
578 * with interrupts disabled.
580 void timer_interrupt(struct pt_regs * regs)
582 struct pt_regs *old_regs;
583 u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
585 /* Ensure a positive value is written to the decrementer, or else
586 * some CPUs will continue to take decrementer exceptions.
588 set_dec(decrementer_max);
590 /* Some implementations of hotplug will get timer interrupts while
591 * offline, just ignore these and we also need to set
592 * decrementers_next_tb as MAX to make sure __check_irq_replay
593 * don't replay timer interrupt when return, otherwise we'll trap
596 if (!cpu_online(smp_processor_id())) {
601 /* Conditionally hard-enable interrupts now that the DEC has been
602 * bumped to its maximum value
604 may_hard_irq_enable();
607 #if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
608 if (atomic_read(&ppc_n_lost_interrupts) != 0)
612 old_regs = set_irq_regs(regs);
617 set_irq_regs(old_regs);
619 EXPORT_SYMBOL(timer_interrupt);
622 * Hypervisor decrementer interrupts shouldn't occur but are sometimes
623 * left pending on exit from a KVM guest. We don't need to do anything
624 * to clear them, as they are edge-triggered.
626 void hdec_interrupt(struct pt_regs *regs)
630 #ifdef CONFIG_SUSPEND
631 static void generic_suspend_disable_irqs(void)
633 /* Disable the decrementer, so that it doesn't interfere
637 set_dec(decrementer_max);
639 set_dec(decrementer_max);
642 static void generic_suspend_enable_irqs(void)
647 /* Overrides the weak version in kernel/power/main.c */
648 void arch_suspend_disable_irqs(void)
650 if (ppc_md.suspend_disable_irqs)
651 ppc_md.suspend_disable_irqs();
652 generic_suspend_disable_irqs();
655 /* Overrides the weak version in kernel/power/main.c */
656 void arch_suspend_enable_irqs(void)
658 generic_suspend_enable_irqs();
659 if (ppc_md.suspend_enable_irqs)
660 ppc_md.suspend_enable_irqs();
664 unsigned long long tb_to_ns(unsigned long long ticks)
666 return mulhdu(ticks, tb_to_ns_scale) << tb_to_ns_shift;
668 EXPORT_SYMBOL_GPL(tb_to_ns);
671 * Scheduler clock - returns current time in nanosec units.
673 * Note: mulhdu(a, b) (multiply high double unsigned) returns
674 * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
675 * are 64-bit unsigned numbers.
677 unsigned long long sched_clock(void)
681 return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
685 #ifdef CONFIG_PPC_PSERIES
688 * Running clock - attempts to give a view of time passing for a virtualised
690 * Uses the VTB register if available otherwise a next best guess.
692 unsigned long long running_clock(void)
695 * Don't read the VTB as a host since KVM does not switch in host
696 * timebase into the VTB when it takes a guest off the CPU, reading the
697 * VTB would result in reading 'last switched out' guest VTB.
699 * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
700 * would be unsafe to rely only on the #ifdef above.
702 if (firmware_has_feature(FW_FEATURE_LPAR) &&
703 cpu_has_feature(CPU_FTR_ARCH_207S))
704 return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
707 * This is a next best approximation without a VTB.
708 * On a host which is running bare metal there should never be any stolen
709 * time and on a host which doesn't do any virtualisation TB *should* equal
710 * VTB so it makes no difference anyway.
712 return local_clock() - kcpustat_this_cpu->cpustat[CPUTIME_STEAL];
716 static int __init get_freq(char *name, int cells, unsigned long *val)
718 struct device_node *cpu;
722 /* The cpu node should have timebase and clock frequency properties */
723 cpu = of_find_node_by_type(NULL, "cpu");
726 fp = of_get_property(cpu, name, NULL);
729 *val = of_read_ulong(fp, cells);
738 static void start_cpu_decrementer(void)
740 #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
741 /* Clear any pending timer interrupts */
742 mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
744 /* Enable decrementer interrupt */
745 mtspr(SPRN_TCR, TCR_DIE);
746 #endif /* defined(CONFIG_BOOKE) || defined(CONFIG_40x) */
749 void __init generic_calibrate_decr(void)
751 ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
753 if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
754 !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
756 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
760 ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
762 if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
763 !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
765 printk(KERN_ERR "WARNING: Estimating processor frequency "
770 int update_persistent_clock(struct timespec now)
774 if (!ppc_md.set_rtc_time)
777 to_tm(now.tv_sec + 1 + timezone_offset, &tm);
781 return ppc_md.set_rtc_time(&tm);
784 static void __read_persistent_clock(struct timespec *ts)
787 static int first = 1;
790 /* XXX this is a litle fragile but will work okay in the short term */
793 if (ppc_md.time_init)
794 timezone_offset = ppc_md.time_init();
796 /* get_boot_time() isn't guaranteed to be safe to call late */
797 if (ppc_md.get_boot_time) {
798 ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
802 if (!ppc_md.get_rtc_time) {
806 ppc_md.get_rtc_time(&tm);
808 ts->tv_sec = mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
809 tm.tm_hour, tm.tm_min, tm.tm_sec);
812 void read_persistent_clock(struct timespec *ts)
814 __read_persistent_clock(ts);
816 /* Sanitize it in case real time clock is set below EPOCH */
817 if (ts->tv_sec < 0) {
824 /* clocksource code */
825 static u64 rtc_read(struct clocksource *cs)
827 return (u64)get_rtc();
830 static u64 timebase_read(struct clocksource *cs)
832 return (u64)get_tb();
835 void update_vsyscall_old(struct timespec *wall_time, struct timespec *wtm,
836 struct clocksource *clock, u32 mult, u64 cycle_last)
838 u64 new_tb_to_xs, new_stamp_xsec;
841 if (clock != &clocksource_timebase)
844 /* Make userspace gettimeofday spin until we're done. */
845 ++vdso_data->tb_update_count;
848 /* 19342813113834067 ~= 2^(20+64) / 1e9 */
849 new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
850 new_stamp_xsec = (u64) wall_time->tv_nsec * XSEC_PER_SEC;
851 do_div(new_stamp_xsec, 1000000000);
852 new_stamp_xsec += (u64) wall_time->tv_sec * XSEC_PER_SEC;
854 BUG_ON(wall_time->tv_nsec >= NSEC_PER_SEC);
855 /* this is tv_nsec / 1e9 as a 0.32 fraction */
856 frac_sec = ((u64) wall_time->tv_nsec * 18446744073ULL) >> 32;
859 * tb_update_count is used to allow the userspace gettimeofday code
860 * to assure itself that it sees a consistent view of the tb_to_xs and
861 * stamp_xsec variables. It reads the tb_update_count, then reads
862 * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
863 * the two values of tb_update_count match and are even then the
864 * tb_to_xs and stamp_xsec values are consistent. If not, then it
865 * loops back and reads them again until this criteria is met.
866 * We expect the caller to have done the first increment of
867 * vdso_data->tb_update_count already.
869 vdso_data->tb_orig_stamp = cycle_last;
870 vdso_data->stamp_xsec = new_stamp_xsec;
871 vdso_data->tb_to_xs = new_tb_to_xs;
872 vdso_data->wtom_clock_sec = wtm->tv_sec;
873 vdso_data->wtom_clock_nsec = wtm->tv_nsec;
874 vdso_data->stamp_xtime = *wall_time;
875 vdso_data->stamp_sec_fraction = frac_sec;
877 ++(vdso_data->tb_update_count);
880 void update_vsyscall_tz(void)
882 vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
883 vdso_data->tz_dsttime = sys_tz.tz_dsttime;
886 static void __init clocksource_init(void)
888 struct clocksource *clock;
891 clock = &clocksource_rtc;
893 clock = &clocksource_timebase;
895 if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
896 printk(KERN_ERR "clocksource: %s is already registered\n",
901 printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
902 clock->name, clock->mult, clock->shift);
905 static int decrementer_set_next_event(unsigned long evt,
906 struct clock_event_device *dev)
908 __this_cpu_write(decrementers_next_tb, get_tb_or_rtc() + evt);
911 /* We may have raced with new irq work */
912 if (test_irq_work_pending())
918 static int decrementer_shutdown(struct clock_event_device *dev)
920 decrementer_set_next_event(decrementer_max, dev);
924 /* Interrupt handler for the timer broadcast IPI */
925 void tick_broadcast_ipi_handler(void)
927 u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
929 *next_tb = get_tb_or_rtc();
933 static void register_decrementer_clockevent(int cpu)
935 struct clock_event_device *dec = &per_cpu(decrementers, cpu);
937 *dec = decrementer_clockevent;
938 dec->cpumask = cpumask_of(cpu);
940 printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
941 dec->name, dec->mult, dec->shift, cpu);
943 clockevents_register_device(dec);
946 static void enable_large_decrementer(void)
948 if (!cpu_has_feature(CPU_FTR_ARCH_300))
951 if (decrementer_max <= DECREMENTER_DEFAULT_MAX)
955 * If we're running as the hypervisor we need to enable the LD manually
956 * otherwise firmware should have done it for us.
958 if (cpu_has_feature(CPU_FTR_HVMODE))
959 mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) | LPCR_LD);
962 static void __init set_decrementer_max(void)
964 struct device_node *cpu;
967 /* Prior to ISAv3 the decrementer is always 32 bit */
968 if (!cpu_has_feature(CPU_FTR_ARCH_300))
971 cpu = of_find_node_by_type(NULL, "cpu");
973 if (of_property_read_u32(cpu, "ibm,dec-bits", &bits) == 0) {
974 if (bits > 64 || bits < 32) {
975 pr_warn("time_init: firmware supplied invalid ibm,dec-bits");
979 /* calculate the signed maximum given this many bits */
980 decrementer_max = (1ul << (bits - 1)) - 1;
985 pr_info("time_init: %u bit decrementer (max: %llx)\n",
986 bits, decrementer_max);
989 static void __init init_decrementer_clockevent(void)
991 int cpu = smp_processor_id();
993 clockevents_calc_mult_shift(&decrementer_clockevent, ppc_tb_freq, 4);
995 decrementer_clockevent.max_delta_ns =
996 clockevent_delta2ns(decrementer_max, &decrementer_clockevent);
997 decrementer_clockevent.min_delta_ns =
998 clockevent_delta2ns(2, &decrementer_clockevent);
1000 register_decrementer_clockevent(cpu);
1003 void secondary_cpu_time_init(void)
1005 /* Enable and test the large decrementer for this cpu */
1006 enable_large_decrementer();
1008 /* Start the decrementer on CPUs that have manual control
1011 start_cpu_decrementer();
1013 /* FIME: Should make unrelatred change to move snapshot_timebase
1015 register_decrementer_clockevent(smp_processor_id());
1018 /* This function is only called on the boot processor */
1019 void __init time_init(void)
1021 struct div_result res;
1026 /* 601 processor: dec counts down by 128 every 128ns */
1027 ppc_tb_freq = 1000000000;
1029 /* Normal PowerPC with timebase register */
1030 ppc_md.calibrate_decr();
1031 printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
1032 ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
1033 printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
1034 ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
1037 tb_ticks_per_jiffy = ppc_tb_freq / HZ;
1038 tb_ticks_per_sec = ppc_tb_freq;
1039 tb_ticks_per_usec = ppc_tb_freq / 1000000;
1040 calc_cputime_factors();
1043 * Compute scale factor for sched_clock.
1044 * The calibrate_decr() function has set tb_ticks_per_sec,
1045 * which is the timebase frequency.
1046 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
1047 * the 128-bit result as a 64.64 fixed-point number.
1048 * We then shift that number right until it is less than 1.0,
1049 * giving us the scale factor and shift count to use in
1052 div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
1053 scale = res.result_low;
1054 for (shift = 0; res.result_high != 0; ++shift) {
1055 scale = (scale >> 1) | (res.result_high << 63);
1056 res.result_high >>= 1;
1058 tb_to_ns_scale = scale;
1059 tb_to_ns_shift = shift;
1060 /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
1061 boot_tb = get_tb_or_rtc();
1063 /* If platform provided a timezone (pmac), we correct the time */
1064 if (timezone_offset) {
1065 sys_tz.tz_minuteswest = -timezone_offset / 60;
1066 sys_tz.tz_dsttime = 0;
1069 vdso_data->tb_update_count = 0;
1070 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
1072 /* initialise and enable the large decrementer (if we have one) */
1073 set_decrementer_max();
1074 enable_large_decrementer();
1076 /* Start the decrementer on CPUs that have manual control
1079 start_cpu_decrementer();
1081 /* Register the clocksource */
1084 init_decrementer_clockevent();
1085 tick_setup_hrtimer_broadcast();
1087 #ifdef CONFIG_COMMON_CLK
1094 #define STARTOFTIME 1970
1095 #define SECDAY 86400L
1096 #define SECYR (SECDAY * 365)
1097 #define leapyear(year) ((year) % 4 == 0 && \
1098 ((year) % 100 != 0 || (year) % 400 == 0))
1099 #define days_in_year(a) (leapyear(a) ? 366 : 365)
1100 #define days_in_month(a) (month_days[(a) - 1])
1102 static int month_days[12] = {
1103 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
1106 void to_tm(int tim, struct rtc_time * tm)
1109 register long hms, day;
1114 /* Hours, minutes, seconds are easy */
1115 tm->tm_hour = hms / 3600;
1116 tm->tm_min = (hms % 3600) / 60;
1117 tm->tm_sec = (hms % 3600) % 60;
1119 /* Number of years in days */
1120 for (i = STARTOFTIME; day >= days_in_year(i); i++)
1121 day -= days_in_year(i);
1124 /* Number of months in days left */
1125 if (leapyear(tm->tm_year))
1126 days_in_month(FEBRUARY) = 29;
1127 for (i = 1; day >= days_in_month(i); i++)
1128 day -= days_in_month(i);
1129 days_in_month(FEBRUARY) = 28;
1132 /* Days are what is left over (+1) from all that. */
1133 tm->tm_mday = day + 1;
1136 * No-one uses the day of the week.
1140 EXPORT_SYMBOL(to_tm);
1143 * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1146 void div128_by_32(u64 dividend_high, u64 dividend_low,
1147 unsigned divisor, struct div_result *dr)
1149 unsigned long a, b, c, d;
1150 unsigned long w, x, y, z;
1153 a = dividend_high >> 32;
1154 b = dividend_high & 0xffffffff;
1155 c = dividend_low >> 32;
1156 d = dividend_low & 0xffffffff;
1159 ra = ((u64)(a - (w * divisor)) << 32) + b;
1161 rb = ((u64) do_div(ra, divisor) << 32) + c;
1164 rc = ((u64) do_div(rb, divisor) << 32) + d;
1167 do_div(rc, divisor);
1170 dr->result_high = ((u64)w << 32) + x;
1171 dr->result_low = ((u64)y << 32) + z;
1175 /* We don't need to calibrate delay, we use the CPU timebase for that */
1176 void calibrate_delay(void)
1178 /* Some generic code (such as spinlock debug) use loops_per_jiffy
1179 * as the number of __delay(1) in a jiffy, so make it so
1181 loops_per_jiffy = tb_ticks_per_jiffy;
1184 #if IS_ENABLED(CONFIG_RTC_DRV_GENERIC)
1185 static int rtc_generic_get_time(struct device *dev, struct rtc_time *tm)
1187 ppc_md.get_rtc_time(tm);
1188 return rtc_valid_tm(tm);
1191 static int rtc_generic_set_time(struct device *dev, struct rtc_time *tm)
1193 if (!ppc_md.set_rtc_time)
1196 if (ppc_md.set_rtc_time(tm) < 0)
1202 static const struct rtc_class_ops rtc_generic_ops = {
1203 .read_time = rtc_generic_get_time,
1204 .set_time = rtc_generic_set_time,
1207 static int __init rtc_init(void)
1209 struct platform_device *pdev;
1211 if (!ppc_md.get_rtc_time)
1214 pdev = platform_device_register_data(NULL, "rtc-generic", -1,
1216 sizeof(rtc_generic_ops));
1218 return PTR_ERR_OR_ZERO(pdev);
1221 device_initcall(rtc_init);